{"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file rk_3_3.c\n * \\brief Source file to optimize Runge-Kutta 3 steps 3rd order methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"rk.h\"\n#include \"rk_3_3.h\"\n\n#define DEBUG_RK_3_3 0 ///< macro to debug.\n\n/**\n * Function to obtain the coefficients of a 3 steps 3rd order Runge-Kutta \n * method.\n */\nint\nrk_tb_3_3 (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb, *r;\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_tb_3_3: start\\n\");\n#endif\n tb = optimize->coefficient;\n r = optimize->random_data;\n t3 (tb) = 1.L;\n t1 (tb) = r[0];\n t2 (tb) = r[1];\n b32 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb)));\n if (isnan (b32 (tb)))\n return 0;\n b31 (tb) = (1.L / 3.L - 0.5L * t2 (tb)) / (t1 (tb) * (t1 (tb) - t2 (tb)));\n if (isnan (b31 (tb)))\n return 0;\n b21 (tb) = 1 / 6.L / (b32 (tb) * t1 (tb));\n if (isnan (b21 (tb)))\n return 0;\n rk_b_3 (tb);\n#if DEBUG_RK_3_3\n rk_print_tb (optimize, \"rk_tb_3_3\", stderr);\n fprintf (stderr, \"rk_tb_3_3: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 3 steps 3rd order, 4th order in\n * equations depending only in time, Runge-Kutta method.\n */\nint\nrk_tb_3_3t (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb, *r;\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_tb_3_3t: start\\n\");\n#endif\n tb = optimize->coefficient;\n r = optimize->random_data;\n t3 (tb) = 1.L;\n t1 (tb) = r[0];\n t2 (tb) = (4.L * t1 (tb) - 3.L) / (6.L * t1 (tb) - 4.L);\n if (isnan (t2 (tb)))\n return 0;\n b32 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb)));\n if ((b32 (tb)))\n return 0;\n b31 (tb) = (1.L / 3.L - 0.5L * t2 (tb)) / (t1 (tb) * (t1 (tb) - t2 (tb)));\n if (isnan (b31 (tb)))\n return 0;\n b21 (tb) = 1 / 6.L / (b32 (tb) * t1 (tb));\n if (isnan (b21 (tb)))\n return 0;\n rk_b_3 (tb);\n#if DEBUG_RK_3_3\n rk_print_tb (optimize, \"rk_tb_3_3t\", stderr);\n fprintf (stderr, \"rk_tb_3_3t: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 3 steps 2nd-3rd order Runge-Kutta \n * pair.\n */\nint\nrk_tb_3_3p (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb;\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_tb_3_3p: start\\n\");\n#endif\n if (!rk_tb_3_3 (optimize))\n return 0;\n tb = optimize->coefficient;\n e31 (tb) = 0.5L / t1 (tb);\n rk_e_3 (tb);\n#if DEBUG_RK_3_3\n rk_print_e (optimize, \"rk_tb_3_3p\", stderr);\n fprintf (stderr, \"rk_tb_3_3p: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 3 steps 2nd-3rd order, 2nd-4th order\n * in equations depending only in time, Runge-Kutta pair.\n */\nint\nrk_tb_3_3tp (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb;\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_tb_3_3tp: start\\n\");\n#endif\n if (!rk_tb_3_3t (optimize))\n return 0;\n tb = optimize->coefficient;\n e31 (tb) = 0.5L / t1 (tb);\n rk_e_3 (tb);\n#if DEBUG_RK_3_3\n rk_print_e (optimize, \"rk_tb_3_3tp\", stderr);\n fprintf (stderr, \"rk_tb_3_3tp: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to calculate the objective function of a 3 steps 3rd order \n * Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_3_3 (RK * rk) ///< RK struct.\n{\n long double *tb;\n long double o;\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_objective_tb_3_3: start\\n\");\n#endif\n tb = rk->tb->coefficient;\n o = fminl (0.L, b20 (tb));\n if (b21 (tb) < 0.L)\n o += b21 (tb);\n if (b30 (tb) < 0.L)\n o += b30 (tb);\n if (b31 (tb) < 0.L)\n o += b31 (tb);\n if (b32 (tb) < 0.L)\n o += b32 (tb);\n if (o < 0.L)\n {\n o = 40.L - o;\n goto end;\n }\n o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb)));\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\nend:\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_objective_tb_3_3: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_3_3: end\\n\");\n#endif\n return o;\n}\n\n/**\n * Function to calculate the objective function of a 3 steps 3rd order, 4th\n * order in equations depending only in time, Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_3_3t (RK * rk) ///< RK struct.\n{\n long double *tb;\n long double o;\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_objective_tb_3_3t: start\\n\");\n#endif\n tb = rk->tb->coefficient;\n o = fminl (0.L, b20 (tb));\n if (b21 (tb) < 0.L)\n o += b21 (tb);\n if (b30 (tb) < 0.L)\n o += b30 (tb);\n if (b31 (tb) < 0.L)\n o += b31 (tb);\n if (b32 (tb) < 0.L)\n o += b32 (tb);\n if (o < 0.L)\n {\n o = 40.L - o;\n goto end;\n }\n o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb)));\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_objective_tb_3_3: optimal=%Lg\\n\", o);\n#endif\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\nend:\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_objective_tb_3_3t: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_3_3t: end\\n\");\n#endif\n return o;\n}\n\n/**\n * Function to calculate the objective function of a 3 steps 2nd-3rd order \n * Runge-Kutta pair.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_3_3p (RK * rk) ///< RK struct.\n{\n long double *tb;\n long double o;\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_objective_tb_3_3p: start\\n\");\n#endif\n tb = rk->tb->coefficient;\n o = fminl (0.L, b20 (tb));\n if (b21 (tb) < 0.L)\n o += b21 (tb);\n if (b30 (tb) < 0.L)\n o += b30 (tb);\n if (b31 (tb) < 0.L)\n o += b31 (tb);\n if (b32 (tb) < 0.L)\n o += b32 (tb);\n if (e30 (tb) < 0.L)\n o += e30 (tb);\n if (o < 0.L)\n {\n o = 40.L - o;\n goto end;\n }\n o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb)));\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\nend:\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_objective_tb_3_3p: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_3_3p: end\\n\");\n#endif\n return o;\n}\n\n/**\n * Function to calculate the objective function of a 3 steps 2nd-3rd order, \n * 3rd-4th order in equations depending only in time, Runge-Kutta pair.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_3_3tp (RK * rk) ///< RK struct.\n{\n long double *tb;\n long double o;\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_objective_tb_3_3tp: start\\n\");\n#endif\n tb = rk->tb->coefficient;\n o = fminl (0.L, b20 (tb));\n if (b21 (tb) < 0.L)\n o += b21 (tb);\n if (b30 (tb) < 0.L)\n o += b30 (tb);\n if (b31 (tb) < 0.L)\n o += b31 (tb);\n if (b32 (tb) < 0.L)\n o += b32 (tb);\n if (e30 (tb) < 0.L)\n o += e30 (tb);\n if (o < 0.L)\n {\n o = 40.L - o;\n goto end;\n }\n o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb)));\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_objective_tb_3_3p: optimal=%Lg\\n\", o);\n#endif\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\nend:\n#if DEBUG_RK_3_3\n fprintf (stderr, \"rk_objective_tb_3_3tp: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_3_3tp: end\\n\");\n#endif\n return o;\n}\n", "meta": {"hexsha": "85be9a9d042873a2d2d600fdf1d39113cf7423c2", "size": 8588, "ext": "c", "lang": "C", "max_stars_repo_path": "rk_3_3.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rk_3_3.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rk_3_3.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9651162791, "max_line_length": 80, "alphanum_fraction": 0.6207498836, "num_tokens": 3147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4499293228092998}} {"text": "/////////////////////////////////////////////////////////////////////\n// = NMatrix\n//\n// A linear algebra library for scientific computation in Ruby.\n// NMatrix is part of SciRuby.\n//\n// NMatrix was originally inspired by and derived from NArray, by\n// Masahiro Tanaka: http://narray.rubyforge.org\n//\n// == Copyright Information\n//\n// SciRuby is Copyright (c) 2010 - 2014, Ruby Science Foundation\n// NMatrix is Copyright (c) 2012 - 2014, John Woods and the Ruby Science Foundation\n//\n// Please see LICENSE.txt for additional copyright notices.\n//\n// == Contributing\n//\n// By contributing source code to SciRuby, you agree to be bound by\n// our Contributor Agreement:\n//\n// * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement\n//\n// == getrs.h\n//\n// getrs function in native C++.\n//\n\n/*\n * Automatically Tuned Linear Algebra Software v3.8.4\n * (C) Copyright 1999 R. Clint Whaley\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions, and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. The name of the ATLAS group or the names of its contributers may\n * not be used to endorse or promote products derived from this\n * software without specific written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ATLAS GROUP OR ITS CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#ifndef POTRS_H\n#define POTRS_H\n\nextern \"C\" {\n#if defined HAVE_CBLAS_H\n #include \n#elif defined HAVE_ATLAS_CBLAS_H\n #include \n#endif\n}\n\nnamespace nm { namespace math {\n\n/*\n * Solves a system of linear equations A*X = B with a symmetric positive definite matrix A using the Cholesky factorization computed by POTRF.\n *\n * From ATLAS 3.8.0.\n */\ntemplate \nint potrs(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const int N, const int NRHS, const DType* A,\n const int lda, DType* B, const int ldb)\n{\n // enum CBLAS_DIAG Lunit, Uunit; // These aren't used. Not sure why they're declared in ATLAS' src.\n\n CBLAS_TRANSPOSE MyTrans = is_complex ? CblasConjTrans : CblasTrans;\n\n if (!N || !NRHS) return 0;\n\n const DType ONE = 1;\n\n if (Order == CblasColMajor) {\n if (Uplo == CblasUpper) {\n nm::math::trsm(Order, CblasLeft, CblasUpper, MyTrans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb);\n nm::math::trsm(Order, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb);\n } else {\n nm::math::trsm(Order, CblasLeft, CblasLower, CblasNoTrans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb);\n nm::math::trsm(Order, CblasLeft, CblasLower, MyTrans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb);\n }\n } else {\n // There's some kind of scaling operation that normally happens here in ATLAS. Not sure what it does, so we'll only\n // worry if something breaks. It probably has to do with their non-templated code and doesn't apply to us.\n\n if (Uplo == CblasUpper) {\n nm::math::trsm(Order, CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb);\n nm::math::trsm(Order, CblasRight, CblasUpper, MyTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb);\n } else {\n nm::math::trsm(Order, CblasRight, CblasLower, MyTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb);\n nm::math::trsm(Order, CblasRight, CblasLower, CblasNoTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb);\n }\n }\n return 0;\n}\n\n\n/*\n* Function signature conversion for calling LAPACK's potrs functions as directly as possible.\n*\n* For documentation: http://www.netlib.org/lapack/double/dpotrs.f\n*\n* This function should normally go in math.cpp, but we need it to be available to nmatrix.cpp.\n*/\ntemplate \ninline int clapack_potrs(const enum CBLAS_ORDER order, const enum CBLAS_UPLO uplo, const int n, const int nrhs,\n const void* a, const int lda, void* b, const int ldb) {\n return potrs(order, uplo, n, nrhs, reinterpret_cast(a), lda, reinterpret_cast(b), ldb);\n}\n\n\n} } // end nm::math\n\n#endif // POTRS_H\n", "meta": {"hexsha": "6bc62ce49c2ab269973b63617d4c5a31d2d1697a", "size": 5234, "ext": "h", "lang": "C", "max_stars_repo_path": "ext/nmatrix/math/potrs.h", "max_stars_repo_name": "blackwinter-attic/nmatrix", "max_stars_repo_head_hexsha": "cb2cd26195d544ac03b347e293c071faed6f90a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ext/nmatrix/math/potrs.h", "max_issues_repo_name": "blackwinter-attic/nmatrix", "max_issues_repo_head_hexsha": "cb2cd26195d544ac03b347e293c071faed6f90a6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ext/nmatrix/math/potrs.h", "max_forks_repo_name": "blackwinter-attic/nmatrix", "max_forks_repo_head_hexsha": "cb2cd26195d544ac03b347e293c071faed6f90a6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2615384615, "max_line_length": 142, "alphanum_fraction": 0.6975544517, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4496652533861534}} {"text": "\n/*\n* -----------------------------------------------------------------\n* ODE Solver Library --- ode_lib.h\n* Version: 1.6180\n* Date: Feb 19, 2010\n* ----------------------------------------------------------------- \n* Programmer: Americo Barbosa da Cunha Junior\n* americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n* Copyright (c) 2010 by Americo Barbosa da Cunha Junior\n*\n* This program is free software: you can redistribute it and/or\n* modify it under the terms of the GNU General Public License as\n* published by the Free Software Foundation, either version 3 of\n* the License, or (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* A copy of the GNU General Public License is available in\n* LICENSE.txt or http://www.gnu.org/licenses/.\n* -----------------------------------------------------------------\n* This is the header file for a library\n* with the ODE solution tools.\n* -----------------------------------------------------------------\n*/\n\n\n\n#ifndef __ODESOLVER_LIB_H__\n#define __ODESOLVER_LIB_H__\n\n\n#include \n#include \n#include \n\n\n#undef RTOL\n#define RTOL 1.0e-6\n\n#undef ATOL\n#define ATOL 1.0e-15\n\n\n\n\n/*\n*------------------------------------------------------------\n* function prototypes\n*------------------------------------------------------------\n*/\n\ndouble uround(void);\n\ndouble wnorm(int n,\n double *v1,\n double *v2);\n\nvoid ewtset(int n,\n double *v,\n double atol,\n double rtol,\n double *ewt);\n\nint jacobian(CVRhsFn f,\n void *f_data,\n gsl_vector *Fx,\n gsl_vector *x,\n double t,\n double atol,\n double rtol,\n gsl_matrix *J);\n\nint gradient(CVRhsFn f,\n void *f_data,\n void *cvode_mem,\n double t0,\n double delta_t,\n double atol,\n double rtol,\n gsl_vector *phi,\n gsl_vector *Rphi,\n gsl_matrix *A);\n\nvoid linear_approx(gsl_vector *x,\n gsl_vector *x0,\n gsl_vector *Fx0,\n gsl_matrix *DFx0,\n gsl_vector *Fx);\n\nint odesolver_init(CVRhsFn f,\n void *data,\n double t0,\n int mxsteps,\n\t\t double atol,\n double rtol,\n gsl_vector *x,\n void *cvode_mem);\n\nint odesolver_reinit(CVRhsFn f,\n void *f_data,\n double t0,\n\t\t double atol,\n double rtol,\n gsl_vector *x,\n void *cvode_mem);\n\nint odesolver(void *cvode_mem,\n double tf,\n gsl_vector *Fx);\n\n\n#endif /* __ODESOLVER_LIB_H__ */\n", "meta": {"hexsha": "8c122e981c9a357ea57dccd3d3ccf5b17c8811a4", "size": 3118, "ext": "h", "lang": "C", "max_stars_repo_path": "CRFlowLib-1.0/include/ode_lib.h", "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_issues_repo_path": "CRFlowLib-1.0/include/ode_lib.h", "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRFlowLib-1.0/include/ode_lib.h", "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "avg_line_length": 26.4237288136, "max_line_length": 68, "alphanum_fraction": 0.4749839641, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228891883799, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.44956393543014067}} {"text": "#include \n#include \n#if !defined(__APPLE__)\n#include \n#endif\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"../cosmolike_core/theory/basics.c\"\n#include \"../cosmolike_core/theory/structs.c\"\n#include \"../cosmolike_core/theory/parameters.c\"\n#include \"../cosmolike_core/emu17/P_cb/emu.c\"\n#include \"../cosmolike_core/theory/recompute.c\"\n#include \"../cosmolike_core/theory/cosmo3D.c\"\n#include \"../cosmolike_core/theory/redshift.c\"\n#include \"../cosmolike_core/theory/halo.c\"\n#include \"../cosmolike_core/theory/HOD.c\"\n#include \"../cosmolike_core/theory/cosmo2D_fourier.c\"\n#include \"../cosmolike_core/theory/IA.c\"\n#include \"../cosmolike_core/theory/cluster.c\"\n#include \"../cosmolike_core/theory/BAO.c\"\n#include \"../cosmolike_core/theory/external_prior.c\"\n#include \"../cosmolike_core/theory/covariances_3D.c\"\n#include \"../cosmolike_core/theory/covariances_fourier.c\"\n#include \"../cosmolike_core/theory/covariances_cluster.c\"\n#include \"init_SRD.c\"\n\nvoid run_cov_N_N (char *OUTFILE, char *PATH, int nzc1, int nzc2,int start);\nvoid run_cov_cgl_N (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int nzc2, int start);\nvoid run_cov_cgl_cgl (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int start);\nvoid run_cov_cgl_cgl_all (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster);\nvoid run_cov_shear_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start);\nvoid run_cov_shear_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start);\nvoid run_cov_ggl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start);\nvoid run_cov_ggl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start);\nvoid run_cov_cl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start);\nvoid run_cov_cl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start);\n\nvoid run_cov_ggl_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_clustering_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_clustering_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_clustering(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_shear_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\n\n\nvoid run_cov_N_N (char *OUTFILE, char *PATH, int nzc1, int nzc2,int start)\n{\n int nN1, nN2,i,j;\n double cov;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n i += Cluster.N200_Nbin*nzc1+nN1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n j += Cluster.N200_Nbin*nzc2+nN2;\n\n cov =cov_N_N(nzc1,nN1, nzc2, nN2);\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,0.0,0.0, nzc1, nN1, nzc2, nN2,cov,0.0);\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_cgl_N (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int nzc2, int start)\n{\n int nN1, nN2, nl1, nzc1, nzs1,i,j;\n double cov;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n nzc1 = ZC(N1);\n nzs1 = ZSC(N1);\n for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){\n for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n j += Cluster.N200_Nbin*nzc2+nN2;\n\n cov =cov_cgl_N(ell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2);\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j, ell_Cluster[nl1], 0., nzc1, nzs1, nzc2, nN2,cov,0.);\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_cgl_cgl (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int start)\n{\n int nN1, nN2, nl1, nzc1, nzs1, nl2, nzc2, nzs2,i,j;\n double c_g, c_ng;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n nzc1 = ZC(N1);\n nzs1 = ZSC(N1);\n nzc2 = ZC(N2);\n nzs2 = ZSC(N2);\n for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){\n for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2;\n\n c_g = 0;\n c_ng = cov_NG_cgl_cgl(ell_Cluster[nl1],ell_Cluster[nl2],nzc1,nN1, nzs1, nzc2, nN2,nzs2);\n if (nl2 == nl1){c_g =cov_G_cgl_cgl(ell_Cluster[nl1],dell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2,nzs2);}\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell_Cluster[nl1],ell_Cluster[nl2], nzc1, nzs1, nzc2, nzs2,c_g, c_ng);\n }\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_cgl_cgl_all (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster)\n{\n int nN1, nN2, nl1, nzc1, nzs1, nl2, nzc2, nzs2,i,j, N1,N2;\n double c_g, c_ng;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s\",PATH,OUTFILE);\n F1 =fopen(filename,\"w\");\n for (N1 = 0; N1 < tomo.cgl_Npowerspectra; N1 ++){\n for (N2 = 0; N2 < tomo.cgl_Npowerspectra; N2 ++){\n nzc1 = ZC(N1);\n nzs1 = ZSC(N1);\n nzc2 = ZC(N2);\n nzs2 = ZSC(N2);\n for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){\n for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2; \n c_g = 0;\n c_ng = cov_NG_cgl_cgl(ell_Cluster[nl1],ell_Cluster[nl2],nzc1,nN1, nzs1, nzc2, nN2,nzs2);\n if (nl2 == nl1){c_g =cov_G_cgl_cgl(ell_Cluster[nl1],dell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2,nzs2);}\n fprintf(F1,\"%d %d %e %e %d %d %d %d %d %d %e %e\\n\",i,j,ell_Cluster[nl1],ell_Cluster[nl2], nzc1, nN1,nzs1, nzc2, nN2,nzs2,c_g, c_ng);\n }\n }\n }\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_shear_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start)\n{\n int nz1,nz2, nN2, nl1, nzc1, i,j;\n double cov;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n nz1 = Z1(N1);\n nz2 = Z2(N1);\n for( nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n cov = 0.;\n i = like.Ncl*N1+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n j += Cluster.N200_Nbin*nzc2+nN2;\n\n if (ell[nl1] < like.lmax_shear){cov =cov_shear_N(ell[nl1],nz1,nz2, nzc2, nN2);}\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j, ell[nl1], 0., nz1, nz2, nzc2, nN2,cov,0.);\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_shear_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start)\n{\n int nN1, nN2, nzs1, nzs2,nl2, nzc2, nzs3,i,j;\n double c_g, c_ng;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n nzs1 = Z1(N1);\n nzs2 = Z2(N1);\n nzc2 = ZC(N2);\n nzs3 = ZSC(N2);\n for(nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){\n i = like.Ncl*N1+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2; \n c_g = 0.;\n c_ng = 0.;\n if (ell[nl1] < like.lmax_shear){\n c_ng = cov_NG_shear_cgl(ell[nl1],ell_Cluster[nl2],nzs1, nzs2, nzc2, nN2,nzs3);\n if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.001){ \n c_g =cov_G_shear_cgl(ell[nl1],dell_Cluster[nl2],nzs1,nzs2, nzc2, nN2,nzs3);\n }\n }\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell[nl1],ell_Cluster[nl2], nzs1, nzs2, nzc2, nzs3,c_g, c_ng);\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_ggl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start)\n{\n int zl,zs, nN2, nl1, nzc1, i,j;\n double cov,weight;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n zl = ZL(N1);\n zs = ZS(N1);\n for( nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+N1)+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n j += Cluster.N200_Nbin*nzc2+nN2;\n cov = 0.;\n weight = test_kmax(ell[nl1],zl);\n if (weight){\n cov =cov_ggl_N(ell[nl1],zl,zs, nzc2, nN2);\n }\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j, ell[nl1], 0., zl, zs, nzc2, nN2,cov,0.);\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_ggl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start)\n{\n int nN2, zl, zs, nzs1, nl2, nzc2, nzs3,i,j;\n double c_g, c_ng,weight;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n zl = ZL(N1);\n zs = ZS(N1);\n nzc2 = ZC(N2);\n nzs3 = ZSC(N2);\n for(nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+N1)+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2;\n\n c_g = 0; c_ng = 0.;\n weight = test_kmax(ell[nl1],zl);\n if (weight){\n c_ng = cov_NG_ggl_cgl(ell[nl1],ell_Cluster[nl2],zl,zs, nzc2, nN2,nzs3);\n if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.1){c_g =cov_G_ggl_cgl(ell[nl1],dell_Cluster[nl2],zl,zs, nzc2, nN2,nzs3);}\n }\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell[nl1],ell_Cluster[nl2], zl, zs, nzc2, nzs3,c_g, c_ng);\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_cl_N (char *OUTFILE, char *PATH, double *ell, double *dell,int N1, int nzc2, int start)\n{\n int zl,zs, nN2, nl1, nzc1, i,j;\n double cov,weight;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n for( nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+N1)+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n j += Cluster.N200_Nbin*nzc2+nN2;\n cov = 0.;\n weight = test_kmax(ell[nl1],N1);\n if (weight){\n cov =cov_cl_N(ell[nl1],N1,N1,nzc2,nN2);\n }\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j, ell[nl1], 0., N1, N1, nzc2, nN2,cov,0.);\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_cl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start)\n{\n int nN2,nzc2, nzs3,i,j,nl2;\n double c_g, c_ng,weight;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n nzc2 = ZC(N2);\n nzs3 = ZSC(N2);\n for(nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+N1)+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2;\n\n c_g = 0; c_ng = 0.;\n weight = test_kmax(ell[nl1],N1);\n if (weight){\n c_ng = cov_NG_cl_cgl(ell[nl1],ell_Cluster[nl2],N1,N1, nzc2, nN2,nzs3);\n if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.1){\n c_g =cov_G_cl_cgl(ell[nl1],dell_Cluster[nl2],N1,N1, nzc2, nN2,nzs3);\n }\n }\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell[nl1],ell_Cluster[nl2], N1,N1, nzc2, nzs3,c_g, c_ng);\n //printf(\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell[nl1],ell_Cluster[nl2], N1,N1, nzc2, nzs3,c_g, c_ng);\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_ggl_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start)\n{\n int zl,zs,z3,z4,nl1,nl2,weight;\n double c_ng, c_g;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\"); \n zl = ZL(n1); zs = ZS(n1);\n printf(\"\\nN_ggl = %d (%d, %d)\\n\", n1,zl,zs);\n z3 = Z1(n2); z4 = Z2(n2);\n printf(\"N_shear = %d (%d, %d)\\n\", n2,z3,z4);\n for (nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nl2 = 0; nl2 like.lmax_shear && n1!=n2){c_g = 0.;} \n } \n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",like.Ncl*n1+nl1,like.Ncl*(n2)+nl2,ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng);\n //printf(\"%d %d %e %e %d %d %d %d %e %e\\n\", like.Ncl*n1+nl1,like.Ncl*(n2)+nl2, ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng);\n }\n }\n fclose(F1);\n}\n\n\nint main(int argc, char** argv)\n{\n \n int i,l,m,n,o,s,p,nl1,t,k;\n char OUTFILE[400],filename[400],arg1[400],arg2[400];\n \n int N_scenarios=12;\n double area_table[12]={7500.0,13000.0,16000.0,10000.0,15000.0,20000.0,10000.0,15000.0,20000.0,10000.0,15000.0,20000.0};\n double nsource_table[12]={9.8,12.1,15.1,15.1,18.9,23.5,20.3,23.5,26.9,26.9,30.8,35.0};\n double nlens_table[12]={15.0,20.0,25.0,25.0,32.0,41.0,35.0,41.0,48.0,48.0,57.0,67.0};\n \n char survey_designation[12][200]={\"LSST_Y1\",\"LSST_Y1\",\"LSST_Y1\",\"LSST_Y3\",\"LSST_Y3\",\"LSST_Y3\",\"LSST_Y6\",\"LSST_Y6\",\"LSST_Y6\",\"LSST_Y10\",\"LSST_Y10\",\"LSST_Y10\"};\n char source_zfile[12][400]={\"WL_zdistri_model0_z0=1.940000e-01_alpha=8.830000e-01\",\"WL_zdistri_model1_z0=1.900000e-01_alpha=8.620000e-01\",\"WL_zdistri_model2_z0=1.860000e-01_alpha=8.410000e-01\",\"WL_zdistri_model3_z0=1.860000e-01_alpha=8.410000e-01\",\"WL_zdistri_model4_z0=1.830000e-01_alpha=8.210000e-01\",\"WL_zdistri_model5_z0=1.790000e-01_alpha=8.000000e-01\",\"WL_zdistri_model6_z0=1.810000e-01_alpha=8.140000e-01\",\"WL_zdistri_model7_z0=1.790000e-01_alpha=8.000000e-01\",\"WL_zdistri_model8_z0=1.760000e-01_alpha=7.860000e-01\",\"WL_zdistri_model9_z0=1.760000e-01_alpha=7.860000e-01\",\"WL_zdistri_model10_z0=1.740000e-01_alpha=7.720000e-01\",\"WL_zdistri_model11_z0=1.710000e-01_alpha=7.590000e-01\"};\n char lens_zfile[12][400]={\"LSS_zdistri_model0_z0=2.590000e-01_alpha=9.520000e-01\",\"LSS_zdistri_model1_z0=2.610000e-01_alpha=9.370000e-01\",\"LSS_zdistri_model2_z0=2.640000e-01_alpha=9.250000e-01\",\"LSS_zdistri_model3_z0=2.640000e-01_alpha=9.250000e-01\",\"LSS_zdistri_model4_z0=2.680000e-01_alpha=9.150000e-01\",\"LSS_zdistri_model5_z0=2.740000e-01_alpha=9.070000e-01\",\"LSS_zdistri_model6_z0=2.700000e-01_alpha=9.120000e-01\",\"LSS_zdistri_model7_z0=2.740000e-01_alpha=9.070000e-01\",\"LSS_zdistri_model8_z0=2.780000e-01_alpha=9.030000e-01\",\"LSS_zdistri_model9_z0=2.780000e-01_alpha=9.030000e-01\",\"LSS_zdistri_model10_z0=2.830000e-01_alpha=9.000000e-01\",\"LSS_zdistri_model11_z0=2.880000e-01_alpha=8.980000e-01\"};\n \n int Ntomo_lens[12]={5,5,5,7,7,7,9,9,9,10,10,10};\n //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n // use this remapping only if files fail !!!!!!!!! \n //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n // int fail[5]={1134, 259, 497, 623, 718};\n // hit=fail[hit-1];\n //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n \n int hit=atoi(argv[1]);\n Ntable.N_a=20;\n k=1;\n \n for(t=0;t<1;t++){\n \n //RUN MODE setup\n init_cosmo();\n init_binning_fourier(20,20.0,15000.0,3000.0,21.0,5,Ntomo_lens[t]);\n init_survey(survey_designation[t]);\n sprintf(arg1,\"zdistris/%s\",source_zfile[t]);\n sprintf(arg2,\"zdistris/%s\",lens_zfile[t]); \n init_galaxies(arg1,arg2,\"none\",\"none\",\"source\");\n init_clusters();\n init_IA(\"none\", \"GAMA\"); \n init_probes(\"3x2pt_clusterN_clusterWL\");\n \n\n //set l-bins for shear, ggl, clustering, clusterWL\n double logdl=(log(like.lmax)-log(like.lmin))/like.Ncl;\n double *ell, *dell, *ell_Cluster, *dell_Cluster;\n ell=create_double_vector(0,like.Ncl-1);\n dell=create_double_vector(0,like.Ncl-1);\n ell_Cluster=create_double_vector(0,Cluster.lbin-1);\n dell_Cluster=create_double_vector(0,Cluster.lbin-1);\n int j=0;\n for(i=0;ilike.lmax_shear){\n ell_Cluster[j]=ell[i];\n dell_Cluster[j]=dell[i];\n printf(\"%le %le\\n\",ell[i],ell_Cluster[j]);\n j++;\n }\n } \n\n\n printf(\"----------------------------------\\n\"); \n survey.area=area_table[t];\n survey.n_gal=nsource_table[t];\n survey.n_lens=nlens_table[t]; \n \n sprintf(survey.name,\"%s_area%le_ng%le_nl%le\",survey_designation[t],survey.area,survey.n_gal,survey.n_lens);\n printf(\"area: %le n_source: %le n_lens: %le\\n\",survey.area,survey.n_gal,survey.n_lens);\n\n sprintf(covparams.outdir,\"/home/u17/timeifler/covparallel/\"); \n\n printf(\"----------------------------------\\n\"); \n sprintf(OUTFILE,\"%s_ssss_cov_Ncl%d_Ntomo%d\",survey.name,like.Ncl,tomo.shear_Nbin);\n for (l=0;l\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"brains.h\"\n\n\n/* \n * calculate (Fcon + ftrend)^Ag \n * \n */\nvoid calculate_con_rm(const void *pm)\n{\n int i, m;\n double fcon, A, Ag, ftrend, a0=0.0, tmp;\n double *pmodel = (double *)pm;\n\n A=exp(pmodel[idx_resp]);\n Ag=pmodel[idx_resp + 1];\n\n /* add different trend in continuum and emission */\n if(parset.flag_trend_diff > 0)\n {\n tmp = 0.0;\n for(m=1; m 0.0)\n {\n Fcon_rm[i] = A * pow(fcon, 1.0 + Ag);\n }\n else \n {\n Fcon_rm[i] = 0.0;\n }\n }\n }\n else \n {\n for(i=0; i clouds_tau[i])\n tau_min = clouds_tau[i];\n if(tau_max < clouds_tau[i])\n tau_max = clouds_tau[i];\n }\n\n dTransTau = (tau_max - tau_min)/(parset.n_tau - 1);\n for(i=0; i clouds_tau[i])\n tau_min = clouds_tau[i];\n if(tau_max < clouds_tau[i])\n tau_max = clouds_tau[i];\n }\n\n dTransTau = (tau_max - tau_min)/(parset.n_tau - 1);\n for(i=0; i= transv[n_vel-1]+dV)\n continue;\n idV = (V - transv[0])/dV;\n //trans2d[idt*n_vel + idV] += pow(1.0/r, 2.0*(1 + gam)) * weight;\n trans2d[idt*n_vel + idV] += clouds_weight[i];\n }\n }\n\n /* normalize transfer function */\n Anorm = 0.0;\n for(i=0; i\n#include \n#include \n#include \n\nint\nfunc (double t, const double y[], double f[],\n void *params)\n{\n double mu = *(double *)params;\n f[0] = y[1];\n f[1] = -y[0] - mu*y[1]*(y[0]*y[0] - 1);\n return GSL_SUCCESS;\n}\n\nint\njac (double t, const double y[], double *dfdy, \n double dfdt[], void *params)\n{\n double mu = *(double *)params;\n gsl_matrix_view dfdy_mat \n = gsl_matrix_view_array (dfdy, 2, 2);\n gsl_matrix * m = &dfdy_mat.matrix; \n gsl_matrix_set (m, 0, 0, 0.0);\n gsl_matrix_set (m, 0, 1, 1.0);\n gsl_matrix_set (m, 1, 0, -2.0*mu*y[0]*y[1] - 1.0);\n gsl_matrix_set (m, 1, 1, -mu*(y[0]*y[0] - 1.0));\n dfdt[0] = 0.0;\n dfdt[1] = 0.0;\n return GSL_SUCCESS;\n}\n\nint\nmain (void)\n{\n const gsl_odeiv_step_type * T \n = gsl_odeiv_step_rk8pd;\n\n gsl_odeiv_step * s \n = gsl_odeiv_step_alloc (T, 2);\n gsl_odeiv_control * c \n = gsl_odeiv_control_y_new (1e-6, 0.0);\n gsl_odeiv_evolve * e \n = gsl_odeiv_evolve_alloc (2);\n\n double mu = 10;\n gsl_odeiv_system sys = {func, jac, 2, &mu};\n\n double t = 0.0, t1 = 100.0;\n double h = 1e-6;\n double y[2] = { 1.0, 0.0 };\n\n while (t < t1)\n {\n int status = gsl_odeiv_evolve_apply (e, c, s,\n &sys, \n &t, t1,\n &h, y);\n\n if (status != GSL_SUCCESS)\n break;\n\n printf (\"%.5e %.5e %.5e\\n\", t, y[0], y[1]);\n }\n\n gsl_odeiv_evolve_free (e);\n gsl_odeiv_control_free (c);\n gsl_odeiv_step_free (s);\n return 0;\n}\n", "meta": {"hexsha": "8a8f79493e85d3a9ddd931896ea1f055df8e4975", "size": 1592, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/ode-initval.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/doc/examples/ode-initval.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/doc/examples/ode-initval.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 22.4225352113, "max_line_length": 52, "alphanum_fraction": 0.5408291457, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.44898257139995934}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n/*! \\file conduction.c\n* \\brief Computes conduction bases on an implicit diffusion solver\n*\n*/\n\n#ifdef CONDUCTION\n\n#define MAX_COND_ITER 25\n#define COND_ITER_ACCURACY 1.0e-4\n\nstatic struct conductiondata_in\n{\n MyDouble Pos[3];\n MyFloat Hsml;\n MyFloat Density;\n MyFloat Kappa;\n int NodeList[NODELISTLENGTH];\n}\n *ConductionDataIn, *ConductionDataGet;\n\n\nstatic struct conductiondata_out\n{\n MyFloat Out;\n MyFloat Sum;\n}\n *ConductionDataResult, *ConductionDataOut;\n\n\nstatic double *Energy, *EnergyOld;\nstatic double *Residual, *DVec, *QVec;\nstatic double *Kappa;\n\n\n/* we will use the conjugate gradient method to compute a solution\n of the implicitly formulate diffusion equation */\n/* Note: the conduction equation we solve is really formulated with u instead of T, i.e.\n the factor (gamma-1)*mu*mp/k_B that converts from T to u is implicitely absorbed in a \n redefinition of kappa */\n\nvoid conduction(void)\n{\n int i, iter;\n double delta0, delta1, alpha, beta, a3inv, dt, rel_change, loc_max_rel_change, glob_max_rel_change;\n double sumnew, sumold, sumtransfer, sumnew_tot, sumold_tot, sumtransfer_tot;\n\n if(ThisTask == 0)\n {\n printf(\"Start thermal conduction...\\n\");\n fflush(stdout);\n }\n\n Energy = (double *) mymalloc(N_gas * sizeof(double));\n EnergyOld = (double *) mymalloc(N_gas * sizeof(double));\n Residual = (double *) mymalloc(N_gas * sizeof(double));\n DVec = (double *) mymalloc(N_gas * sizeof(double));\n QVec = (double *) mymalloc(N_gas * sizeof(double));\n\n Kappa = (double *) mymalloc(N_gas * sizeof(double));\n\n\n if(All.ComovingIntegrationOn)\n a3inv = 1 / (All.Time * All.Time * All.Time);\n else\n a3inv = 1.0;\n\n\n dt = (All.Conduction_Ti_endstep - All.Conduction_Ti_begstep) * All.Timebase_interval;\n\n if(All.ComovingIntegrationOn)\n dt *= All.Time / hubble_function(All.Time);\n\n if(ThisTask == 0)\n {\n printf(\"dt=%g\\n\", dt);\n }\n\n /* First, let's compute the thermal energies per unit mass and \n conductivities for all particles */\n\n for(i = 0; i < N_gas; i++)\n {\n if(P[i].Type == 0)\n\t{\n\t /* this gives the thermal energy per unit mass for particle i */\n\t Energy[i] = EnergyOld[i] = SphP[i].Entropy *\n\t pow(SphP[i].d.Density * a3inv, GAMMA_MINUS1) / GAMMA_MINUS1;\n\n#ifdef CONDUCTION_CONSTANT\n\t Kappa[i] = All.ConductionCoeff;\n#else\n\t Kappa[i] = All.ConductionCoeff * pow(EnergyOld[i], 2.5);\n#ifdef CONDUCTION_SATURATION\n\t electron_free_path = All.ElectronFreePathFactor * Energy[i] * Energy[i] / (SphP[i].Density * a3inv);\n\t temp_scale_length =\n\t atime * fabs(smoothentr) / sqrt(gradentr[0] * gradentr[0] +\n\t\t\t\t\t gradentr[1] * gradentr[1] + gradentr[2] * gradentr[2]);\n\t Kappa[i] /= (1 + 4.2 * electron_free_path / temp_scale_length);\n#endif\n#endif\n\n#ifdef SFR\n\t if(SphP[i].Density * a3inv >= All.PhysDensThresh)\n\t Kappa[i] = 0;\n#endif\n\n\t /* we'll factor the timestep into the conductivities, for simplicity */\n\t Kappa[i] *= dt;\n\t}\n }\n\n\n\n /* Let's start the Conjugate Gradient Algorithm */\n\n /* Initialization */\n\n conduction_matrix_multiply(EnergyOld, Residual);\n\n for(i = 0; i < N_gas; i++)\n {\n if(P[i].Type == 0)\n\t{\n\t Residual[i] = EnergyOld[i] - Residual[i];\n\t DVec[i] = Residual[i];\n\t}\n }\n\n delta1 = conduction_vector_multiply(Residual, Residual);\n delta0 = delta1;\n\n iter = 0;\t\t\t/* iteration counter */\n glob_max_rel_change = 1 + COND_ITER_ACCURACY;\t/* to make sure that we enter the iteration */\n\n while(iter < MAX_COND_ITER && glob_max_rel_change > COND_ITER_ACCURACY && delta1 > 0)\n {\n conduction_matrix_multiply(DVec, QVec);\n\n alpha = delta1 / conduction_vector_multiply(DVec, QVec);\n\n for(i = 0, loc_max_rel_change = 0; i < N_gas; i++)\n\t{\n\t Energy[i] += alpha * DVec[i];\n\t Residual[i] -= alpha * QVec[i];\n\n\t rel_change = alpha * DVec[i] / Energy[i];\n\t if(loc_max_rel_change < rel_change)\n\t loc_max_rel_change = rel_change;\n\t}\n\n delta0 = delta1;\n delta1 = conduction_vector_multiply(Residual, Residual);\n\n beta = delta1 / delta0;\n\n for(i = 0; i < N_gas; i++)\n\tDVec[i] = Residual[i] + beta * DVec[i];\n\n iter++;\n\n\n MPI_Allreduce(&loc_max_rel_change, &glob_max_rel_change, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);\n\n if(ThisTask == 0)\n\t{\n\t printf(\"conduction iter=%d delta1=%g delta1/delta0=%g max-rel-change=%g\\n\",\n\t\t iter, delta1, delta1 / delta0, glob_max_rel_change);\n\t fflush(stdout);\n\t}\n }\n\n\n /* Now we have the solution vector in Energy[] */\n /* assign it to the entropies, and update the pressure */\n\n for(i = 0, sumnew = sumold = sumtransfer = 0; i < N_gas; i++)\n {\n if(P[i].Type == 0)\n\t{\n\t sumnew += P[i].Mass * Energy[i];\n\t sumold += P[i].Mass * EnergyOld[i];\n\t sumtransfer += P[i].Mass * fabs(Energy[i] - EnergyOld[i]);\n\n\t SphP[i].Entropy = Energy[i] / pow(SphP[i].d.Density * a3inv, GAMMA_MINUS1) * GAMMA_MINUS1;\n\t}\n }\n\n MPI_Allreduce(&sumnew, &sumnew_tot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n MPI_Allreduce(&sumold, &sumold_tot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n MPI_Allreduce(&sumtransfer, &sumtransfer_tot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n\n if(ThisTask == 0)\n {\n printf(\"\\nconduction finished. energy_before=%g energy_after=%g rel-change=%g rel-transfer=%g\\n\\n\",\n\t sumold_tot, sumnew_tot, (sumnew_tot - sumold_tot) / sumold_tot, sumtransfer_tot / sumold_tot);\n fflush(stdout);\n }\n\n myfree(Kappa);\n myfree(QVec);\n myfree(DVec);\n myfree(Residual);\n myfree(EnergyOld);\n myfree(Energy);\n}\n\n\ndouble conduction_vector_multiply(double *a, double *b)\n{\n int i;\n double sum, sumall;\n\n for(i = 0, sum = 0; i < N_gas; i++)\n if(P[i].Type == 0)\n sum += a[i] * b[i];\n\n MPI_Allreduce(&sum, &sumall, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n\n return sumall;\n}\n\n\nvoid conduction_matrix_multiply(double *in, double *out)\n{\n int i, j, k, ngrp, ndone, ndone_flag, dummy;\n int sendTask, recvTask, nexport, nimport, place;\n double *sum;\n\n\n /* allocate buffers to arrange communication */\n\n Ngblist = (int *) mymalloc(NumPart * sizeof(int));\n\n All.BunchSize =\n (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) +\n\t\t\t\t\t sizeof(struct conductiondata_in) +\n\t\t\t\t\t sizeof(struct conductiondata_out) +\n\t\t\t\t\t sizemax(sizeof(struct conductiondata_in),\n\t\t\t\t\t\t sizeof(struct conductiondata_out))));\n DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index));\n DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist));\n\n\n sum = (double *) mymalloc(N_gas * sizeof(double));\n\n\n i = 0;\t\t\t/* need to go over all gas particles */\n\n do\n {\n for(j = 0; j < NTask; j++)\n\t{\n\t Send_count[j] = 0;\n\t Exportflag[j] = -1;\n\t}\n\n /* do local particles and prepare export list */\n for(nexport = 0; i < N_gas; i++)\n\tif(P[i].Type == 0)\n\t {\n\t if(conduction_evaluate(i, 0, in, out, sum, &nexport, Send_count) < 0)\n\t break;\n\t }\n\n#ifdef MYSORT\n mysort_dataindex(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);\n#else\n qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);\n#endif\n\n MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);\n\n for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)\n\t{\n\t Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];\n\t nimport += Recv_count[j];\n\n\t if(j > 0)\n\t {\n\t Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];\n\t Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1];\n\t }\n\t}\n\n ConductionDataGet = (struct conductiondata_in *) mymalloc(nimport * sizeof(struct conductiondata_in));\n ConductionDataIn = (struct conductiondata_in *) mymalloc(nexport * sizeof(struct conductiondata_in));\n\n /* prepare particle data for export */\n\n for(j = 0; j < nexport; j++)\n\t{\n\t place = DataIndexTable[j].Index;\n\n\t for(k = 0; k < 3; k++)\n\t ConductionDataIn[j].Pos[k] = P[place].Pos[k];\n\n\t ConductionDataIn[j].Hsml = PPP[place].Hsml;\n\t ConductionDataIn[j].Density = SphP[place].d.Density;\n\t ConductionDataIn[j].Kappa = Kappa[place];\n\n\t memcpy(ConductionDataIn[j].NodeList,\n\t\t DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));\n\t}\n\n\n /* exchange particle data */\n for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t{\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\n\t if(recvTask < NTask)\n\t {\n\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t{\n\t\t /* get the particles */\n\t\t MPI_Sendrecv(&ConductionDataIn[Send_offset[recvTask]],\n\t\t\t Send_count[recvTask] * sizeof(struct conductiondata_in), MPI_BYTE,\n\t\t\t recvTask, TAG_HYDRO_A,\n\t\t\t &ConductionDataGet[Recv_offset[recvTask]],\n\t\t\t Recv_count[recvTask] * sizeof(struct conductiondata_in), MPI_BYTE,\n\t\t\t recvTask, TAG_HYDRO_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t}\n\t }\n\t}\n\n myfree(ConductionDataIn);\n ConductionDataResult =\n\t(struct conductiondata_out *) mymalloc(nimport * sizeof(struct conductiondata_out));\n ConductionDataOut = (struct conductiondata_out *) mymalloc(nexport * sizeof(struct conductiondata_out));\n\n\n /* now do the particles that were sent to us */\n for(j = 0; j < nimport; j++)\n\tconduction_evaluate(j, 1, in, out, sum, &dummy, &dummy);\n\n if(i >= N_gas)\n\tndone_flag = 1;\n else\n\tndone_flag = 0;\n\n MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n\n /* get the result */\n for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t{\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\t if(recvTask < NTask)\n\t {\n\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t{\n\t\t /* send the results */\n\t\t MPI_Sendrecv(&ConductionDataResult[Recv_offset[recvTask]],\n\t\t\t Recv_count[recvTask] * sizeof(struct conductiondata_out),\n\t\t\t MPI_BYTE, recvTask, TAG_HYDRO_B,\n\t\t\t &ConductionDataOut[Send_offset[recvTask]],\n\t\t\t Send_count[recvTask] * sizeof(struct conductiondata_out),\n\t\t\t MPI_BYTE, recvTask, TAG_HYDRO_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t}\n\t }\n\t}\n\n /* add the result to the local particles */\n for(j = 0; j < nexport; j++)\n\t{\n\t place = DataIndexTable[j].Index;\n\n\t out[place] += ConductionDataOut[j].Out;\n\t sum[place] += ConductionDataOut[j].Sum;\n\t}\n\n myfree(ConductionDataOut);\n myfree(ConductionDataResult);\n myfree(ConductionDataGet);\n }\n while(ndone < NTask);\n\n\n /* do final operations */\n\n for(i = 0; i < N_gas; i++)\n if(P[i].Type == 0)\n {\n\tout[i] += in[i] * (1 + sum[i]);\n }\n\n myfree(sum);\n\n myfree(DataNodeList);\n myfree(DataIndexTable);\n myfree(Ngblist);\n}\n\n\n\n\n\nint conduction_evaluate(int target, int mode, double *in, double *out, double *sum,\n\t\t\tint *nexport, int *nsend_local)\n{\n int startnode, numngb, listindex = 0;\n int j, n;\n MyDouble *pos;\n MyFloat h_i, rho;\n double dx, dy, dz;\n double h_i2, hinv_i, hinv4_i, hinv_j, hinv4_j;\n double dwk_i, h_j, dwk_j, dwk;\n double r, r2, u, Kappa_i, kappa_mean, w, out_sum, w_sum;\n\n\n if(mode == 0)\n {\n pos = P[target].Pos;\n h_i = PPP[target].Hsml;\n rho = SphP[target].d.Density;\n Kappa_i = Kappa[target];\n }\n else\n {\n pos = ConductionDataGet[target].Pos;\n h_i = ConductionDataGet[target].Hsml;\n rho = ConductionDataGet[target].Density;\n Kappa_i = ConductionDataGet[target].Kappa;\n }\n\n h_i2 = h_i * h_i;\n hinv_i = 1.0 / h_i;\n#ifndef TWODIMS\n hinv4_i = hinv_i * hinv_i * hinv_i * hinv_i;\n#else\n hinv4_i = hinv_i * hinv_i * hinv_i / boxSize_Z;\n#endif\n\n /* initialize variables before SPH loop is started */\n out_sum = 0;\n w_sum = 0;\n\n /* Now start the actual SPH computation for this particle */\n\n if(mode == 0)\n {\n startnode = All.MaxPart;\t/* root node */\n }\n else\n {\n startnode = ConductionDataGet[target].NodeList[0];\n startnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n }\n\n while(startnode >= 0)\n {\n while(startnode >= 0)\n\t{\n\t numngb = ngb_treefind_pairs(pos, h_i, target, &startnode, mode, nexport, nsend_local);\n\n\t if(numngb < 0)\n\t return -1;\n\n\t for(n = 0; n < numngb; n++)\n\t {\n\t j = Ngblist[n];\n\n\t dx = pos[0] - P[j].Pos[0];\n\t dy = pos[1] - P[j].Pos[1];\n\t dz = pos[2] - P[j].Pos[2];\n\n#ifdef PERIODIC\t\t\t/* now find the closest image in the given box size */\n\t if(dx > boxHalf_X)\n\t\tdx -= boxSize_X;\n\t if(dx < -boxHalf_X)\n\t\tdx += boxSize_X;\n\t if(dy > boxHalf_Y)\n\t\tdy -= boxSize_Y;\n\t if(dy < -boxHalf_Y)\n\t\tdy += boxSize_Y;\n\t if(dz > boxHalf_Z)\n\t\tdz -= boxSize_Z;\n\t if(dz < -boxHalf_Z)\n\t\tdz += boxSize_Z;\n#endif\n\t r2 = dx * dx + dy * dy + dz * dz;\n\n\t h_j = PPP[j].Hsml;\n\t if(r2 < h_i2 || r2 < h_j * h_j)\n\t\t{\n\t\t r = sqrt(r2);\n\t\t if(r > 0)\n\t\t {\n\t\t if(r2 < h_i2)\n\t\t\t{\n\t\t\t u = r * hinv_i;\n\t\t\t if(u < 0.5)\n\t\t\t dwk_i = hinv4_i * u * (KERNEL_COEFF_3 * u - KERNEL_COEFF_4);\n\t\t\t else\n\t\t\t dwk_i = hinv4_i * KERNEL_COEFF_6 * (1.0 - u) * (1.0 - u);\n\t\t\t}\n\t\t else\n\t\t\tdwk_i = 0;\n\n\t\t if(r2 < h_j * h_j)\n\t\t\t{\n\t\t\t hinv_j = 1.0 / h_j;\n#ifndef TWODIMS\n\t\t\t hinv4_j = hinv_j * hinv_j * hinv_j * hinv_j;\n#else\n\t\t\t hinv4_j = hinv_j * hinv_j * hinv_j / boxSize_Z;\n#endif\n\t\t\t u = r * hinv_j;\n\t\t\t if(u < 0.5)\n\t\t\t dwk_j = hinv4_j * u * (KERNEL_COEFF_3 * u - KERNEL_COEFF_4);\n\t\t\t else\n\t\t\t dwk_j = hinv4_j * KERNEL_COEFF_6 * (1.0 - u) * (1.0 - u);\n\t\t\t}\n\t\t else\n\t\t\tdwk_j = 0;\n\n\n\t\t /* conduction equation kernel */\n\t\t if((Kappa_i + Kappa[j]) > 0)\n\t\t\t{\n\t\t\t kappa_mean = 2 * (Kappa_i * Kappa[j]) / (Kappa_i + Kappa[j]);\n\t\t\t dwk = 0.5 * (dwk_i + dwk_j);\n\n\t\t\t w = 2.0 * P[j].Mass / (rho * SphP[j].d.Density) * kappa_mean * (-dwk) / r;\n\n\t\t\t out_sum += (-w * in[j]);\n\t\t\t w_sum += w;\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\t}\n\n if(mode == 1)\n\t{\n\t listindex++;\n\t if(listindex < NODELISTLENGTH)\n\t {\n\t startnode = ConductionDataGet[target].NodeList[listindex];\n\t if(startnode >= 0)\n\t\tstartnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n\t }\n\t}\n }\n\n\n /* Now collect the result at the right place */\n if(mode == 0)\n {\n out[target] = out_sum;\n sum[target] = w_sum;\n }\n else\n {\n ConductionDataResult[target].Out = out_sum;\n ConductionDataResult[target].Sum = w_sum;\n }\n\n return 0;\n}\n\n\n#endif\n", "meta": {"hexsha": "3f26b42b9de229e9a3740926cb678ca21ed2f421", "size": 14518, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/conduction.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/conduction.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/conduction.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2486956522, "max_line_length": 110, "alphanum_fraction": 0.62487946, "num_tokens": 4558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.44815474581016246}} {"text": "/* ode-initval2/rk4imp.c\n * \n * Copyright (C) 2009, 2010 Tuomo Keskitalo\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Based on rk4imp.c by Gerard Jungman */\n\n/* Gaussian implicit 4th order Runge-Kutta method. Error estimation\n is carried out by the step doubling method.\n */\n\n/* References: \n\n Ascher, U.M., Petzold, L.R., Computer methods for ordinary\n differential and differential-algebraic equations, SIAM, \n Philadelphia, 1998. ISBN 0898714125, 9780898714128\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"odeiv_util.h\"\n#include \"rksubs.c\"\n#include \"modnewton1.c\"\n\n/* Stage of method */\n#define RK4IMP_STAGE 2\n\ntypedef struct\n{\n gsl_matrix *A; /* Runge-Kutta coefficients */\n double *y_onestep; /* Result with one step */\n double *y_twostep; /* Result with two half steps */\n double *ytmp; /* Temporary work space */\n double *y_save; /* Backup space */\n double *YZ; /* Runge-Kutta points */\n double *fYZ; /* Derivatives at YZ */\n gsl_matrix *dfdy; /* Jacobian matrix */\n double *dfdt; /* time derivative of f */\n modnewton1_state_t *esol; /* nonlinear equation solver */\n double *errlev; /* desired error level of y */\n const gsl_odeiv2_driver *driver; /* pointer to driver object */\n}\nrk4imp_state_t;\n\nstatic void *\nrk4imp_alloc (size_t dim)\n{\n rk4imp_state_t *state = (rk4imp_state_t *) malloc (sizeof (rk4imp_state_t));\n\n if (state == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for rk4imp_state\",\n GSL_ENOMEM);\n }\n\n state->A = gsl_matrix_alloc (RK4IMP_STAGE, RK4IMP_STAGE);\n\n if (state->A == 0)\n {\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for A\", GSL_ENOMEM);\n }\n\n state->y_onestep = (double *) malloc (dim * sizeof (double));\n\n if (state->y_onestep == 0)\n {\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y_onestep\", GSL_ENOMEM);\n }\n\n state->y_twostep = (double *) malloc (dim * sizeof (double));\n\n if (state->y_twostep == 0)\n {\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y_onestep\", GSL_ENOMEM);\n }\n\n state->ytmp = (double *) malloc (dim * sizeof (double));\n\n if (state->ytmp == 0)\n {\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for ytmp\", GSL_ENOMEM);\n }\n\n state->y_save = (double *) malloc (dim * sizeof (double));\n\n if (state->y_save == 0)\n {\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y_save\", GSL_ENOMEM);\n }\n\n state->YZ = (double *) malloc (dim * RK4IMP_STAGE * sizeof (double));\n\n if (state->YZ == 0)\n {\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for YZ\", GSL_ENOMEM);\n }\n\n state->fYZ = (double *) malloc (dim * RK4IMP_STAGE * sizeof (double));\n\n if (state->fYZ == 0)\n {\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for fYZ\", GSL_ENOMEM);\n }\n\n state->dfdt = (double *) malloc (dim * sizeof (double));\n\n if (state->dfdt == 0)\n {\n free (state->fYZ);\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for dfdt\", GSL_ENOMEM);\n }\n\n state->dfdy = gsl_matrix_alloc (dim, dim);\n\n if (state->dfdy == 0)\n {\n free (state->dfdt);\n free (state->fYZ);\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for dfdy\", GSL_ENOMEM);\n }\n\n state->esol = modnewton1_alloc (dim, RK4IMP_STAGE);\n\n if (state->esol == 0)\n {\n gsl_matrix_free (state->dfdy);\n free (state->dfdt);\n free (state->fYZ);\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for esol\", GSL_ENOMEM);\n }\n\n state->errlev = (double *) malloc (dim * sizeof (double));\n\n if (state->errlev == 0)\n {\n modnewton1_free (state->esol);\n gsl_matrix_free (state->dfdy);\n free (state->dfdt);\n free (state->fYZ);\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for errlev\", GSL_ENOMEM);\n }\n\n state->driver = NULL;\n\n return state;\n}\n\nstatic int\nrk4imp_apply (void *vstate, size_t dim, double t, double h,\n double y[], double yerr[],\n const double dydt_in[], double dydt_out[],\n const gsl_odeiv2_system * sys)\n{\n /* Makes a Gaussian implicit 4th order Runge-Kutta with step size h\n and estimates the local error of the step.\n */\n\n rk4imp_state_t *state = (rk4imp_state_t *) vstate;\n\n double *const y_onestep = state->y_onestep;\n double *const y_twostep = state->y_twostep;\n double *const ytmp = state->ytmp;\n double *const y_save = state->y_save;\n double *const YZ = state->YZ; /* Runge-Kutta points */\n double *const fYZ = state->fYZ;\n gsl_matrix *const dfdy = state->dfdy;\n double *const dfdt = state->dfdt;\n double *const errlev = state->errlev;\n\n const modnewton1_state_t *esol = state->esol;\n\n /* Runge-Kutta coefficients */\n\n gsl_matrix *A = state->A;\n\n const double b[] = { 0.5, 0.5 };\n const double c[] = { (3 - sqrt (3)) / 6, (3 + sqrt (3)) / 6 };\n\n gsl_matrix_set (A, 0, 0, 1.0 / 4);\n gsl_matrix_set (A, 0, 1, (3 - 2 * sqrt (3)) / 12);\n gsl_matrix_set (A, 1, 0, (3 + 2 * sqrt (3)) / 12);\n gsl_matrix_set (A, 1, 1, 1.0 / 4);\n\n if (esol == NULL)\n {\n GSL_ERROR (\"no non-linear equation solver speficied\", GSL_EINVAL);\n }\n\n /* Get desired error levels via gsl_odeiv2_control object through driver\n object, which is a requirement for this stepper.\n */\n\n if (state->driver == NULL)\n {\n return GSL_EFAULT;\n }\n else\n {\n size_t i;\n\n for (i = 0; i < dim; i++)\n {\n if (dydt_in != NULL)\n {\n gsl_odeiv2_control_errlevel (state->driver->c, y[i],\n dydt_in[i], h, i, &errlev[i]);\n }\n else\n {\n gsl_odeiv2_control_errlevel (state->driver->c, y[i],\n 0.0, h, i, &errlev[i]);\n }\n }\n }\n\n /* Evaluate Jacobian for modnewton1 */\n\n {\n int s = GSL_ODEIV_JA_EVAL (sys, t, y, dfdy->data, dfdt);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n /* Calculate a single step with size h */\n\n {\n int s = modnewton1_init ((void *) esol, A, h, dfdy, sys);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n {\n int s = modnewton1_solve ((void *) esol, A, c, t, h, y,\n sys, YZ, errlev);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n {\n size_t j;\n\n for (j = 0; j < RK4IMP_STAGE; j++)\n {\n int s =\n GSL_ODEIV_FN_EVAL (sys, t + c[j] * h, &YZ[j * dim], &fYZ[j * dim]);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n }\n\n {\n int s = rksubs (y_onestep, h, y, fYZ, b, RK4IMP_STAGE, dim);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n /* Error estimation by step doubling */\n\n {\n int s = modnewton1_init ((void *) esol, A, h / 2.0, dfdy, sys);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n /* 1st half step */\n\n {\n int s = modnewton1_solve ((void *) esol, A, c, t, h / 2.0, y,\n sys, YZ, errlev);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n {\n size_t j;\n\n for (j = 0; j < RK4IMP_STAGE; j++)\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + c[j] * h / 2.0, &YZ[j * dim],\n &fYZ[j * dim]);\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n }\n\n {\n int s = rksubs (ytmp, h / 2.0, y, fYZ, b, RK4IMP_STAGE, dim);\n\n if (s != GSL_SUCCESS)\n return s;\n }\n\n /* Save original y values in case of error */\n\n DBL_MEMCPY (y_save, y, dim);\n\n /* 2nd half step */\n\n {\n int s = modnewton1_solve ((void *) esol, A, c, t + h / 2.0, h / 2.0,\n ytmp, sys, YZ, errlev);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n {\n size_t j;\n\n for (j = 0; j < RK4IMP_STAGE; j++)\n {\n int s =\n GSL_ODEIV_FN_EVAL (sys, t + h / 2.0 + c[j] * h / 2.0, &YZ[j * dim],\n &fYZ[j * dim]);\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n }\n\n {\n int s = rksubs (y_twostep, h / 2.0, ytmp, fYZ, b, RK4IMP_STAGE, dim);\n\n if (s != GSL_SUCCESS)\n {\n DBL_MEMCPY (y, y_save, dim);\n return s;\n }\n }\n\n /* Note: rk4imp returns y using the results from two half steps\n instead of the single step since the results are freely\n available and more precise.\n */\n\n DBL_MEMCPY (y, y_twostep, dim);\n\n /* Error estimation */\n\n {\n size_t i;\n for (i = 0; i < dim; i++)\n {\n yerr[i] = ODEIV_ERR_SAFETY * 0.5 *\n fabs (y_twostep[i] - y_onestep[i]) / 15.0;\n }\n }\n\n /* Derivatives at output */\n\n if (dydt_out != NULL)\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);\n\n if (s != GSL_SUCCESS)\n {\n /* Restore original values */\n DBL_MEMCPY (y, y_save, dim);\n\n return s;\n }\n }\n\n return GSL_SUCCESS;\n}\n\nstatic int\nrk4imp_set_driver (void *vstate, const gsl_odeiv2_driver * d)\n{\n rk4imp_state_t *state = (rk4imp_state_t *) vstate;\n\n state->driver = d;\n\n return GSL_SUCCESS;\n}\n\nstatic int\nrk4imp_reset (void *vstate, size_t dim)\n{\n rk4imp_state_t *state = (rk4imp_state_t *) vstate;\n\n DBL_ZERO_MEMSET (state->y_onestep, dim);\n DBL_ZERO_MEMSET (state->y_twostep, dim);\n DBL_ZERO_MEMSET (state->ytmp, dim);\n DBL_ZERO_MEMSET (state->y_save, dim);\n DBL_ZERO_MEMSET (state->YZ, dim * RK4IMP_STAGE);\n DBL_ZERO_MEMSET (state->fYZ, dim * RK4IMP_STAGE);\n\n return GSL_SUCCESS;\n}\n\nstatic unsigned int\nrk4imp_order (void *vstate)\n{\n rk4imp_state_t *state = (rk4imp_state_t *) vstate;\n state = 0; /* prevent warnings about unused parameters */\n return 4;\n}\n\nstatic void\nrk4imp_free (void *vstate)\n{\n rk4imp_state_t *state = (rk4imp_state_t *) vstate;\n\n free (state->errlev);\n modnewton1_free (state->esol);\n gsl_matrix_free (state->dfdy);\n free (state->dfdt);\n free (state->fYZ);\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n}\n\nstatic const gsl_odeiv2_step_type rk4imp_type = {\n \"rk4imp\", /* name */\n 1, /* can use dydt_in? */\n 1, /* gives exact dydt_out? */\n &rk4imp_alloc,\n &rk4imp_apply,\n &rk4imp_set_driver,\n &rk4imp_reset,\n &rk4imp_order,\n &rk4imp_free\n};\n\nconst gsl_odeiv2_step_type *gsl_odeiv2_step_rk4imp = &rk4imp_type;\n", "meta": {"hexsha": "99267169ac74ba2fe2b2ce119687cc2a43eaa67f", "size": 12882, "ext": "c", "lang": "C", "max_stars_repo_path": "Integration/gsl-1.15/ode-initval2/rk4imp.c", "max_stars_repo_name": "WikiGaze/Wikipedia-readers-gaze", "max_stars_repo_head_hexsha": "b723fcad149662a9af981c4e507678d9c7f106d2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Integration/gsl-1.15/ode-initval2/rk4imp.c", "max_issues_repo_name": "WikiGaze/Wikipedia-readers-gaze", "max_issues_repo_head_hexsha": "b723fcad149662a9af981c4e507678d9c7f106d2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Integration/gsl-1.15/ode-initval2/rk4imp.c", "max_forks_repo_name": "WikiGaze/Wikipedia-readers-gaze", "max_forks_repo_head_hexsha": "b723fcad149662a9af981c4e507678d9c7f106d2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1688555347, "max_line_length": 81, "alphanum_fraction": 0.5653625213, "num_tokens": 3876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4479674618157456}} {"text": "#ifndef UTIL_H\n#define UTIL_H\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_MKL\n#include \n#include \n#else\n#include \n#include \n#endif\n\ntypedef Eigen::SparseMatrix SpMat;\ntypedef Eigen::VectorBlock, -1> Segment;\ntypedef Eigen::Block, -1, -1> MatrixBlock;\n\nbool are_connected(Eigen::VectorXi &a, Eigen::VectorXi &b, SpMat &A);\nbool should_be_disconnected(int lvl1, int lvl2, int sep1, int sep2);\ndouble elapsed(timeval& start, timeval& end);\nvoid swap2perm(Eigen::VectorXi* swap, Eigen::VectorXi* perm);\nbool isperm(Eigen::VectorXi* perm);\nSpMat symmetric_graph(SpMat& A);\n\ntypedef timeval timer;\ntimer wctime();\n\n/**\n * C <- alpha A * B + beta C\n * C <- alpha A^T * B + beta C\n * C <- alpha A * B^T + beta C\n * C <- alpha A^T * B^T + beta C\n * Gemm\n */\nvoid gemm(Eigen::MatrixXd* A, Eigen::MatrixXd* B, Eigen::MatrixXd* C, CBLAS_TRANSPOSE tA, CBLAS_TRANSPOSE tB, double alpha, double beta);\n\n/** Return a new\n * C <- alpha A^(/T) * B^(/T)\n **/\nEigen::MatrixXd* gemm_new(Eigen::MatrixXd* A, Eigen::MatrixXd* B, CBLAS_TRANSPOSE tA, CBLAS_TRANSPOSE tB, double alpha);\n\n/**\n * C <- C - A * A^T\n */\nvoid syrk(Eigen::MatrixXd* A, Eigen::MatrixXd* C);\n\n/** \n * A <- L, L L^T = A\n * Return != 0 if potf failed (not spd)\n */ \nint potf(Eigen::MatrixXd* A);\n\n/**\n * A <- [L\\U] (lower and upper)\n * p <- swap (NOT a permutation)\n * A[p] = L*U\n * L is unit diagonal\n * U is not\n * Return != 0 if getf failed (singular)\n */\nint getf(Eigen::MatrixXd* A, Eigen::VectorXi* swap);\n\n/**\n * Compute an estimated 1-norm condition number of A using its LU or Cholesky factorization\n */\ndouble rcond_1_getf(Eigen::MatrixXd* A_LU, double A_1_norm);\ndouble rcond_1_potf(Eigen::MatrixXd* A_LLT, double A_1_norm);\n\n/**\n * B <- B * L^(-1)\n * B <- B * L^(-T)\n * B <- B * U^(-1)\n * B <- B * U^(-T)\n */\nvoid trsm_right(Eigen::MatrixXd* L, Eigen::MatrixXd* B, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag);\n\n/**\n * B <- L^(-1) * B\n * B <- L^(-T) * B\n * B <- U^(-1) * B\n * B <- U^(-T) * B\n */\nvoid trsm_left(Eigen::MatrixXd* L, Eigen::MatrixXd* B, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag);\n\n/**\n * x <- L^(-1) * x\n * x <- L^(-T) * x\n * x <- U^(-1) * x\n * x <- U^(-T) * x\n */\nvoid trsv(Eigen::MatrixXd* L, Segment* x, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag);\n\n/**\n * x <- L^T * x\n */\nvoid trmv_trans(Eigen::MatrixXd* L, Segment* x);\n\n/**\n * A <- L^T * A\n */\nvoid trmm_trans(Eigen::MatrixXd* L, Eigen::MatrixXd* A);\n\n/**\n * x2 <- x2 - A21 * x1\n */\nvoid gemv_notrans(Eigen::MatrixXd* A21, Segment* x1, Segment* x2);\n\n/**\n * x2 <- x2 - A12^T * x1\n */\nvoid gemv_trans(Eigen::MatrixXd* A12, Segment* x1, Segment* x2);\n\n/**\n * AP = QR\n */\nvoid geqp3(Eigen::MatrixXd* A, Eigen::VectorXi* jpvt, Eigen::VectorXd* tau);\n\n/**\n * A = U S VT\n * Compute the full SVD, where if A is mxn, U is mxm, V is nxn, and S is min(M,N)\n * VT is V^T, *not* V.\n */\nvoid gesvd(Eigen::MatrixXd* A, Eigen::MatrixXd* U, Eigen::VectorXd* S, Eigen::MatrixXd* VT);\n\n/**\n * A = U S U^T \n * A <- U\n * Full Symmetric EVD\n */\nvoid syev(Eigen::MatrixXd* A, Eigen::VectorXd* S);\n\n/**\n * x <- Q * x\n */\nvoid ormqr_notrans(Eigen::MatrixXd* v, Eigen::VectorXd* h, Segment* x);\n\n/**\n * x <- Q^T * x\n * A <- Q^T * A\n */\nvoid ormqr_trans(Eigen::MatrixXd* v, Eigen::VectorXd* h, Segment* x);\n\n/**\n * A <- A * Q\n * A <- A * Q^T\n * A <- Q * A\n * A <- Q^T * A\n */\nvoid ormqr(Eigen::MatrixXd* v, Eigen::VectorXd* h, Eigen::MatrixXd* A, char side, char trans);\n\n/**\n * Create the thin Q\n */\nvoid orgqr(Eigen::MatrixXd* v, Eigen::VectorXd* h);\n\n/** \n * Create a square Q\n */\n// void orgqr_fat(Eigen::MatrixXd* v, Eigen::VectorXd* h);\n\n/**\n * A = QR\n */\nvoid geqrf(Eigen::MatrixXd* A, Eigen::VectorXd* tau);\n\nint choose_rank(Eigen::VectorXd& s, double tol);\n\nstd::size_t hashv(std::vector vals);\n\n// Hash function for Eigen matrix and vector.\n// The code is from `hash_combine` function of the Boost library. See\n// http://www.boost.org/doc/libs/1_55_0/doc/html/hash/reference.html#boost.hash_combine .\ntemplate\nstruct matrix_hash : std::unary_function {\n std::size_t operator()(T const& matrix) const {\n // Note that it is oblivious to the storage order of Eigen matrix (column- or\n // row-major). It will give you the same hash value for two different matrices if they\n // are the transpose of each other in different storage order.\n size_t seed = 0;\n for (size_t i = 0; i < matrix.size(); ++i) {\n auto elem = *(matrix.data() + i);\n seed ^= std::hash()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n }\n return seed;\n }\n};\n\nvoid block2dense(Eigen::VectorXi &rowval, Eigen::VectorXi &colptr, Eigen::VectorXd &nnzval, int i, int j, int li, int lj, Eigen::MatrixXd *dst, bool transpose);\n\nEigen::MatrixXd linspace_nd(int n, int dim);\n\n// Returns A[p,p]\nSpMat symm_perm(SpMat &A, Eigen::VectorXi &p);\n\n// Random vector with seed\nEigen::VectorXd random(int size, int seed);\n\nEigen::MatrixXd random(int rows, int cols, int seed);\n\n// Print vector\ntemplate\nstd::ostream& operator<<(std::ostream& os, const std::vector& v) {\n for(auto v_ : v) {\n os << v_ << \" \" ;\n }\n os << std::endl;\n return os;\n}\n\n/**\n * Statistics and Logging\n **/\n\nstruct Profile {\n public:\n double elim;\n double scale;\n double spars;\n double merge;\n\n double mergealloc;\n double mergecopy;\n\n double geqp3;\n double geqrf;\n double potf;\n double trsm;\n double gemm;\n\n double buildq;\n double scattq;\n double perma;\n double scatta;\n double prese;\n double assmb;\n double phi;\n\n Profile() :\n elim(0), scale(0), spars(0), merge(0), \n mergealloc(0), mergecopy(0),\n geqp3(0), geqrf(0), potf(0), trsm(0), gemm(0),\n buildq(0), scattq(0), perma(0), scatta(0), prese(0), assmb(0), phi(0)\n {}\n};\n\ntemplate\nstruct Stats {\n private:\n T min;\n T max;\n T sum;\n int count;\n public:\n Stats(): min(std::numeric_limits::max()), max(std::numeric_limits::lowest()), sum(0), count(0) {};\n void addData(T value) {\n this->min = (this->min < value ? this->min : value);\n this->max = (this->max > value ? this->max : value);\n this->sum += value;\n this->count += 1;\n }\n T getMin() const { return this->count == 0 ? 0 : this->min; }\n T getMax() const { return this->count == 0 ? 0 : this->max; }\n double getMean() const { return ((double)this->sum)/((double)this->count); }\n int getCount() const { return this->count; }\n T getSum() const { return this->sum; }\n};\n\nstruct Log {\n public:\n int dofs_nd;\n int dofs_left_nd;\n int dofs_left_elim;\n int dofs_left_spars;\n long long int fact_nnz;\n Stats rank_before;\n Stats rank_after;\n Stats nbrs;\n Stats cond_diag;\n Stats norm_diag; \n \n Log() :\n dofs_nd(0),\n dofs_left_nd(0), dofs_left_elim(0), dofs_left_spars(0),\n fact_nnz(0),\n rank_before(Stats()), rank_after(Stats()), nbrs(Stats()),\n cond_diag(Stats()), norm_diag(Stats())\n {}\n};\n\n#endif\n", "meta": {"hexsha": "7fd40a7a93828fb5f009d3b123e9fe0af609379b", "size": 7716, "ext": "h", "lang": "C", "max_stars_repo_path": "include/util.h", "max_stars_repo_name": "wuyou33/spaND_public", "max_stars_repo_head_hexsha": "5383ec0af835634bef7b2ff24c979794a2ef253b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-23T12:04:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-23T12:04:30.000Z", "max_issues_repo_path": "include/util.h", "max_issues_repo_name": "wuyou33/spaND_public", "max_issues_repo_head_hexsha": "5383ec0af835634bef7b2ff24c979794a2ef253b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/util.h", "max_forks_repo_name": "wuyou33/spaND_public", "max_forks_repo_head_hexsha": "5383ec0af835634bef7b2ff24c979794a2ef253b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8060200669, "max_line_length": 160, "alphanum_fraction": 0.5922757906, "num_tokens": 2405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.44794425573815266}} {"text": "/* linalg/invtri_complex.c\n *\n * Copyright (C) 2019 Patrick Alken\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the\n * Free Software Foundation; either version 3, or (at your option) any\n * later version.\n *\n * This source is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * This module contains code to invert complex triangular matrices\n */\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"recurse.h\"\n\nstatic int complex_tri_invert_L2(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T);\nstatic int complex_tri_invert_L3(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T);\nstatic int triangular_singular(const gsl_matrix_complex * T);\n\n/*\ngsl_linalg_complex_tri_invert()\n Invert a complex triangular matrix T using Level 3 BLAS\n\nInputs: Uplo - CblasUpper or CblasLower\n Diag - unit triangular?\n T - on output the upper (or lower) part of T\n is replaced by its inverse\n\nReturn: success/error\n*/\n\nint\ngsl_linalg_complex_tri_invert(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T)\n{\n const size_t N = T->size1;\n\n if (N != T->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else\n {\n int status;\n\n status = triangular_singular(T);\n if (status)\n return status;\n\n return complex_tri_invert_L3(Uplo, Diag, T);\n }\n}\n\n/*\ncomplex_tri_invert_L2()\n Invert a complex triangular matrix T\n\nInputs: Uplo - CblasUpper or CblasLower\n Diag - unit triangular?\n T - on output the upper (or lower) part of T\n is replaced by its inverse\n\nReturn: success/error\n\nNotes:\n1) Based on LAPACK routine ZTRTI2 using Level 2 BLAS\n*/\n\nstatic int\ncomplex_tri_invert_L2(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T)\n{\n const size_t N = T->size1;\n\n if (N != T->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else\n {\n size_t i;\n\n if (Uplo == CblasUpper)\n {\n for (i = 0; i < N; ++i)\n {\n gsl_complex * Tii = gsl_matrix_complex_ptr(T, i, i);\n gsl_complex aii;\n\n if (Diag == CblasNonUnit)\n {\n *Tii = gsl_complex_inverse(*Tii);\n GSL_REAL(aii) = -GSL_REAL(*Tii);\n GSL_IMAG(aii) = -GSL_IMAG(*Tii);\n }\n else\n aii = GSL_COMPLEX_NEGONE;\n\n if (i > 0)\n {\n gsl_matrix_complex_view m = gsl_matrix_complex_submatrix(T, 0, 0, i, i);\n gsl_vector_complex_view v = gsl_matrix_complex_subcolumn(T, i, 0, i);\n\n gsl_blas_ztrmv(CblasUpper, CblasNoTrans, Diag, &m.matrix, &v.vector);\n gsl_blas_zscal(aii, &v.vector);\n }\n }\n }\n else\n {\n for (i = 0; i < N; ++i)\n {\n size_t j = N - i - 1;\n gsl_complex * Tjj = gsl_matrix_complex_ptr(T, j, j);\n gsl_complex ajj;\n\n if (Diag == CblasNonUnit)\n {\n *Tjj = gsl_complex_inverse(*Tjj);\n GSL_REAL(ajj) = -GSL_REAL(*Tjj);\n GSL_IMAG(ajj) = -GSL_IMAG(*Tjj);\n }\n else\n ajj = GSL_COMPLEX_NEGONE;\n\n if (j < N - 1)\n {\n gsl_matrix_complex_view m = gsl_matrix_complex_submatrix(T, j + 1, j + 1, N - j - 1, N - j - 1);\n gsl_vector_complex_view v = gsl_matrix_complex_subcolumn(T, j, j + 1, N - j - 1);\n\n gsl_blas_ztrmv(CblasLower, CblasNoTrans, Diag, &m.matrix, &v.vector);\n gsl_blas_zscal(ajj, &v.vector);\n }\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ncomplex_tri_invert_L3()\n Invert a complex triangular matrix T\n\nInputs: Uplo - CblasUpper or CblasLower\n Diag - unit triangular?\n T - on output the upper (or lower) part of T\n is replaced by its inverse\n\nReturn: success/error\n\nNotes:\n1) Based on ReLAPACK using Level 3 BLAS\n*/\n\nstatic int\ncomplex_tri_invert_L3(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T)\n{\n const size_t N = T->size1;\n\n if (N != T->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else if (N <= CROSSOVER_INVTRI)\n {\n /* use Level 2 algorithm */\n return complex_tri_invert_L2(Uplo, Diag, T);\n }\n else\n {\n /*\n * partition matrix:\n *\n * T11 T12\n * T21 T22\n *\n * where T11 is N1-by-N1\n */\n int status;\n const size_t N1 = GSL_LINALG_SPLIT_COMPLEX(N);\n const size_t N2 = N - N1;\n gsl_matrix_complex_view T11 = gsl_matrix_complex_submatrix(T, 0, 0, N1, N1);\n gsl_matrix_complex_view T12 = gsl_matrix_complex_submatrix(T, 0, N1, N1, N2);\n gsl_matrix_complex_view T21 = gsl_matrix_complex_submatrix(T, N1, 0, N2, N1);\n gsl_matrix_complex_view T22 = gsl_matrix_complex_submatrix(T, N1, N1, N2, N2);\n\n /* recursion on T11 */\n status = complex_tri_invert_L3(Uplo, Diag, &T11.matrix);\n if (status)\n return status;\n\n if (Uplo == CblasLower)\n {\n /* T21 = - T21 * T11 */\n gsl_blas_ztrmm(CblasRight, Uplo, CblasNoTrans, Diag, GSL_COMPLEX_NEGONE, &T11.matrix, &T21.matrix);\n\n /* T21 = T22 * T21^{-1} */\n gsl_blas_ztrsm(CblasLeft, Uplo, CblasNoTrans, Diag, GSL_COMPLEX_ONE, &T22.matrix, &T21.matrix);\n }\n else\n {\n /* T12 = - T11 * T12 */\n gsl_blas_ztrmm(CblasLeft, Uplo, CblasNoTrans, Diag, GSL_COMPLEX_NEGONE, &T11.matrix, &T12.matrix);\n\n /* T12 = T12 * T22^{-1} */\n gsl_blas_ztrsm(CblasRight, Uplo, CblasNoTrans, Diag, GSL_COMPLEX_ONE, &T22.matrix, &T12.matrix);\n }\n\n /* recursion on T22 */\n status = complex_tri_invert_L3(Uplo, Diag, &T22.matrix);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n }\n}\n\nstatic int\ntriangular_singular(const gsl_matrix_complex * T)\n{\n size_t i;\n\n for (i = 0; i < T->size1; ++i)\n {\n gsl_complex z = gsl_matrix_complex_get(T, i, i);\n if (GSL_REAL(z) == 0.0 && GSL_IMAG(z) == 0.0)\n return GSL_ESING;\n }\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "38a43e7d2828ae3d48dc5f6becf220e8c045db43", "size": 6953, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/linalg/invtri_complex.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/linalg/invtri_complex.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/invtri_complex.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.812, "max_line_length": 114, "alphanum_fraction": 0.5961455487, "num_tokens": 1973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6261241632752916, "lm_q1q2_score": 0.44794425074699296}} {"text": "/* linalg/trimult_complex.c\n *\n * Copyright (C) 2019 Patrick Alken\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the\n * Free Software Foundation; either version 3, or (at your option) any\n * later version.\n *\n * This source is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * This module contains code to compute L^T L where L is a lower triangular matrix\n */\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"recurse.h\"\n\nstatic int triangular_multherm_L2(CBLAS_UPLO_t Uplo, gsl_matrix_complex * T);\nstatic int triangular_multherm_L3(CBLAS_UPLO_t Uplo, gsl_matrix_complex * T);\nstatic int triangular_mult_L2(CBLAS_UPLO_t Uplo, gsl_matrix_complex * LU);\nstatic int triangular_mult_L3(CBLAS_UPLO_t Uplo, gsl_matrix_complex * A);\nstatic void complex_conj_vector(gsl_vector_complex * v);\n\nint\ngsl_linalg_complex_tri_LHL(gsl_matrix_complex * L)\n{\n return triangular_multherm_L3(CblasLower, L);\n}\n\nint\ngsl_linalg_complex_tri_UL(gsl_matrix_complex * LU)\n{\n return triangular_mult_L3(CblasUpper, LU);\n}\n\n\n/*\ntriangular_multherm_L2()\n Compute L^H L or U U^H\n\nInputs: Uplo - CblasUpper or CblasLower\n T - on output the upper (or lower) part of T\n is replaced by L^H L or U U^H\n\nReturn: success/error\n\nNotes:\n1) Based on LAPACK routine ZLAUU2 using Level 2 BLAS\n*/\n\nstatic int\ntriangular_multherm_L2(CBLAS_UPLO_t Uplo, gsl_matrix_complex * T)\n{\n const size_t N = T->size1;\n\n if (N != T->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else\n {\n size_t i;\n\n if (Uplo == CblasUpper)\n {\n }\n else\n {\n for (i = 0; i < N; ++i)\n {\n gsl_complex * Tii = gsl_matrix_complex_ptr(T, i, i);\n gsl_complex z0 = *Tii;\n\n if (i < N - 1)\n {\n gsl_vector_complex_view v = gsl_matrix_complex_subcolumn(T, i, i + 1, N - i - 1);\n double norm = gsl_blas_dznrm2(&v.vector);\n\n GSL_REAL(*Tii) = gsl_complex_abs2(*Tii) + norm * norm;\n\n if (i > 0)\n {\n gsl_vector_complex_view w = gsl_matrix_complex_subrow(T, i, 0, i);\n gsl_matrix_complex_view m = gsl_matrix_complex_submatrix(T, i + 1, 0, N - i - 1, i);\n\n complex_conj_vector(&w.vector);\n gsl_blas_zgemv(CblasConjTrans, GSL_COMPLEX_ONE, &m.matrix, &v.vector, z0, &w.vector);\n complex_conj_vector(&w.vector);\n }\n }\n else\n {\n gsl_vector_complex_view w = gsl_matrix_complex_row(T, i);\n gsl_blas_zdscal(GSL_REAL(z0), &w.vector);\n }\n\n GSL_IMAG(*Tii) = 0.0;\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ntriangular_multherm_L3()\n Compute L^H L or U U^H\n\nInputs: Uplo - CblasUpper or CblasLower\n T - on output the upper (or lower) part of T\n is replaced by L^H L or U U^H\n\nReturn: success/error\n\nNotes:\n1) Based on ReLAPACK using Level 3 BLAS\n*/\n\nstatic int\ntriangular_multherm_L3(CBLAS_UPLO_t Uplo, gsl_matrix_complex * T)\n{\n const size_t N = T->size1;\n\n if (N != T->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else if (N <= CROSSOVER_TRIMULT)\n {\n /* use Level 2 algorithm */\n return triangular_multherm_L2(Uplo, T);\n }\n else\n {\n /*\n * partition matrix:\n *\n * T11 T12\n * T21 T22\n *\n * where T11 is N1-by-N1\n */\n int status;\n const size_t N1 = GSL_LINALG_SPLIT_COMPLEX(N);\n const size_t N2 = N - N1;\n gsl_matrix_complex_view T11 = gsl_matrix_complex_submatrix(T, 0, 0, N1, N1);\n gsl_matrix_complex_view T12 = gsl_matrix_complex_submatrix(T, 0, N1, N1, N2);\n gsl_matrix_complex_view T21 = gsl_matrix_complex_submatrix(T, N1, 0, N2, N1);\n gsl_matrix_complex_view T22 = gsl_matrix_complex_submatrix(T, N1, N1, N2, N2);\n\n /* recursion on T11 */\n status = triangular_multherm_L3(Uplo, &T11.matrix);\n if (status)\n return status;\n\n if (Uplo == CblasLower)\n {\n /* T11 += T21^T T21 */\n gsl_blas_zherk(Uplo, CblasConjTrans, 1.0, &T21.matrix, 1.0, &T11.matrix);\n\n /* T21 = T22^T * T21 */\n gsl_blas_ztrmm(CblasLeft, Uplo, CblasConjTrans, CblasNonUnit, GSL_COMPLEX_ONE, &T22.matrix, &T21.matrix);\n }\n else\n {\n /* T11 += T12 T12^T */\n gsl_blas_zherk(Uplo, CblasNoTrans, 1.0, &T12.matrix, 1.0, &T11.matrix);\n\n /* T12 = T12 * T22^T */\n gsl_blas_ztrmm(CblasRight, Uplo, CblasConjTrans, CblasNonUnit, GSL_COMPLEX_ONE, &T22.matrix, &T12.matrix);\n }\n\n /* recursion on T22 */\n status = triangular_multherm_L3(Uplo, &T22.matrix);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n }\n}\n\n/********************************************\n * INTERNAL ROUTINES *\n ********************************************/\n\n/*\ntriangular_mult_L2()\n Compute U L or L U\n\nInputs: Uplo - CblasUpper or CblasLower (first triangular factor)\n LU - on input, matrix in LU form;\n on output U*L or L*U\n\nReturn: success/error\n*/\n\nstatic int\ntriangular_mult_L2(CBLAS_UPLO_t Uplo, gsl_matrix_complex * LU)\n{\n const size_t N = LU->size1;\n\n if (N != LU->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else\n {\n size_t i;\n\n /* quick return */\n if (N == 1)\n return GSL_SUCCESS;\n\n if (Uplo == CblasUpper)\n {\n /* compute U*L and store in LU */\n\n for (i = 0; i < N; ++i)\n {\n gsl_complex * Aii = gsl_matrix_complex_ptr(LU, i, i);\n gsl_complex Uii = *Aii;\n\n if (i < N - 1)\n {\n gsl_vector_complex_view lb = gsl_matrix_complex_subcolumn(LU, i, i + 1, N - i - 1);\n gsl_vector_complex_view ur = gsl_matrix_complex_subrow(LU, i, i + 1, N - i - 1);\n gsl_complex dot;\n\n gsl_blas_zdotu(&lb.vector, &ur.vector, &dot);\n *Aii = gsl_complex_add(*Aii, dot);\n\n if (i > 0)\n {\n gsl_matrix_complex_view U_TR = gsl_matrix_complex_submatrix(LU, 0, i + 1, i, N - i - 1);\n gsl_matrix_complex_view L_BL = gsl_matrix_complex_submatrix(LU, i + 1, 0, N - i - 1, i);\n gsl_vector_complex_view ut = gsl_matrix_complex_subcolumn(LU, i, 0, i);\n gsl_vector_complex_view ll = gsl_matrix_complex_subrow(LU, i, 0, i);\n\n gsl_blas_zgemv(CblasTrans, GSL_COMPLEX_ONE, &L_BL.matrix, &ur.vector, Uii, &ll.vector);\n gsl_blas_zgemv(CblasNoTrans, GSL_COMPLEX_ONE, &U_TR.matrix, &lb.vector, GSL_COMPLEX_ONE, &ut.vector);\n }\n }\n else\n {\n gsl_vector_complex_view v = gsl_matrix_complex_subrow(LU, i, 0, i);\n gsl_blas_zscal(Uii, &v.vector);\n }\n }\n }\n else\n {\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ntriangular_mult_L3()\n Compute U L or L U\n\nInputs: Uplo - CblasUpper or CblasLower (for the first triangular factor)\n A - on input, matrix in LU format;\n on output, U L or L U\n\nReturn: success/error\n*/\n\nstatic int\ntriangular_mult_L3(CBLAS_UPLO_t Uplo, gsl_matrix_complex * A)\n{\n const size_t N = A->size1;\n\n if (N != A->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else if (N <= CROSSOVER_TRIMULT)\n {\n return triangular_mult_L2(Uplo, A);\n }\n else\n {\n /* partition matrix:\n *\n * A11 A12\n * A21 A22\n *\n * where A11 is N1-by-N1\n */\n int status;\n const size_t N1 = GSL_LINALG_SPLIT_COMPLEX(N);\n const size_t N2 = N - N1;\n gsl_matrix_complex_view A11 = gsl_matrix_complex_submatrix(A, 0, 0, N1, N1);\n gsl_matrix_complex_view A12 = gsl_matrix_complex_submatrix(A, 0, N1, N1, N2);\n gsl_matrix_complex_view A21 = gsl_matrix_complex_submatrix(A, N1, 0, N2, N1);\n gsl_matrix_complex_view A22 = gsl_matrix_complex_submatrix(A, N1, N1, N2, N2);\n\n /* recursion on A11 */\n status = triangular_mult_L3(Uplo, &A11.matrix);\n if (status)\n return status;\n\n if (Uplo == CblasLower)\n {\n }\n else\n {\n /* form U * L */\n\n /* A11 += A12 A21 */\n gsl_blas_zgemm(CblasNoTrans, CblasNoTrans, GSL_COMPLEX_ONE, &A12.matrix, &A21.matrix, GSL_COMPLEX_ONE, &A11.matrix);\n\n /* A12 = A12 * L22 */\n gsl_blas_ztrmm(CblasRight, CblasLower, CblasNoTrans, CblasUnit, GSL_COMPLEX_ONE, &A22.matrix, &A12.matrix);\n\n /* A21 = U22 * A21 */\n gsl_blas_ztrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, GSL_COMPLEX_ONE, &A22.matrix, &A21.matrix);\n }\n\n /* recursion on A22 */\n status = triangular_mult_L3(Uplo, &A22.matrix);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n }\n}\n\nstatic void\ncomplex_conj_vector(gsl_vector_complex * v)\n{\n size_t i;\n\n for (i = 0; i < v->size; ++i)\n {\n gsl_complex * vi = gsl_vector_complex_ptr(v, i);\n GSL_IMAG(*vi) = -GSL_IMAG(*vi);\n }\n}\n", "meta": {"hexsha": "7410247e553449bf3a446424514e13ee2e67326b", "size": 10066, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/linalg/trimult_complex.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/linalg/trimult_complex.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/trimult_complex.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 28.1173184358, "max_line_length": 126, "alphanum_fraction": 0.5824557918, "num_tokens": 2849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834734, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.44794425074699296}} {"text": "/* \r\n * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\r\n */\r\n\r\n#ifndef _GSL_BOOST_UBLAS_MATRIX_PROD_\r\n#define _GSL_BOOST_UBLAS_MATRIX_PROD_\r\n\r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\nnamespace boost { namespace numeric { namespace ublas {\r\n\r\n /* \r\n * GSL has separate implementations for floats and doubles\r\n * hence we first have specializations for these two types\r\n * TSeparate templates for diagonal and symmetric matreces\r\n * and their combinations. To check whether a specific\r\n * routine is called, define GSLDEBUG\r\n */\r\n \r\n // partial specialization for double precision (dgemm))\r\n template\r\n inline matrix // prod( m1, m2 )\r\n prod(const matrix &m1, const matrix &m2)\r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;34mGSL [CMD,CM]\\x1b[0;39m\\n\" << std::flush;\r\n #endif\r\n \r\n gsl_matrix_const_view mA = gsl_matrix_const_view_array (&m1(0,0), m1.size1(), m1.size2());\r\n gsl_matrix_const_view mB = gsl_matrix_const_view_array (&m2(0,0), m2.size1(), m2.size2());\r\n\r\n boost::numeric::ublas::matrix AxB( m1.size1(), m2.size2() );\r\n gsl_matrix_view mC = gsl_matrix_view_array (&AxB(0,0), AxB.size1(), AxB.size2());\r\n\r\n gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,\r\n 1.0, &mA.matrix, &mB.matrix,\r\n 0.0, &mC.matrix);\r\n return AxB;\r\n } \r\n \r\n // partial specialization for single precision (sgemm))\r\n template\r\n inline matrix // prod( m1, m2 )\r\n prod(const matrix &m1, const matrix &m2)\r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;34mGSL [CMS,CM]\\x1b[0;39m\\n\" << std::flush;\r\n #endif\r\n \r\n gsl_matrix_float_const_view mA = gsl_matrix_float_const_view_array (&m1(0,0), m1.size1(), m1.size2());\r\n gsl_matrix_float_const_view mB = gsl_matrix_float_const_view_array (&m2(0,0), m2.size1(), m2.size2());\r\n\r\n boost::numeric::ublas::matrix AxB( m1.size1(), m2.size2() );\r\n gsl_matrix_float_view mC = gsl_matrix_float_view_array (&AxB(0,0), AxB.size1(), AxB.size2());\r\n\r\n gsl_blas_sgemm (CblasNoTrans, CblasNoTrans,\r\n 1.0, &mA.matrix, &mB.matrix,\r\n 0.0, &mC.matrix);\r\n return AxB;\r\n } \r\n \r\n // full specialization \r\n template\r\n inline matrix // prod( m1, m2 )\r\n prod(const matrix &m1, const matrix &m2)\r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;34mGSL [CM,CM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n \r\n return prod(m1,m2);\r\n } \r\n \r\n /// transpose products\r\n template\r\n inline matrix // prod( trans(m1), m2 )\r\n prod(const matrix_unary2,scalar_identity > &m1, const matrix &m2)\r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;32mGSL [CTM,CM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n boost::numeric::ublas::matrix _m1 = m1;\r\n return prod(_m1,m2);\r\n } \r\n \r\n template\r\n inline matrix // prod( m1, trans(m2) )\r\n prod(const matrix &m1, const matrix_unary2,scalar_identity > &m2)\r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;32mGSL [CM,CTM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n \r\n const boost::numeric::ublas::matrix _m2 = m2;\r\n return prod(m1,_m2);\r\n } \r\n \r\n template\r\n inline matrix // prod( trans(m1), trans(m2) )\r\n prod(const matrix_unary2,scalar_identity > &m1, const matrix_unary2,scalar_identity > &m2) \r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;32mGSL [CTM,CTM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n \r\n boost::numeric::ublas::matrix _m1 = m1;\r\n boost::numeric::ublas::matrix _m2 = m2;\r\n \r\n return prod(_m1,_m2);\r\n } \r\n\r\n /// diagonal matrix\r\n template\r\n inline matrix // prod( diagonal m1, m2 )\r\n prod(const diagonal_matrix &m1, const matrix &m2 ) \r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;33mGSL [CDM, CM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n const matrix _m1 = m1; \r\n return prod(_m1,m2);\r\n }\r\n\r\n template\r\n inline matrix // prod( m1, diagonal m2 )\r\n prod(const matrix &m1, const diagonal_matrix &m2 ) \r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;33mGSL [CM, CDM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n const matrix _m2 = m2; \r\n return prod(m1,_m2);\r\n }\r\n\r\n template\r\n inline matrix // prod( diagonal m1, diagonal m2 )\r\n prod(const diagonal_matrix &m1, const diagonal_matrix &m2 ) \r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;33mGSL [CDM, CM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n const matrix _m1 = m1; \r\n const matrix _m2 = m2; \r\n return prod(_m1,_m2);\r\n } \r\n \r\n template\r\n inline matrix // prod( diagonal m1, transpose m2 )\r\n prod(const diagonal_matrix &m1, const matrix_unary2,scalar_identity > &m2) \r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;33mGSL [CDM, CTM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n\r\n const matrix _m1 = m1; \r\n const matrix _m2 = m2; \r\n \r\n return prod(_m1,_m2);\r\n \r\n }\r\n\r\n template\r\n inline matrix // prod( transpose m1, diagonal m2 )\r\n prod(const matrix_unary2,scalar_identity > &m1, const diagonal_matrix &m2) \r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;33mGSL [CTM, CDM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n\r\n const matrix _m1 = m1; \r\n const matrix _m2 = m2; \r\n \r\n return prod(_m1,_m2);\r\n \r\n }\r\n \r\n // symmetric matrix \r\n template\r\n inline matrix // prod( symmetric m1, m2 )\r\n prod(symmetric_matrix &m1, matrix &m2 ) \r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;33mGSL [CSM, CM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n \r\n assert( m1.size1() == m2.size1() );\r\n const matrix _m1 = m1; \r\n \r\n return prod(_m1, m2 );\r\n } \r\n\r\n template\r\n inline matrix // prod( m1, symmetric m2 )\r\n prod( matrix &m1, symmetric_matrix &m2 ) \r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;33mGSL [CSM, CM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n \r\n assert( m1.size1() == m2.size1() );\r\n const matrix _m2 = m2; \r\n \r\n return prod(m1, _m2 );\r\n } \r\n\r\n template\r\n inline matrix // prod( symmetric m1, symmetric m2 )\r\n prod(symmetric_matrix &m1, symmetric_matrix &m2 ) \r\n {\r\n #ifdef GSLDEBUG \r\n std::cout << \"\\x1b[0;33mGSL [CSM, CM]\\x1b[0;39m -> \" << std::flush;\r\n #endif\r\n \r\n assert( m1.size1() == m2.size1() );\r\n const matrix _m1 = m1; \r\n const matrix _m2 = m2; \r\n \r\n return prod(_m1, _m2 );\r\n } \r\n \r\n}}}\r\n\r\n#endif // _GSL_BOOST_UBLAS_MATRIX_PROD_ \r\n", "meta": {"hexsha": "3adf97710750d226f2fdff9ce995576710c00080", "size": 8641, "ext": "h", "lang": "C", "max_stars_repo_path": "include/votca/ctp/votca_gsl_boost_ublas_matrix_prod.h", "max_stars_repo_name": "mbarbry/ctp", "max_stars_repo_head_hexsha": "8461ba9d012c7e171a05e0b114b59d0523fc9a56", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/votca/ctp/votca_gsl_boost_ublas_matrix_prod.h", "max_issues_repo_name": "mbarbry/ctp", "max_issues_repo_head_hexsha": "8461ba9d012c7e171a05e0b114b59d0523fc9a56", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/votca/ctp/votca_gsl_boost_ublas_matrix_prod.h", "max_forks_repo_name": "mbarbry/ctp", "max_forks_repo_head_hexsha": "8461ba9d012c7e171a05e0b114b59d0523fc9a56", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8547717842, "max_line_length": 133, "alphanum_fraction": 0.5565328087, "num_tokens": 2696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6150878696277513, "lm_q1q2_score": 0.4477688680088836}} {"text": "/*\n * author: Achim Gaedke\n * created: May 2001\n * file: pygsl/src/sfmodule.c\n * $Id: sfmodule.c,v 1.3 2006/07/13 16:01:00 schnizer Exp $\n */\n#include \n#include \n#include \n#include \n\n\n\nstatic PyObject* gsl_module_error;\n\nint eval_gsl_mode_char(gsl_mode_t* mode, char mode_char) {\n\n char error_text[]=\"illegal gsl_mode\";\n PyObject* gsl_error_object;\n PyObject* gsl_error_module;\n PyObject* gsl_error_dict;\n\n switch (mode_char)\n {\n case 's':\n case 'S':\n *mode=GSL_PREC_SINGLE;\n return 0;\n case 'a':\n case 'A':\n *mode=GSL_PREC_APPROX;\n return 0;\n case 'd':\n case 'D':\n *mode=GSL_PREC_DOUBLE;\n return 0;\n }\n /* must set exception */\n gsl_error_module=PyImport_ImportModule(\"pygsl.errors\");\n gsl_error_dict=PyModule_GetDict(gsl_error_module);\n gsl_error_object=PyDict_GetItemString(gsl_error_dict,\"gsl_Error\");\n PyErr_SetObject(gsl_error_object,\n\t\t PyString_FromString(error_text));\n\n return -1;\n}\n\nstatic PyObject* gsl_sf_gauss(PyObject *self,\n\t\t\t PyObject *args\n\t\t\t )\n{\n const double norm=1.0/M_SQRT2/M_SQRTPI;\n double x;\n double sigma=1.0;\n double mu=0;\n double tmp;\n gsl_sf_result result;\n int err_result;\n PyObject* python_result;\n\n if (!PyArg_ParseTuple(args, \"d|dd:gauss\", &x, &mu, &sigma))\n return NULL;\n \n /*use tmp as temporary variable*/\n tmp=((x-mu)/sigma);\n err_result=gsl_sf_exp_mult_e(tmp*tmp/-2.0,\n\t\t\t\t norm/sigma,\n\t\t\t\t &result);\n if (err_result)\n return NULL;\n\n python_result=PyTuple_New(2);\n if (python_result==NULL)\n return NULL;\n PyTuple_SetItem(python_result,0,PyFloat_FromDouble(result.val));\n PyTuple_SetItem(python_result,1,PyFloat_FromDouble(result.err));\n return python_result;\n}\n\n/*automatically wrapped functions*/\n#include \"sf_functions.c\"\n\nstatic PyMethodDef sfMethods[] = {\n#include \"sf_index.c\"\n {\"gauss\",gsl_sf_gauss, METH_VARARGS},\n {NULL, NULL} /* Sentinel */\n};\n\nDL_EXPORT(void) initsf(void)\n{\n PyObject* gsl_errors_module;\n PyObject* sf_module;\n PyObject* gsl_errors_dict;\n\n gsl_errors_module=PyImport_ImportModule (\"pygsl.errors\");\n init_pygsl();\n /* here is an error check needed! */\n gsl_errors_dict=PyModule_GetDict(gsl_errors_module);\n gsl_module_error=PyDict_GetItemString(gsl_errors_dict,\"gsl_Error\");\n sf_module=Py_InitModule(\"sf\", sfMethods);\n\n return;\n}\n", "meta": {"hexsha": "7c7087a08556c4054281baa813d8c92aacd5ab3a", "size": 2396, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/src/sfmodule.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/src/sfmodule.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/src/sfmodule.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 23.0384615385, "max_line_length": 69, "alphanum_fraction": 0.6999165275, "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.44753329338495906}} {"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file rk_3_2.c\n * \\brief Source file to optimize Runge-Kutta 3 steps 2nd order methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"rk.h\"\n#include \"rk_3_2.h\"\n\n#define DEBUG_RK_3_2 0 ///< macro to debug.\n\n/**\n * Function to obtain the coefficients of a 3 steps 2nd order Runge-Kutta \n * method.\n */\nint\nrk_tb_3_2 (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb, *r;\n#if DEBUG_RK_3_2\n fprintf (stderr, \"rk_tb_3_2: start\\n\");\n#endif\n tb = optimize->coefficient;\n r = optimize->random_data;\n t3 (tb) = 1.L;\n t1 (tb) = r[0];\n t2 (tb) = r[1];\n b21 (tb) = r[2];\n b32 (tb) = r[3];\n b31 (tb) = (0.5L - b32 (tb) * t2 (tb)) / t1 (tb);\n if (isnan (b31 (tb)))\n return 0;\n rk_b_3 (tb);\n#if DEBUG_RK_3_2\n rk_print_tb (optimize, \"rk_tb_3_2\", stderr);\n fprintf (stderr, \"rk_tb_3_2: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 3 steps 2nd order, 3rd order in\n * equations depending only in time, Runge-Kutta method.\n */\nint\nrk_tb_3_2t (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb, *r;\n#if DEBUG_RK_3_2\n fprintf (stderr, \"rk_tb_3_2t: start\\n\");\n#endif\n tb = optimize->coefficient;\n r = optimize->random_data;\n t3 (tb) = 1.L;\n t1 (tb) = r[0];\n t2 (tb) = r[1];\n b21 (tb) = r[2];\n b32 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb)));\n if (isnan (b32 (tb)))\n return 0;\n b31 (tb) = (0.5L - b32 (tb) * t2 (tb)) / t1 (tb);\n if (isnan (b31 (tb)))\n return 0;\n rk_b_3 (tb);\n#if DEBUG_RK_3_2\n rk_print_tb (optimize, \"rk_tb_3_2t\", stderr);\n fprintf (stderr, \"rk_tb_3_2t: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 3 steps 1st-2nd order Runge-Kutta \n * pair.\n */\nint\nrk_tb_3_2p (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb;\n#if DEBUG_RK_3_2\n fprintf (stderr, \"rk_tb_3_2p: start\\n\");\n#endif\n if (!rk_tb_3_2 (optimize))\n return 0;\n tb = optimize->coefficient;\n e31 (tb) = 0.L;\n rk_e_3 (tb);\n#if DEBUG_RK_3_2\n rk_print_e (optimize, \"rk_tb_3_2p\", stderr);\n fprintf (stderr, \"rk_tb_3_2p: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 3 steps 1st-2nd order, 1st-3rd order\n * in equations depending only in time, Runge-Kutta method.\n */\nint\nrk_tb_3_2tp (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb;\n#if DEBUG_RK_3_2\n fprintf (stderr, \"rk_tb_3_2tp: start\\n\");\n#endif\n if (!rk_tb_3_2t (optimize))\n return 0;\n tb = optimize->coefficient;\n e31 (tb) = 0.L;\n rk_e_3 (tb);\n#if DEBUG_RK_3_2\n rk_print_tb (optimize, \"rk_tb_3_2tp\", stderr);\n fprintf (stderr, \"rk_tb_3_2pt: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to calculate the objective function of a 3 steps 2nd order \n * Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_3_2 (RK * rk) ///< RK struct.\n{\n long double *tb;\n long double o;\n#if DEBUG_RK_3_2\n fprintf (stderr, \"rk_objective_tb_3_2: start\\n\");\n#endif\n tb = rk->tb->coefficient;\n o = fminl (0.L, b20 (tb));\n if (b30 (tb) < 0.L)\n o += b30 (tb);\n if (b31 (tb) < 0.L)\n o += b31 (tb);\n if (o < 0.L)\n {\n o = 40.L - o;\n goto end;\n }\n o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb)));\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\nend:\n#if DEBUG_RK_3_2\n fprintf (stderr, \"rk_objective_tb_3_2: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_3_2: end\\n\");\n#endif\n return o;\n}\n\n/**\n * Function to calculate the objective function of a 3 steps 2nd order, 3rd\n * order in equations depending only in time, Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_3_2t (RK * rk) ///< RK struct.\n{\n long double *tb;\n long double o;\n#if DEBUG_RK_3_2\n fprintf (stderr, \"rk_objective_tb_3_2t: start\\n\");\n#endif\n tb = rk->tb->coefficient;\n o = fminl (0.L, b20 (tb));\n if (b30 (tb) < 0.L)\n o += b30 (tb);\n if (b31 (tb) < 0.L)\n o += b31 (tb);\n if (b32 (tb) < 0.L)\n o += b32 (tb);\n if (o < 0.L)\n {\n o = 40.L - o;\n goto end;\n }\n o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb)));\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\nend:\n#if DEBUG_RK_3_2\n fprintf (stderr, \"rk_objective_tb_3_2t: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_3_2t: end\\n\");\n#endif\n return o;\n}\n", "meta": {"hexsha": "77d8716ebfc1f0b93c4c9f7145194ae4b75ffb17", "size": 5978, "ext": "c", "lang": "C", "max_stars_repo_path": "rk_3_2.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rk_3_2.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rk_3_2.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.547008547, "max_line_length": 80, "alphanum_fraction": 0.6567413851, "num_tokens": 2041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.44753328544992993}} {"text": "/* This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n General Public License for more details. You should have received\n a copy of the GNU General Public License along with this program;\n if not, write to the Free Foundation, Inc., 59 Temple Place, Suite\n 330, Boston, MA 02111-1307 USA\n\n From Robert M. Ziff, \"Four-tap shift-register-sequence\n random-number generators,\" Computers in Physics 12(4), Jul/Aug\n 1998, pp 385-392. A generalized feedback shift-register (GFSR)\n is basically an xor-sum of particular past lagged values. A \n four-tap register looks like:\n ra[nd] = ra[nd-A] ^ ra[nd-B] ^ ra[nd-C] ^ ra[nd-D]\n \n Ziff notes that \"it is now widely known\" that two-tap registers\n have serious flaws, the most obvious one being the three-point\n correlation that comes from the defn of the generator. Nice\n mathematical properties can be derived for GFSR's, and numerics\n bears out the claim that 4-tap GFSR's with appropriately chosen\n offsets are as random as can be measured, using the author's test.\n\n This implementation uses the values suggested the the author's\n example on p392, but altered to fit the GSL framework. The \"state\"\n is 2^14 longs, or 64Kbytes; 2^14 is the smallest power of two that\n is larger than D, the largest offset. We really only need a state\n with the last D values, but by going to a power of two, we can do a\n masking operation instead of a modulo, and this is presumably\n faster, though I haven't actually tried it. The article actually\n suggested a short/fast hack:\n\n #define RandomInteger (++nd, ra[nd&M]=ra[(nd-A)&M]\\\n ^ra[(nd-B)&M]^ra[(nd-C)&M]^ra[(nd-D)&M])\n\n so that (as long as you've defined nd,ra[M+1]), then you ca do things\n like: 'if (RandomInteger < p) {...}'.\n\n Note that n&M varies from 0 to M, *including* M, so that the\n array has to be of size M+1. Since M+1 is a power of two, n&M\n is a potentially quicker implementation of the equivalent n%(M+1).\n\n This implementation copyright (C) 1998 James Theiler, based on\n the example mt.c in the GSL, as implemented by Brian Gough.\n*/\n\n#include \n#include \n#include \n\nstatic inline unsigned long int gfsr4_get (void *vstate);\nstatic double gfsr4_get_double (void *vstate);\nstatic void gfsr4_set (void *state, unsigned long int s);\n\n/* Magic numbers */\n#define A 471\n#define B 1586\n#define C 6988\n#define D 9689\n#define M 16383 /* = 2^14-1 */\n/* #define M 0x0003fff */\n\ntypedef struct\n {\n int nd;\n unsigned long ra[M+1];\n }\ngfsr4_state_t;\n\nstatic inline unsigned long\ngfsr4_get (void *vstate)\n{\n gfsr4_state_t *state = (gfsr4_state_t *) vstate;\n\n state->nd = ((state->nd)+1)&M;\n return state->ra[(state->nd)] =\n state->ra[((state->nd)+(M+1-A))&M]^\n state->ra[((state->nd)+(M+1-B))&M]^\n state->ra[((state->nd)+(M+1-C))&M]^\n state->ra[((state->nd)+(M+1-D))&M];\n \n}\n\nstatic double\ngfsr4_get_double (void * vstate)\n{\n return gfsr4_get (vstate) / 4294967296.0 ;\n}\n\nstatic void\ngfsr4_set (void *vstate, unsigned long int s)\n{\n gfsr4_state_t *state = (gfsr4_state_t *) vstate;\n int i, j;\n /* Masks for turning on the diagonal bit and turning off the\n leftmost bits */\n unsigned long int msb = 0x80000000UL;\n unsigned long int mask = 0xffffffffUL;\n\n if (s == 0)\n s = 4357; /* the default seed is 4357 */\n\n /* We use the congruence s_{n+1} = (69069*s_n) mod 2^32 to\n initialize the state. This works because ANSI-C unsigned long\n integer arithmetic is automatically modulo 2^32 (or a higher\n power of two), so we can safely ignore overflow. */\n\n#define LCG(n) ((69069 * n) & 0xffffffffUL)\n\n /* Brian Gough suggests this to avoid low-order bit correlations */\n for (i = 0; i <= M; i++)\n {\n unsigned long t = 0 ;\n unsigned long bit = msb ;\n for (j = 0; j < 32; j++)\n {\n s = LCG(s) ;\n if (s & msb) \n t |= bit ;\n bit >>= 1 ;\n }\n state->ra[i] = t ;\n }\n\n /* Perform the \"orthogonalization\" of the matrix */\n /* Based on the orthogonalization used in r250, as suggested initially\n * by Kirkpatrick and Stoll, and pointed out to me by Brian Gough\n */\n\n /* BJG: note that this orthogonalisation doesn't have any effect\n here because the the initial 6695 elements do not participate in\n the calculation. For practical purposes this orthogonalisation\n is somewhat irrelevant, because the probability of the original\n sequence being degenerate should be exponentially small. */\n\n for (i=0; i<32; ++i) {\n int k=7+i*3;\n state->ra[k] &= mask; /* Turn off bits left of the diagonal */\n state->ra[k] |= msb; /* Turn on the diagonal bit */\n mask >>= 1;\n msb >>= 1;\n }\n\n state->nd = i;\n}\n\nstatic const gsl_rng_type gfsr4_type =\n{\"gfsr4\", /* name */\n 0xffffffffUL, /* RAND_MAX */\n 0, /* RAND_MIN */\n sizeof (gfsr4_state_t),\n &gfsr4_set,\n &gfsr4_get,\n &gfsr4_get_double};\n\nconst gsl_rng_type *gsl_rng_gfsr4 = &gfsr4_type;\n\n\n\n\n\n", "meta": {"hexsha": "10d15e76a4a5db253dc1505de5d267d2efe9f931", "size": 5513, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/rng/gfsr4.c", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/rng/gfsr4.c", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/rng/gfsr4.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 33.2108433735, "max_line_length": 72, "alphanum_fraction": 0.6564483947, "num_tokens": 1594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.44741289198530904}} {"text": "//\n// main.c\n// ODE_MODEL\n//\n// Created by Kari Heine on 28/10/2020.\n// Copyright © 2020 Kari Heine. All rights reserved.\n//\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"particle_filters.h\"\n\n#define MAX_TEST_MESH_SIZE 4000 // Mesh size for BPF and MLBPF level 1 (the truth mesh size)\n#define N_SETTINGS 500 // Number of different scenarios\n#define N_SCALES 1 // Scaling samplesizes to study convergence\n#define N_MEASUREMENTS 2 // Number of places where the beam deflection is measured\n\nvoid generate_signal(double* x, int len, double std_sig, double x0, gsl_rng* rng, double L);\nvoid create_dense_solver_matrix(double* A, int n);\nvoid init_with_zeros(double* array, long length);\nvoid make_lapack_band_matrix(double *A, int n, double *ab, int ku, int kl);\ndouble compute_estimation_error(double* x_hat, double* x_ref, int len);\nvoid particle_allocation_time_matching(int max_mesh_size, int* level_0_mesh_sizes, int n_level_0_mesh_sizes, int bpf_sample_size, double std_sig, double obs_std, int data_length, double x0, double *y, int kl, int ku, double* ab_bpf, int ldab, double w, double d, double E, double I, double h_bpf, double *ab0, double h1, double L, double* meass, int N_meas);\nvoid get_settings(int** settings);\nvoid write_beam_in_file(int data_length, int true_mesh_size, double h, double* beam);\n\nint main(void) {\n \n gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus);\n gsl_rng_set(rng,clock());\n// gsl_rng_set(rng,42);\n \n /* Global parameters */\n /* ----------------- */\n int N_top = 250; // Top leve Monte Carlo iterations\n int kl = 3; // Lower diagonal bandwidth for the ODE solver\n int ku = 3; // upper diagonal bandwidth for the ODE solver\n int ldab = 2 * kl + ku + 1; // parameter for Lapack DGBSV\n int run_time_matching = 0; // This toggle (0 or 1) determines if we want to run time matching or filtering\n int N_ref = 100000; // Sample size for the reference filter\n \n /* Signal and observations */\n /* ----------------------- */\n int data_length = 50; // number of time steps\n double x0 = 2; // initial state\n double std_sig = 0.02; // signal noise standard deviation\n double obs_std = 0.0002; // observation noise standard deviation\n \n // Data arrays for the signal and observations\n double* x = (double*) malloc(data_length * sizeof(double));\n double* y = (double*) malloc(N_MEASUREMENTS * data_length * sizeof(double));\n FILE * data_out;\n \n /* Euler-Bernoulli beam parameters */\n /* ------------------------------- */\n double L = 4; // Length (m)\n double w = 0.3; // Width (m)\n double d = 0.03; // thickness (m)\n double E = 1e10; // Young's modulus\n double I = w * d * d * d / (double) 12; // Inertia\n double measurements[N_MEASUREMENTS] = {1, 1.75}; // deflection measurement points along the beam (m)\n int minds[N_MEASUREMENTS]; // mesh point indices for the deflection measurement points\n \n /* Beam solver setup for data generation */\n /* ------------------------------------- */\n int true_mesh_size = MAX_TEST_MESH_SIZE;\n double* A = (double*) malloc(MAX_TEST_MESH_SIZE * MAX_TEST_MESH_SIZE * sizeof(double));\n int* ipiv = (int*) malloc(MAX_TEST_MESH_SIZE * sizeof(int));\n double* ab = (double*) malloc(ldab * MAX_TEST_MESH_SIZE * sizeof(double));\n double* ab_copy = (double*) malloc(ldab * MAX_TEST_MESH_SIZE * sizeof(double));\n double* signal_payload = (double*) malloc(MAX_TEST_MESH_SIZE * data_length * sizeof(double));\n double h = L / (double)(true_mesh_size-1);\n int ldb = true_mesh_size, info = 0;\n \n // Calculate the indices for the deflection measurement points.\n for(int i = 0; i < N_MEASUREMENTS; i++) {\n minds[i] = (int)((measurements[i] / L) * (double) true_mesh_size);\n }\n \n create_dense_solver_matrix(A, true_mesh_size);\n \n /* Convert the design matrix to general band representation */\n init_with_zeros(ab, ldab * true_mesh_size);\n make_lapack_band_matrix(A, true_mesh_size, ab, ku, kl);\n \n /* COMPARISON SETUP */\n /* ---------------- */\n FILE * error_out = fopen(\"error.txt\", \"w\");\n double bpf_MSE = 0;\n double mlbpf_MSE = 0;\n double scaler = 1;\n double bpf_MSE_error_matched = 0;\n \n /* BPF SETUP */\n /* --------- */\n double *x_hat_bpf = (double*) malloc(data_length * sizeof(double));\n double *x_ref = (double*) malloc(data_length * sizeof(double));\n double *p_ref = (double*) malloc(data_length * sizeof(double));\n FILE* ref_out;\n double filtering_time[4]; // array for time recording\n int N = 500;\n int mesh_size_bpf = MAX_TEST_MESH_SIZE;\n double* ab_bpf = ab;\n int* ipiv_bpf = ipiv;\n double h_bpf = L / (double) (mesh_size_bpf-1);\n \n create_dense_solver_matrix(A, mesh_size_bpf);\n init_with_zeros(ab_bpf, ldab*mesh_size_bpf);\n make_lapack_band_matrix(A, mesh_size_bpf, ab_bpf, ku, kl);\n \n /* MLBPF SETUP */\n /* ----------- */\n double worst_case_sign_ratio[1] = { 100 }; // This is basically sustitute for \"Inf\"\n double *x_hats_mlbpf = (double*) malloc(data_length * sizeof(double));\n int mesh_sizes[2] = {10, 500}; // these values will be overwritten\n int N0, N1;\n \n double* ab0 = (double*) malloc(ldab * MAX_TEST_MESH_SIZE * sizeof(double));\n double* ab1 = ab;\n int* ipiv0 = ipiv;\n int* ipiv1 = ipiv;\n double h0;\n \n init_with_zeros(ab0, ldab * MAX_TEST_MESH_SIZE);\n init_with_zeros(ab1, ldab * MAX_TEST_MESH_SIZE);\n \n // We can create the solver matrices for level 1 only which has fixed mesh size\n create_dense_solver_matrix(A, MAX_TEST_MESH_SIZE);\n make_lapack_band_matrix(A, MAX_TEST_MESH_SIZE, ab1, ku, kl);\n double h1 = L / (double)(MAX_TEST_MESH_SIZE - 1);\n \n if(run_time_matching) {\n /*\n * Particle allocation time matching\n *\n * This part of the code should be run when trying to find the correct N0 sample sizes to match the\n * BPF running time\n */\n int max_mesh_size = MAX_TEST_MESH_SIZE;\n int level_0_mesh_sizes[20] = {100, 105, 110, 115, 120, 130, 140, 150, 160, 180, 200, 220, 240, 260, 280, 320, 360, 400, 440, 500};\n int n_level_0_mesh_sizes = 20;\n \n generate_signal(x, data_length, std_sig, x0, rng, L);\n create_payload(data_length, true_mesh_size, signal_payload, w, d, x, h, E, I, L);\n \n array_copy(ab, ab_copy, ldab * true_mesh_size); // Restore undamaged band matrix\n \n // Solve the Euler-Bernoulli beam\n dgbsv_(&true_mesh_size, &kl, &ku, &data_length, ab_copy, &ldab, ipiv, signal_payload, &ldb, &info);\n \n // Generate measurements\n for(int i = 0; i < data_length; i++)\n for(int j = 0; j < N_MEASUREMENTS; j++)\n y[i + j * data_length] = signal_payload[i * true_mesh_size + minds[j]] + gsl_ran_gaussian(rng, obs_std);\n \n particle_allocation_time_matching(max_mesh_size, level_0_mesh_sizes, n_level_0_mesh_sizes, N, std_sig, obs_std, data_length, x0, y, kl, ku, ab_bpf, ldab, w, d, E, I, h_bpf, ab0, h1, L, measurements, N_MEASUREMENTS);\n \n printf(\"Particle allocation time matching done! Exiting...\\n\");\n return 0; // the code exits\n }\n \n /*\n * THIS IS THE ACTUAL FILTER COMPARISON PART\n */\n \n // Settings are hard coded here. TODO: This should be changed to reading a file.\n int** settings = (int **)malloc(N_SETTINGS * sizeof(int*));\n for(int i = 0; i < N_SETTINGS; i++)\n settings[i] = (int *) malloc(4*sizeof(int));\n int sample_sizes[2] = {0,0};\n get_settings(settings);\n \n // Top level iteration\n for(int nmc = 0; nmc < N_top; nmc++) {\n \n printf(\"Top level iteration %i out of %i.*****************************\\n\", nmc + 1, N_top);\n \n /* To save computational time and also to take into account the possibility that a particular\n data set is more favourable to one or the other algorithm, we create new data every nth top\n level iteration, and compute the reference filter.\n */\n if (nmc % 10 == 0) {\n \n // Create the signal\n generate_signal(x, data_length, std_sig, x0, rng, L);\n\n printf(\"Signal generated\\n\");\n fflush(stdout);\n\n create_payload(data_length, true_mesh_size, signal_payload, w, d, x, h, E, I, L);\n\n printf(\"Payload created\\n\");\n fflush(stdout);\n \n array_copy(ab, ab_copy, ldab * true_mesh_size);\n \n // Solve the Euler-Bernoulli beam\n dgbsv_(&true_mesh_size, &kl, &ku, &data_length, ab_copy, &ldab, ipiv, signal_payload, &ldb, &info);\n \n printf(\"\\nBeam solved. Info: %i\\n\\n\",info);\n fflush(stdout);\n \n // write_beam_in_file(data_length, true_mesh_size, h, signal_payload);\n \n // Generate the noisy measurements\n data_out = fopen(\"data.txt\",\"w\");\n for(int i = 0; i < data_length; i++) {\n \n // Noisy measurements for one time step but all measurement points\n for(int j = 0; j < N_MEASUREMENTS; j++) {\n y[i + j*data_length] = signal_payload[i * true_mesh_size + minds[j]] + gsl_ran_gaussian(rng, obs_std);\n }\n \n fprintf(data_out,\"%i %e \",i, x[i]); // write true signal into a file\n for(int j = 0; j < N_MEASUREMENTS; j++) {\n // write noisy and noiseless observation into a file\n fprintf(data_out,\"%6.6e %6.6e \", y[i+j*data_length], signal_payload[i * true_mesh_size + minds[j]]);\n }\n fprintf(data_out,\"\\n\");\n }\n fclose(data_out);\n \n printf(\"Data generated\\n\");\n \n /* Compute a reference solution */\n printf(\"Reference filter with N_ref = %i\\n\", N_ref);\n fflush(stdout);\n bootstrapfilter(y, std_sig, obs_std, data_length, x0, N_ref, x_ref, p_ref, filtering_time, mesh_size_bpf, kl, ku, ab_bpf, ldab, ipiv_bpf, mesh_size_bpf, info, w, d, E, I, h_bpf, L, measurements, (int)N_MEASUREMENTS);\n \n // Write the reference filter output into a file with columns:\n // step index, posterior mean, posterior variance, true signal, observation\n ref_out = fopen(\"ref_filter_out.txt\",\"w\");\n for(int i = 0; i < data_length;i++)\n fprintf(ref_out,\"%i %e %e %e %e\\n\",i,x_ref[i],p_ref[i],x[i],y[i]);\n fclose(ref_out);\n \n // return 0; // option to exit after reference filter may be useful in debugging\n \n }\n \n /* Run the benchmark BPF */\n // NB: This is not the reference, but a comparison filter which is time is matched to MLBPF\n bootstrapfilter(y, std_sig, obs_std, data_length, x0, N, x_hat_bpf, NULL, filtering_time, mesh_size_bpf, kl, ku, ab_bpf, ldab, ipiv_bpf, mesh_size_bpf, info, w, d, E, I, h_bpf, L, measurements, (int)N_MEASUREMENTS);\n \n // bpf_MSE = compute_estimation_error(x_hat_bpf,x,data_length); // compute the error w.r.t. the truth\n bpf_MSE = compute_estimation_error(x_hat_bpf,x_ref,data_length);\n \n // Write the results in a file\n fprintf(error_out, \"%e %i %i %f %i %e %e %f %e %f %i\\n\", bpf_MSE, 0, N, filtering_time[0], 0, filtering_time[1], filtering_time[2], worst_case_sign_ratio[0], filtering_time[3], scaler, mesh_size_bpf);\n \n /* Compute the error matched BPF */\n // The ERROR matched filter, i.e. it produces roughly the same level of error, but hopefully takes\n // much longer to achieve it.\n printf(\"Error matched filter\\n\");\n bootstrapfilter(y, std_sig, obs_std, data_length, x0, 4*N, x_hat_bpf, NULL, filtering_time, mesh_size_bpf, kl, ku, ab_bpf, ldab, ipiv_bpf, mesh_size_bpf, info, w, d, E, I, h_bpf, L, measurements, (int)N_MEASUREMENTS);\n \n // bpf_MSE = compute_estimation_error(x_hat_bpf,x,data_length); // compute the error w.r.t. the truth\n bpf_MSE_error_matched = compute_estimation_error(x_hat_bpf,x_ref,data_length);\n \n // Write the results in a file\n fprintf(error_out, \"%e %i %i %f %i %e %e %f %e %f %i\\n\", bpf_MSE_error_matched, 0, N, filtering_time[0], -1, filtering_time[1], filtering_time[2], worst_case_sign_ratio[0], filtering_time[3], scaler, mesh_size_bpf);\n \n /* Iterate over different mesh size and particle allocation configurations */\n for(int i_setting = 0; i_setting < N_SETTINGS; i_setting++) {\n \n // Rename\n sample_sizes[0] = settings[i_setting][0];\n sample_sizes[1] = settings[i_setting][1];\n mesh_sizes[0] = settings[i_setting][2];\n mesh_sizes[1] = settings[i_setting][3];\n \n // Ensure odd number of particles\n sample_sizes[0] = (sample_sizes[0] + sample_sizes[1]) % 2 == 0 ? sample_sizes[0] + 1 : sample_sizes[0];\n \n init_with_zeros(ab0, ldab * mesh_sizes[0]);\n create_dense_solver_matrix(A, mesh_sizes[0]);\n make_lapack_band_matrix(A, mesh_sizes[0], ab0, ku, kl);\n h0 = L / (double)(mesh_sizes[0] - 1);\n \n printf(\"Setting %i out of %i\\n\",i_setting+1,N_SETTINGS);\n fflush(stdout);\n \n MLbootstrapfilter(y, std_sig, obs_std, data_length, x0, sample_sizes, worst_case_sign_ratio, x_hats_mlbpf, filtering_time, mesh_sizes, kl, ku, ab0, ab1, ldab, ipiv0, ipiv1, mesh_sizes[0], mesh_sizes[1], info, w, d, E, I, h0, h1, L, measurements, (int)N_MEASUREMENTS);\n \n // mlbpf_MSE = compute_estimation_error(x_hats_mlbpf,x,data_length);\n mlbpf_MSE = compute_estimation_error(x_hats_mlbpf,x_ref,data_length);\n \n N0 = sample_sizes[0];\n N1 = sample_sizes[1];\n \n fprintf(error_out, \"%e %i %i %f %i %e %e %f %e %f %i\\n\", mlbpf_MSE, N0, N1, filtering_time[0], i_setting + 1, filtering_time[1], filtering_time[2], worst_case_sign_ratio[0], filtering_time[3], scaler, mesh_sizes[0]);\n fflush(error_out);\n \n }\n }\n \n /* Free all that was allocated */\n free(x);\n free(y);\n free(A);\n free(ipiv);\n free(ab);\n free(ab_copy);\n free(signal_payload);\n free(x_hat_bpf);\n free(x_ref);\n free(p_ref);\n free(x_hats_mlbpf);\n free(ab0);\n for(int i = 0; i < N_SETTINGS; i++)\n free(settings[i]);\n free(settings);\n \n return 0;\n}\n\nvoid write_beam_in_file(int data_length, int true_mesh_size, double h, double* beam) {\n \n FILE * payload_out = fopen(\"payload.txt\",\"w\");\n for(int i = 0; i < data_length; i++)\n for(int j = 0; j < true_mesh_size; j++)\n fprintf(payload_out, \"%5.5e %5.10e \\n\", j * h, beam[i * true_mesh_size + j]);\n fclose(payload_out);\n printf(\"Payload written in file\\n\");\n fflush(stdout);\n \n}\n\nvoid particle_allocation_time_matching(int max_mesh_size, int* level_0_mesh_sizes, int n_level_0_mesh_sizes, int bpf_sample_size, double std_sig, double obs_std, int data_length, double x0, double *y, int kl, int ku, double* ab_bpf, int ldab, double w, double d, double E, double I, double h_bpf, double *ab0, double h1, double L, double* meass, int N_meas) {\n \n int N1_step = 20;\n int N0_step = 10000;\n int N0_init = 10;\n int N_top = 5;\n double time_per_iteration;\n double time_tolerance = 1.00; //\n double filtering_time[4];\n int info = 0;\n int* ipiv = (int *) malloc(max_mesh_size * sizeof(int));\n double worst_case_sign_ratio[1] = { 100 };\n double* ab_copy = (double*) malloc(ldab * max_mesh_size * sizeof(double));\n double* ab0_copy = (double*) malloc(ldab * max_mesh_size * sizeof(double));\n double h0;\n double* A0 = (double*) malloc(MAX_TEST_MESH_SIZE * MAX_TEST_MESH_SIZE * sizeof(double));\n \n /* Find the reference time per iteration for BPF */\n double bpf_time_per_iteration = 0;\n for(int nmc = 0; nmc < N_top; nmc++) {\n \n for(int i = 0; i < ldab * max_mesh_size; i++)\n ab_copy[i] = ab_bpf[i];\n \n bootstrapfilter(y, std_sig, obs_std, data_length, x0, bpf_sample_size, NULL, NULL, filtering_time, max_mesh_size, kl, ku, ab_bpf, ldab, ipiv, max_mesh_size, info, w, d, E, I, h_bpf , L, meass, N_MEASUREMENTS);\n bpf_time_per_iteration += filtering_time[0] / (double) N_top;\n }\n \n printf(\"Time per iteration (BPF): %0.5f\\n\",bpf_time_per_iteration);\n fflush(stdout);\n \n int level_0_mesh_size;\n int sample_sizes[2] = {0,0};\n int mesh_sizes[2];\n int N0;\n short direction;\n \n FILE* out = fopen(\"time_matched_sample_sizes.txt\",\"w\");\n \n /* Iterate over level 0 mesh sizes */\n for(int j = 0; j < n_level_0_mesh_sizes; j++) {\n \n level_0_mesh_size = level_0_mesh_sizes[j];\n mesh_sizes[0] = level_0_mesh_size;\n mesh_sizes[1] = max_mesh_size;\n \n // We have to create A0 again for each mesh size\n for(int i = 0; i < ldab * mesh_sizes[0]; i++)\n ab0[i] = 0;\n create_dense_solver_matrix(A0, mesh_sizes[0]);\n make_lapack_band_matrix(A0, mesh_sizes[0], ab0, ku, kl);\n h0 = L / (double)(mesh_sizes[0] - 1);\n \n /* For given L0 mesh, iterate over N1 */\n for(int N1 = 0; N1 <= bpf_sample_size ; N1 = N1 + N1_step) {\n \n \n N0 = N0_init;\n N0_step = 10000;\n \n /* For given L0 mesh and N1 iterate over increasing N0 until MLBPF time per iteration exceeds\n BPF time per iteration */\n time_per_iteration = 0;\n \n direction = 1; // up\n while(1) {\n \n sample_sizes[0] = N0;\n sample_sizes[1] = N1;\n \n /* Estimate the time per iteration by averaging N_top runs */\n time_per_iteration = 0;\n for(int nmc = 0; nmc < N_top; nmc++) {\n \n for(int i = 0; i < ldab * max_mesh_size; i++)\n ab_copy[i] = ab_bpf[i];\n \n for(int i = 0; i < ldab * level_0_mesh_size; i++)\n ab0_copy[i] = ab0[i];\n \n MLbootstrapfilter(y, std_sig, obs_std, data_length, x0, sample_sizes, worst_case_sign_ratio, NULL, filtering_time, mesh_sizes, kl, ku, ab0_copy, ab_copy, ldab, ipiv, ipiv, mesh_sizes[0], max_mesh_size, info, w, d, E, I, h0, h1, L, meass, N_MEASUREMENTS);\n // printf(\"TIMES: %e %e %e %e\\n\", filtering_time[0], filtering_time[1], filtering_time[2], filtering_time[3]);\n // fflush(stdout);\n \n time_per_iteration += filtering_time[0] / (double) N_top;\n }\n \n if (direction == 1 && time_per_iteration > bpf_time_per_iteration * time_tolerance && N0_step > 10) {\n direction = -1; // start going down\n N0_step /= 2; // halve the step\n \n } else if (direction == -1 && time_per_iteration < bpf_time_per_iteration * 1.00 && N0_step > 10) {\n direction = 1;\n N0_step /= 2;\n } else if (N0_step < 10) {\n break;\n }\n N0 = N0 + direction * N0_step;\n \n if(N0 < 1) { // Make sure N0 remains positive and go up if this happens\n N0 = 1;\n direction = 1;\n }\n \n }\n fprintf(out,\"%i %i %i %i\\n\",N0-N0_step,N1,mesh_sizes[0],mesh_sizes[1]);\n fflush(out);\n }\n }\n fclose(out);\n \n free(ipiv);\n free(ab_copy);\n free(ab0_copy);\n free(A0);\n}\n\ndouble compute_estimation_error(double* x_hat, double* x_ref, int len) {\n \n double MSE = 0;\n \n for(int i = 0; i < len; i++) {\n MSE += (x_hat[i]-x_ref[i])*(x_hat[i]-x_ref[i]) / (double) len;\n }\n return MSE;\n}\n\nvoid init_with_zeros(double *array, long length) {\n for (int i = 0; i < length; i++)\n array[i] = 0;\n}\n\nvoid generate_signal(double* x, int len, double std_sig, double x0, gsl_rng* rng, double L) {\n \n double lower_bound = 0.25;\n double upper_bound = L - 0.25;\n x[0] = x0;\n \n for (int i = 1; i < len; i++){\n x[i] = x[i - 1] + gsl_ran_gaussian(rng, std_sig);\n // x[i] = 0.5 / ((double)1.0 + exp(-(double)10.0 * (x[i - 1] - 1))) + (double) 0.75 + gsl_ran_gaussian(rng, std_sig);\n if(x[i] < lower_bound)\n x[i] = lower_bound + lower_bound-x[i];\n if(x[i] > upper_bound)\n x[i] = upper_bound - (x[i]-upper_bound);\n }\n \n}\n\nvoid make_lapack_band_matrix(double *A, int n, double *ab, int ku, int kl) {\n \n int lower, upper, baserow,baserowcand ;\n int n_rows = 2 * kl + ku + 1;\n \n for (int j = 0; j < n; j++) { // iterate columns\n \n lower = j - ku > 0 ? j - ku : 0;\n upper = j + kl < n ? j + kl : n-1;\n \n baserowcand = n_rows - upper - 1;\n baserow = baserowcand < n_rows - (ku+kl+1)? n_rows - (ku+kl+1) : baserowcand;\n \n for (int i = lower; i <= upper; i++) {\n ab[n_rows * j + baserow + i - lower] = A[j * n + i];\n }\n }\n \n}\n\nvoid create_dense_solver_matrix(double* A, int n) {\n \n double pattern[5] = { 1, -4, 6, -4, 1 };\n /* Make sure there are zeros */\n for(int i = 0; i < n*n; i++)\n A[i] = 0;\n \n /* First two lines */\n for (int i = 0; i < n; i++) {\n A[i * n] = 0;\n A[i * n + 1] = 0;\n }\n \n A[0] = 16;\n A[1] = -4;\n A[n + 0] = -9;\n A[n + 1] = 6;\n A[2 * n + 0] = (double) 8 / (double) 3;\n A[2 * n + 1] = -4;\n A[3 * n + 0] = -(double) 1 / (double) 4;\n A[3 * n + 1] = (double) 1;\n \n /* Last two lines */\n for (int i = 0; i < n; i++) {\n A[i * n + n - 2] = 0;\n A[i * n + n - 1] = 0;\n }\n \n // A[(n - 4) * n + n - 2] = (double) 16 / (double) 17;\n A[(n - 4) * n + n - 2] = (double) 1;\n // A[(n - 4) * n + n - 1] = -(double) 12 / (double) 17;\n A[(n - 4) * n + n - 1] = -(double) 1 / (double) 4;\n // A[(n - 3) * n + n - 2] = -(double) 60 / (double) 17;\n A[(n - 3) * n + n - 2] = -(double) 4;\n // A[(n - 3) * n + n - 1] = (double) 96 / (double) 17;\n A[(n - 3) * n + n - 1] = (double) 8 / (double) 3;\n // A[(n - 2) * n + n - 2] = (double) 72 / (double) 17;\n A[(n - 2) * n + n - 2] = (double) 6;\n // A[(n - 2) * n + n - 1] = -(double) 156 / (double) 17;\n A[(n - 2) * n + n - 1] = -(double) 9;\n // A[(n - 1) * n + n - 2] = -(double) 28 / (double) 17;\n A[(n - 1) * n + n - 2] = -(double) 4;\n // A[(n - 1) * n + n - 1] = (double) 72 / (double) 17;\n A[(n - 1) * n + n - 1] = (double) 16;\n \n /* The rest */\n for (int i = 2; i < n - 2; i++) { // row\n for (int j = 0; j < n; j++) {\n A[j * n + i] = 0;\n }\n for (int j = 0; j < 5; j++)\n A[(j + i - 2) * n + i] = pattern[j];\n }\n}\n\nvoid get_settings(int** settings) {\n \n// /* THIS IS FOR N = 1000 */\n// int hc_settings[N_SETTINGS][4] = {\n// {38000, 0, 100, 4000},\n//{36835, 40, 100, 4000},\n//{36054, 80, 100, 4000},\n//{36439, 120, 100, 4000},\n//{35867, 160, 100, 4000},\n//{35658, 200, 100, 4000},\n//{34954, 240, 100, 4000},\n//{34888, 280, 100, 4000},\n//{34570, 320, 100, 4000},\n//{34237, 360, 100, 4000},\n//{33456, 400, 100, 4000},\n//{32811, 440, 100, 4000},\n//{32127, 480, 100, 4000},\n//{30799, 520, 100, 4000},\n//{29146, 560, 100, 4000},\n//{27180, 600, 100, 4000},\n//{24810, 640, 100, 4000},\n//{22713, 680, 100, 4000},\n//{20024, 720, 100, 4000},\n//{17349, 760, 100, 4000},\n//{14049, 800, 100, 4000},\n//{10800, 840, 100, 4000},\n//{7812, 880, 100, 4000},\n//{4960, 920, 100, 4000},\n//{2408, 960, 100, 4000},\n//{36965, 0, 105, 4000},\n//{36354, 40, 105, 4000},\n//{35552, 80, 105, 4000},\n//{34341, 120, 105, 4000},\n//{34073, 160, 105, 4000},\n//{33840, 200, 105, 4000},\n//{33970, 240, 105, 4000},\n//{33444, 280, 105, 4000},\n//{33079, 320, 105, 4000},\n//{32883, 360, 105, 4000},\n//{32615, 400, 105, 4000},\n//{32173, 440, 105, 4000},\n//{31021, 480, 105, 4000},\n//{29393, 520, 105, 4000},\n//{27453, 560, 105, 4000},\n//{25473, 600, 105, 4000},\n//{23605, 640, 105, 4000},\n//{21639, 680, 105, 4000},\n//{19367, 720, 105, 4000},\n//{16693, 760, 105, 4000},\n//{13229, 800, 105, 4000},\n//{10143, 840, 105, 4000},\n//{7134, 880, 105, 4000},\n//{4543, 920, 105, 4000},\n//{2108, 960, 105, 4000},\n//{35266, 0, 110, 4000},\n//{35461, 40, 110, 4000},\n//{35409, 80, 110, 4000},\n//{35058, 120, 110, 4000},\n//{34531, 160, 110, 4000},\n//{33971, 200, 110, 4000},\n//{33437, 240, 110, 4000},\n//{33026, 280, 110, 4000},\n//{32804, 320, 110, 4000},\n//{32765, 360, 110, 4000},\n//{32550, 400, 110, 4000},\n//{31659, 440, 110, 4000},\n//{30162, 480, 110, 4000},\n//{28254, 520, 110, 4000},\n//{26203, 560, 110, 4000},\n//{24055, 600, 110, 4000},\n//{21965, 640, 110, 4000},\n//{19192, 680, 110, 4000},\n//{16087, 720, 110, 4000},\n//{12969, 760, 110, 4000},\n//{10438, 800, 110, 4000},\n//{8172, 840, 110, 4000},\n//{5045, 880, 110, 4000},\n//{2513, 920, 110, 4000},\n//{605, 960, 110, 4000},\n//{32765, 0, 115, 4000},\n//{33038, 40, 115, 4000},\n//{33013, 80, 115, 4000},\n//{32440, 120, 115, 4000},\n//{31593, 160, 115, 4000},\n//{31444, 200, 115, 4000},\n//{31444, 240, 115, 4000},\n//{31235, 280, 115, 4000},\n//{30265, 320, 115, 4000},\n//{29243, 360, 115, 4000},\n//{29035, 400, 115, 4000},\n//{28579, 440, 115, 4000},\n//{27928, 480, 115, 4000},\n//{26274, 520, 115, 4000},\n//{24568, 560, 115, 4000},\n//{22960, 600, 115, 4000},\n//{21743, 640, 115, 4000},\n//{19972, 680, 115, 4000},\n//{17707, 720, 115, 4000},\n//{14634, 760, 115, 4000},\n//{11717, 800, 115, 4000},\n//{8586, 840, 115, 4000},\n//{6040, 880, 115, 4000},\n//{3749, 920, 115, 4000},\n//{1867, 960, 115, 4000},\n//{34171, 0, 120, 4000},\n//{33248, 40, 120, 4000},\n//{32916, 80, 120, 4000},\n//{33066, 120, 120, 4000},\n//{32969, 160, 120, 4000},\n//{32323, 200, 120, 4000},\n//{31901, 240, 120, 4000},\n//{31776, 280, 120, 4000},\n//{31932, 320, 120, 4000},\n//{31580, 360, 120, 4000},\n//{29759, 400, 120, 4000},\n//{29077, 440, 120, 4000},\n//{27950, 480, 120, 4000},\n//{27637, 520, 120, 4000},\n//{25709, 560, 120, 4000},\n//{23834, 600, 120, 4000},\n//{22322, 640, 120, 4000},\n//{20388, 680, 120, 4000},\n//{18175, 720, 120, 4000},\n//{15142, 760, 120, 4000},\n//{12278, 800, 120, 4000},\n//{9471, 840, 120, 4000},\n//{6984, 880, 120, 4000},\n//{4640, 920, 120, 4000},\n//{2362, 960, 120, 4000},\n//{32765, 0, 130, 4000},\n//{32765, 40, 130, 4000},\n//{32622, 80, 130, 4000},\n//{32244, 120, 130, 4000},\n//{31763, 160, 130, 4000},\n//{31249, 200, 130, 4000},\n//{30553, 240, 130, 4000},\n//{29629, 280, 130, 4000},\n//{29062, 320, 130, 4000},\n//{28794, 360, 130, 4000},\n//{28585, 400, 130, 4000},\n//{27778, 440, 130, 4000},\n//{26463, 480, 130, 4000},\n//{24966, 520, 130, 4000},\n//{23411, 560, 130, 4000},\n//{22420, 600, 130, 4000},\n//{20878, 640, 130, 4000},\n//{18827, 680, 130, 4000},\n//{15982, 720, 130, 4000},\n//{13273, 760, 130, 4000},\n//{10487, 800, 130, 4000},\n//{7955, 840, 130, 4000},\n//{6021, 880, 130, 4000},\n//{4524, 920, 130, 4000},\n//{2864, 960, 130, 4000},\n//{31926, 0, 140, 4000},\n//{31405, 40, 140, 4000},\n//{30917, 80, 140, 4000},\n//{30312, 120, 140, 4000},\n//{29876, 160, 140, 4000},\n//{29433, 200, 140, 4000},\n//{29055, 240, 140, 4000},\n//{28579, 280, 140, 4000},\n//{28058, 320, 140, 4000},\n//{27524, 360, 140, 4000},\n//{26952, 400, 140, 4000},\n//{26073, 440, 140, 4000},\n//{24790, 480, 140, 4000},\n//{23332, 520, 140, 4000},\n//{22290, 560, 140, 4000},\n//{21386, 600, 140, 4000},\n//{20128, 640, 140, 4000},\n//{17993, 680, 140, 4000},\n//{15493, 720, 140, 4000},\n//{12941, 760, 140, 4000},\n//{10454, 800, 140, 4000},\n//{7915, 840, 140, 4000},\n//{4605, 880, 140, 4000},\n//{1955, 920, 140, 4000},\n//{151, 960, 140, 4000},\n//{30538, 0, 150, 4000},\n//{29758, 40, 150, 4000},\n//{29140, 80, 150, 4000},\n//{28560, 120, 150, 4000},\n//{27948, 160, 150, 4000},\n//{27336, 200, 150, 4000},\n//{26984, 240, 150, 4000},\n//{26607, 280, 150, 4000},\n//{26458, 320, 150, 4000},\n//{26295, 360, 150, 4000},\n//{26256, 400, 150, 4000},\n//{25643, 440, 150, 4000},\n//{24537, 480, 150, 4000},\n//{23157, 520, 150, 4000},\n//{22245, 560, 150, 4000},\n//{21144, 600, 150, 4000},\n//{19712, 640, 150, 4000},\n//{17473, 680, 150, 4000},\n//{15058, 720, 150, 4000},\n//{12538, 760, 150, 4000},\n//{10024, 800, 150, 4000},\n//{7544, 840, 150, 4000},\n//{5396, 880, 150, 4000},\n//{3281, 920, 150, 4000},\n//{1581, 960, 150, 4000},\n//{22765, 0, 160, 4000},\n//{22186, 40, 160, 4000},\n//{21873, 80, 160, 4000},\n//{21821, 120, 160, 4000},\n//{21827, 160, 160, 4000},\n//{21827, 200, 160, 4000},\n//{21827, 240, 160, 4000},\n//{21801, 280, 160, 4000},\n//{21217, 320, 160, 4000},\n//{20965, 360, 160, 4000},\n//{20026, 400, 160, 4000},\n//{19770, 440, 160, 4000},\n//{18369, 480, 160, 4000},\n//{17388, 520, 160, 4000},\n//{15949, 560, 160, 4000},\n//{15012, 600, 160, 4000},\n//{13845, 640, 160, 4000},\n//{12595, 680, 160, 4000},\n//{11241, 720, 160, 4000},\n//{9887, 760, 160, 4000},\n//{8306, 800, 160, 4000},\n//{6561, 840, 160, 4000},\n//{4634, 880, 160, 4000},\n//{2800, 920, 160, 4000},\n//{1212, 960, 160, 4000},\n//{26379, 0, 180, 4000},\n//{26815, 40, 180, 4000},\n//{26880, 80, 180, 4000},\n//{26556, 120, 180, 4000},\n//{26235, 160, 180, 4000},\n//{25864, 200, 180, 4000},\n//{25637, 240, 180, 4000},\n//{25246, 280, 180, 4000},\n//{24940, 320, 180, 4000},\n//{24399, 360, 180, 4000},\n//{23846, 400, 180, 4000},\n//{23163, 440, 180, 4000},\n//{22564, 480, 180, 4000},\n//{21874, 520, 180, 4000},\n//{20963, 560, 180, 4000},\n//{19739, 600, 180, 4000},\n//{17562, 640, 180, 4000},\n//{14182, 680, 180, 4000},\n//{11115, 720, 180, 4000},\n//{8364, 760, 180, 4000},\n//{6770, 800, 180, 4000},\n//{5407, 840, 180, 4000},\n//{4314, 880, 180, 4000},\n//{3304, 920, 180, 4000},\n//{1678, 960, 180, 4000},\n//{25989, 0, 200, 4000},\n//{25488, 40, 200, 4000},\n//{25142, 80, 200, 4000},\n//{24654, 120, 200, 4000},\n//{24510, 160, 200, 4000},\n//{24119, 200, 200, 4000},\n//{23787, 240, 200, 4000},\n//{23384, 280, 200, 4000},\n//{22974, 320, 200, 4000},\n//{22558, 360, 200, 4000},\n//{22024, 400, 200, 4000},\n//{21729, 440, 200, 4000},\n//{21020, 480, 200, 4000},\n//{19978, 520, 200, 4000},\n//{18430, 560, 200, 4000},\n//{16893, 600, 200, 4000},\n//{15331, 640, 200, 4000},\n//{13443, 680, 200, 4000},\n//{11502, 720, 200, 4000},\n//{9549, 760, 200, 4000},\n//{7778, 800, 200, 4000},\n//{6007, 840, 200, 4000},\n//{4360, 880, 200, 4000},\n//{2870, 920, 200, 4000},\n//{1486, 960, 200, 4000},\n//{23624, 0, 220, 4000},\n//{23285, 40, 220, 4000},\n//{22934, 80, 220, 4000},\n//{22472, 120, 220, 4000},\n//{22075, 160, 220, 4000},\n//{21827, 200, 220, 4000},\n//{21814, 240, 220, 4000},\n//{21678, 280, 220, 4000},\n//{21327, 320, 220, 4000},\n//{20871, 360, 220, 4000},\n//{20343, 400, 220, 4000},\n//{19595, 440, 220, 4000},\n//{18599, 480, 220, 4000},\n//{17219, 520, 220, 4000},\n//{15890, 560, 220, 4000},\n//{14406, 600, 220, 4000},\n//{12882, 640, 220, 4000},\n//{11105, 680, 220, 4000},\n//{9314, 720, 220, 4000},\n//{7517, 760, 220, 4000},\n//{5818, 800, 220, 4000},\n//{4165, 840, 220, 4000},\n//{2694, 880, 220, 4000},\n//{1382, 920, 220, 4000},\n//{497, 960, 220, 4000},\n//{21398, 0, 240, 4000},\n//{21047, 40, 240, 4000},\n//{20754, 80, 240, 4000},\n//{20422, 120, 240, 4000},\n//{20154, 160, 240, 4000},\n//{19861, 200, 240, 4000},\n//{19607, 240, 240, 4000},\n//{19269, 280, 240, 4000},\n//{18892, 320, 240, 4000},\n//{18508, 360, 240, 4000},\n//{18098, 400, 240, 4000},\n//{17518, 440, 240, 4000},\n//{16593, 480, 240, 4000},\n//{15441, 520, 240, 4000},\n//{14230, 560, 240, 4000},\n//{12994, 600, 240, 4000},\n//{11594, 640, 240, 4000},\n//{9999, 680, 240, 4000},\n//{8320, 720, 240, 4000},\n//{6698, 760, 240, 4000},\n//{5188, 800, 240, 4000},\n//{3827, 840, 240, 4000},\n//{2532, 880, 240, 4000},\n//{1271, 920, 240, 4000},\n//{432, 960, 240, 4000},\n//{21730, 0, 260, 4000},\n//{21210, 40, 260, 4000},\n//{20839, 80, 260, 4000},\n//{20519, 120, 260, 4000},\n//{20083, 160, 260, 4000},\n//{19627, 200, 260, 4000},\n//{19223, 240, 260, 4000},\n//{18819, 280, 260, 4000},\n//{18383, 320, 260, 4000},\n//{18436, 360, 260, 4000},\n//{18449, 400, 260, 4000},\n//{18221, 440, 260, 4000},\n//{17270, 480, 260, 4000},\n//{16079, 520, 260, 4000},\n//{14790, 560, 260, 4000},\n//{13515, 600, 260, 4000},\n//{12141, 640, 260, 4000},\n//{10780, 680, 260, 4000},\n//{9257, 720, 260, 4000},\n//{7811, 760, 260, 4000},\n//{6313, 800, 260, 4000},\n//{4894, 840, 260, 4000},\n//{3631, 880, 260, 4000},\n//{2545, 920, 260, 4000},\n//{1614, 960, 260, 4000},\n//{21262, 0, 280, 4000},\n//{20890, 40, 280, 4000},\n//{20545, 80, 280, 4000},\n//{20129, 120, 280, 4000},\n//{19771, 160, 280, 4000},\n//{19367, 200, 280, 4000},\n//{18785, 240, 280, 4000},\n//{18355, 280, 280, 4000},\n//{17965, 320, 280, 4000},\n//{17739, 360, 280, 4000},\n//{17310, 400, 280, 4000},\n//{16619, 440, 280, 4000},\n//{15714, 480, 280, 4000},\n//{14588, 520, 280, 4000},\n//{13403, 560, 280, 4000},\n//{12238, 600, 280, 4000},\n//{10988, 640, 280, 4000},\n//{9673, 680, 280, 4000},\n//{8293, 720, 280, 4000},\n//{6984, 760, 280, 4000},\n//{5690, 800, 280, 4000},\n//{4491, 840, 280, 4000},\n//{3359, 880, 280, 4000},\n//{2362, 920, 280, 4000},\n//{1388, 960, 280, 4000},\n//{13585, 0, 320, 4000},\n//{13391, 40, 320, 4000},\n//{13202, 80, 320, 4000},\n//{12936, 120, 320, 4000},\n//{12610, 160, 320, 4000},\n//{12252, 200, 320, 4000},\n//{11985, 240, 320, 4000},\n//{11776, 280, 320, 4000},\n//{11567, 320, 320, 4000},\n//{11320, 360, 320, 4000},\n//{10989, 400, 320, 4000},\n//{10585, 440, 320, 4000},\n//{9993, 480, 320, 4000},\n//{9263, 520, 320, 4000},\n//{8462, 560, 320, 4000},\n//{7785, 600, 320, 4000},\n//{7232, 640, 320, 4000},\n//{6685, 680, 320, 4000},\n//{6047, 720, 320, 4000},\n//{5304, 760, 320, 4000},\n//{4503, 800, 320, 4000},\n//{3598, 840, 320, 4000},\n//{2648, 880, 320, 4000},\n//{1737, 920, 320, 4000},\n//{881, 960, 320, 4000},\n//{16086, 0, 360, 4000},\n//{15669, 40, 360, 4000},\n//{15330, 80, 360, 4000},\n//{15096, 120, 360, 4000},\n//{14796, 160, 360, 4000},\n//{14465, 200, 360, 4000},\n//{14075, 240, 360, 4000},\n//{13743, 280, 360, 4000},\n//{13455, 320, 360, 4000},\n//{13150, 360, 360, 4000},\n//{12786, 400, 360, 4000},\n//{12284, 440, 360, 4000},\n//{11554, 480, 360, 4000},\n//{10630, 520, 360, 4000},\n//{9686, 560, 360, 4000},\n//{8827, 600, 360, 4000},\n//{7960, 640, 360, 4000},\n//{6945, 680, 360, 4000},\n//{5904, 720, 360, 4000},\n//{4824, 760, 360, 4000},\n//{3840, 800, 360, 4000},\n//{2922, 840, 360, 4000},\n//{2108, 880, 360, 4000},\n//{1386, 920, 360, 4000},\n//{682, 960, 360, 4000},\n//{13802, 0, 400, 4000},\n//{13579, 40, 400, 4000},\n//{13338, 80, 400, 4000},\n//{13098, 120, 400, 4000},\n//{12799, 160, 400, 4000},\n//{12500, 200, 400, 4000},\n//{12180, 240, 400, 4000},\n//{11900, 280, 400, 4000},\n//{11613, 320, 400, 4000},\n//{11327, 360, 400, 4000},\n//{11021, 400, 400, 4000},\n//{10558, 440, 400, 4000},\n//{9920, 480, 400, 4000},\n//{9061, 520, 400, 4000},\n//{8260, 560, 400, 4000},\n//{7551, 600, 400, 4000},\n//{6847, 640, 400, 4000},\n//{5988, 680, 400, 4000},\n//{4992, 720, 400, 4000},\n//{4048, 760, 400, 4000},\n//{3188, 800, 400, 4000},\n//{2406, 840, 400, 4000},\n//{1684, 880, 400, 4000},\n//{1027, 920, 400, 4000},\n//{480, 960, 400, 4000},\n//{12200, 0, 440, 4000},\n//{11984, 40, 440, 4000},\n//{11737, 80, 440, 4000},\n//{11483, 120, 440, 4000},\n//{11229, 160, 440, 4000},\n//{10949, 200, 440, 4000},\n//{10631, 240, 440, 4000},\n//{10365, 280, 440, 4000},\n//{10156, 320, 440, 4000},\n//{9946, 360, 440, 4000},\n//{9646, 400, 440, 4000},\n//{9224, 440, 440, 4000},\n//{8657, 480, 440, 4000},\n//{7941, 520, 440, 4000},\n//{7270, 560, 440, 4000},\n//{6593, 600, 440, 4000},\n//{5878, 640, 440, 4000},\n//{5039, 680, 440, 4000},\n//{4200, 720, 440, 4000},\n//{3424, 760, 440, 4000},\n//{2700, 800, 440, 4000},\n//{2017, 840, 440, 4000},\n//{1385, 880, 440, 4000},\n//{838, 920, 440, 4000},\n//{382, 960, 440, 4000},\n//{10206, 0, 500, 4000},\n//{10018, 40, 500, 4000},\n//{9829, 80, 500, 4000},\n//{9608, 120, 500, 4000},\n//{9386, 160, 500, 4000},\n//{9152, 200, 500, 4000},\n//{8931, 240, 500, 4000},\n//{8697, 280, 500, 4000},\n//{8476, 320, 500, 4000},\n//{8261, 360, 500, 4000},\n//{8027, 400, 500, 4000},\n//{7669, 440, 500, 4000},\n//{7200, 480, 500, 4000},\n//{6608, 520, 500, 4000},\n//{5989, 560, 500, 4000},\n//{5357, 600, 500, 4000},\n//{4699, 640, 500, 4000},\n//{4042, 680, 500, 4000},\n//{3398, 720, 500, 4000},\n//{2778, 760, 500, 4000},\n//{2160, 800, 500, 4000},\n//{1554, 840, 500, 4000},\n//{1036, 880, 500, 4000},\n//{538, 920, 500, 4000},\n// {200, 960, 500, 4000}};\n\n /* THIS IS FOR N = 500 */\n int hc_settings[N_SETTINGS][4] = {\n {19432, 0, 100, 4000},\n{17976, 20, 100, 4000},\n{17413, 40, 100, 4000},\n{17524, 60, 100, 4000},\n{17159, 80, 100, 4000},\n{16432, 100, 100, 4000},\n{15611, 120, 100, 4000},\n{14817, 140, 100, 4000},\n{13937, 160, 100, 4000},\n{13338, 180, 100, 4000},\n{12623, 200, 100, 4000},\n{12284, 220, 100, 4000},\n{11594, 240, 100, 4000},\n{11080, 260, 100, 4000},\n{10267, 280, 100, 4000},\n{9648, 300, 100, 4000},\n{8933, 320, 100, 4000},\n{8340, 340, 100, 4000},\n{7630, 360, 100, 4000},\n{6983, 380, 100, 4000},\n{6346, 400, 100, 4000},\n{5709, 420, 100, 4000},\n{4680, 440, 100, 4000},\n{3456, 460, 100, 4000},\n{1792, 480, 100, 4000},\n{18429, 0, 105, 4000},\n{17238, 20, 105, 4000},\n{16495, 40, 105, 4000},\n{15845, 60, 105, 4000},\n{15584, 80, 105, 4000},\n{15136, 100, 105, 4000},\n{14420, 120, 105, 4000},\n{13951, 140, 105, 4000},\n{13261, 160, 105, 4000},\n{12909, 180, 105, 4000},\n{12408, 200, 105, 4000},\n{11978, 220, 105, 4000},\n{11398, 240, 105, 4000},\n{10838, 260, 105, 4000},\n{9959, 280, 105, 4000},\n{9374, 300, 105, 4000},\n{8715, 320, 105, 4000},\n{8337, 340, 105, 4000},\n{7706, 360, 105, 4000},\n{7121, 380, 105, 4000},\n{6425, 400, 105, 4000},\n{5650, 420, 105, 4000},\n{4310, 440, 105, 4000},\n{3021, 460, 105, 4000},\n{1423, 480, 105, 4000},\n{17632, 0, 110, 4000},\n{16920, 20, 110, 4000},\n{16340, 40, 110, 4000},\n{15910, 60, 110, 4000},\n{15402, 80, 110, 4000},\n{14849, 100, 110, 4000},\n{14244, 120, 110, 4000},\n{13651, 140, 110, 4000},\n{13058, 160, 110, 4000},\n{12486, 180, 110, 4000},\n{11900, 200, 110, 4000},\n{11366, 220, 110, 4000},\n{10819, 240, 110, 4000},\n{10260, 260, 110, 4000},\n{9596, 280, 110, 4000},\n{9017, 300, 110, 4000},\n{8371, 320, 110, 4000},\n{7967, 340, 110, 4000},\n{7381, 360, 110, 4000},\n{6867, 380, 110, 4000},\n{6177, 400, 110, 4000},\n{5520, 420, 110, 4000},\n{4648, 440, 110, 4000},\n{3398, 460, 110, 4000},\n{1789, 480, 110, 4000},\n{16904, 0, 115, 4000},\n{16411, 20, 115, 4000},\n{15943, 40, 115, 4000},\n{15500, 60, 115, 4000},\n{15057, 80, 115, 4000},\n{14601, 100, 115, 4000},\n{14010, 120, 115, 4000},\n{13366, 140, 115, 4000},\n{12650, 160, 115, 4000},\n{12082, 180, 115, 4000},\n{11554, 200, 115, 4000},\n{11138, 220, 115, 4000},\n{10695, 240, 115, 4000},\n{10200, 260, 115, 4000},\n{9588, 280, 115, 4000},\n{8970, 300, 115, 4000},\n{8449, 320, 115, 4000},\n{7889, 340, 115, 4000},\n{7336, 360, 115, 4000},\n{6686, 380, 115, 4000},\n{6133, 400, 115, 4000},\n{5494, 420, 115, 4000},\n{4497, 440, 115, 4000},\n{3266, 460, 115, 4000},\n{1665, 480, 115, 4000},\n{16498, 0, 120, 4000},\n{16055, 20, 120, 4000},\n{15631, 40, 120, 4000},\n{15194, 60, 120, 4000},\n{14751, 80, 120, 4000},\n{14295, 100, 120, 4000},\n{13624, 120, 120, 4000},\n{12993, 140, 120, 4000},\n{12343, 160, 120, 4000},\n{11848, 180, 120, 4000},\n{11333, 200, 120, 4000},\n{10760, 220, 120, 4000},\n{10213, 240, 120, 4000},\n{9692, 260, 120, 4000},\n{9204, 280, 120, 4000},\n{8723, 300, 120, 4000},\n{8189, 320, 120, 4000},\n{7648, 340, 120, 4000},\n{7049, 360, 120, 4000},\n{6516, 380, 120, 4000},\n{5917, 400, 120, 4000},\n{5214, 420, 120, 4000},\n{4328, 440, 120, 4000},\n{3116, 460, 120, 4000},\n{1658, 480, 120, 4000},\n{14992, 0, 130, 4000},\n{14608, 20, 130, 4000},\n{14224, 40, 130, 4000},\n{13891, 60, 130, 4000},\n{13488, 80, 130, 4000},\n{13065, 100, 130, 4000},\n{12538, 120, 130, 4000},\n{11940, 140, 130, 4000},\n{11386, 160, 130, 4000},\n{10872, 180, 130, 4000},\n{10390, 200, 130, 4000},\n{9856, 220, 130, 4000},\n{9420, 240, 130, 4000},\n{8873, 260, 130, 4000},\n{8358, 280, 130, 4000},\n{7739, 300, 130, 4000},\n{7264, 320, 130, 4000},\n{6789, 340, 130, 4000},\n{6366, 360, 130, 4000},\n{5903, 380, 130, 4000},\n{5448, 400, 130, 4000},\n{4797, 420, 130, 4000},\n{3938, 440, 130, 4000},\n{2830, 460, 130, 4000},\n{1496, 480, 130, 4000},\n{14152, 0, 140, 4000},\n{13710, 20, 140, 4000},\n{13286, 40, 140, 4000},\n{12941, 60, 140, 4000},\n{12505, 80, 140, 4000},\n{12075, 100, 140, 4000},\n{11554, 120, 140, 4000},\n{11098, 140, 140, 4000},\n{10604, 160, 140, 4000},\n{10200, 180, 140, 4000},\n{9692, 200, 140, 4000},\n{9210, 220, 140, 4000},\n{8748, 240, 140, 4000},\n{8305, 260, 140, 4000},\n{7850, 280, 140, 4000},\n{7264, 300, 140, 4000},\n{6750, 320, 140, 4000},\n{6307, 340, 140, 4000},\n{5884, 360, 140, 4000},\n{5447, 380, 140, 4000},\n{4952, 400, 140, 4000},\n{4458, 420, 140, 4000},\n{3729, 440, 140, 4000},\n{2668, 460, 140, 4000},\n{1366, 480, 140, 4000},\n{13138, 0, 150, 4000},\n{12792, 20, 150, 4000},\n{12551, 40, 150, 4000},\n{12212, 60, 150, 4000},\n{11828, 80, 150, 4000},\n{11469, 100, 150, 4000},\n{11073, 120, 150, 4000},\n{10643, 140, 150, 4000},\n{10025, 160, 150, 4000},\n{9536, 180, 150, 4000},\n{9159, 200, 150, 4000},\n{8767, 220, 150, 4000},\n{8338, 240, 150, 4000},\n{7843, 260, 150, 4000},\n{7453, 280, 150, 4000},\n{7062, 300, 150, 4000},\n{6593, 320, 150, 4000},\n{6072, 340, 150, 4000},\n{5682, 360, 150, 4000},\n{5226, 380, 150, 4000},\n{4849, 400, 150, 4000},\n{4354, 420, 150, 4000},\n{3742, 440, 150, 4000},\n{2759, 460, 150, 4000},\n{1447, 480, 150, 4000},\n{11320, 0, 160, 4000},\n{11060, 20, 160, 4000},\n{10787, 40, 160, 4000},\n{10513, 60, 160, 4000},\n{10083, 80, 160, 4000},\n{9712, 100, 160, 4000},\n{9485, 120, 160, 4000},\n{9276, 140, 160, 4000},\n{9037, 160, 160, 4000},\n{8743, 180, 160, 4000},\n{8437, 200, 160, 4000},\n{8110, 220, 160, 4000},\n{7680, 240, 160, 4000},\n{7257, 260, 160, 4000},\n{6867, 280, 160, 4000},\n{6483, 300, 160, 4000},\n{6053, 320, 160, 4000},\n{5643, 340, 160, 4000},\n{5220, 360, 160, 4000},\n{4803, 380, 160, 4000},\n{4379, 400, 160, 4000},\n{3892, 420, 160, 4000},\n{3241, 440, 160, 4000},\n{2303, 460, 160, 4000},\n{1189, 480, 160, 4000},\n{11125, 0, 180, 4000},\n{10799, 20, 180, 4000},\n{10526, 40, 180, 4000},\n{10213, 60, 180, 4000},\n{9920, 80, 180, 4000},\n{9484, 100, 180, 4000},\n{9016, 120, 180, 4000},\n{8553, 140, 180, 4000},\n{8156, 160, 180, 4000},\n{7843, 180, 180, 4000},\n{7576, 200, 180, 4000},\n{7297, 220, 180, 4000},\n{6985, 240, 180, 4000},\n{6659, 260, 180, 4000},\n{6346, 280, 180, 4000},\n{5994, 300, 180, 4000},\n{5604, 320, 180, 4000},\n{5161, 340, 180, 4000},\n{4751, 360, 180, 4000},\n{4335, 380, 180, 4000},\n{3963, 400, 180, 4000},\n{3410, 420, 180, 4000},\n{2720, 440, 180, 4000},\n{1802, 460, 180, 4000},\n{891, 480, 180, 4000},\n{9699, 0, 200, 4000},\n{9426, 20, 200, 4000},\n{9159, 40, 200, 4000},\n{8892, 60, 200, 4000},\n{8612, 80, 200, 4000},\n{8293, 100, 200, 4000},\n{7955, 120, 200, 4000},\n{7590, 140, 200, 4000},\n{7284, 160, 200, 4000},\n{6938, 180, 200, 4000},\n{6600, 200, 200, 4000},\n{6229, 220, 200, 4000},\n{5891, 240, 200, 4000},\n{5578, 260, 200, 4000},\n{5252, 280, 200, 4000},\n{4947, 300, 200, 4000},\n{4576, 320, 200, 4000},\n{4244, 340, 200, 4000},\n{3879, 360, 200, 4000},\n{3599, 380, 200, 4000},\n{3286, 400, 200, 4000},\n{2928, 420, 200, 4000},\n{2368, 440, 200, 4000},\n{1633, 460, 200, 4000},\n{813, 480, 200, 4000},\n{8859, 0, 220, 4000},\n{8637, 20, 220, 4000},\n{8397, 40, 220, 4000},\n{8130, 60, 220, 4000},\n{7844, 80, 220, 4000},\n{7563, 100, 220, 4000},\n{7277, 120, 220, 4000},\n{6932, 140, 220, 4000},\n{6601, 160, 220, 4000},\n{6255, 180, 220, 4000},\n{5969, 200, 220, 4000},\n{5682, 220, 220, 4000},\n{5383, 240, 220, 4000},\n{5057, 260, 220, 4000},\n{4732, 280, 220, 4000},\n{4439, 300, 220, 4000},\n{4166, 320, 220, 4000},\n{3840, 340, 220, 4000},\n{3534, 360, 220, 4000},\n{3214, 380, 220, 4000},\n{2889, 400, 220, 4000},\n{2512, 420, 220, 4000},\n{2030, 440, 220, 4000},\n{1444, 460, 220, 4000},\n{741, 480, 220, 4000},\n{7980, 0, 240, 4000},\n{7766, 20, 240, 4000},\n{7538, 40, 240, 4000},\n{7323, 60, 240, 4000},\n{7115, 80, 240, 4000},\n{6848, 100, 240, 4000},\n{6561, 120, 240, 4000},\n{6196, 140, 240, 4000},\n{5897, 160, 240, 4000},\n{5604, 180, 240, 4000},\n{5331, 200, 240, 4000},\n{5064, 220, 240, 4000},\n{4784, 240, 240, 4000},\n{4491, 260, 240, 4000},\n{4237, 280, 240, 4000},\n{3969, 300, 240, 4000},\n{3729, 320, 240, 4000},\n{3436, 340, 240, 4000},\n{3143, 360, 240, 4000},\n{2850, 380, 240, 4000},\n{2563, 400, 240, 4000},\n{2277, 420, 240, 4000},\n{1854, 440, 240, 4000},\n{1294, 460, 240, 4000},\n{636, 480, 240, 4000},\n{7414, 0, 260, 4000},\n{7180, 20, 260, 4000},\n{6939, 40, 260, 4000},\n{6712, 60, 260, 4000},\n{6471, 80, 260, 4000},\n{6262, 100, 260, 4000},\n{6008, 120, 260, 4000},\n{5734, 140, 260, 4000},\n{5402, 160, 260, 4000},\n{5142, 180, 260, 4000},\n{4920, 200, 260, 4000},\n{4712, 220, 260, 4000},\n{4458, 240, 260, 4000},\n{4178, 260, 260, 4000},\n{3943, 280, 260, 4000},\n{3696, 300, 260, 4000},\n{3449, 320, 260, 4000},\n{3189, 340, 260, 4000},\n{2949, 360, 260, 4000},\n{2701, 380, 260, 4000},\n{2434, 400, 260, 4000},\n{2121, 420, 260, 4000},\n{1698, 440, 260, 4000},\n{1157, 460, 260, 4000},\n{565, 480, 260, 4000},\n{6652, 0, 280, 4000},\n{6503, 20, 280, 4000},\n{6301, 40, 280, 4000},\n{6093, 60, 280, 4000},\n{5884, 80, 280, 4000},\n{5689, 100, 280, 4000},\n{5441, 120, 280, 4000},\n{5193, 140, 280, 4000},\n{4934, 160, 280, 4000},\n{4693, 180, 280, 4000},\n{4452, 200, 280, 4000},\n{4217, 220, 280, 4000},\n{3996, 240, 280, 4000},\n{3775, 260, 280, 4000},\n{3567, 280, 280, 4000},\n{3326, 300, 280, 4000},\n{3098, 320, 280, 4000},\n{2850, 340, 280, 4000},\n{2616, 360, 280, 4000},\n{2382, 380, 280, 4000},\n{2134, 400, 280, 4000},\n{1880, 420, 280, 4000},\n{1502, 440, 280, 4000},\n{1033, 460, 280, 4000},\n{499, 480, 280, 4000},\n{5226, 0, 320, 4000},\n{5142, 20, 320, 4000},\n{5038, 40, 320, 4000},\n{4933, 60, 320, 4000},\n{4797, 80, 320, 4000},\n{4654, 100, 320, 4000},\n{4498, 120, 320, 4000},\n{4335, 140, 320, 4000},\n{4172, 160, 320, 4000},\n{4002, 180, 320, 4000},\n{3821, 200, 320, 4000},\n{3580, 220, 320, 4000},\n{3365, 240, 320, 4000},\n{3157, 260, 320, 4000},\n{2987, 280, 320, 4000},\n{2785, 300, 320, 4000},\n{2596, 320, 320, 4000},\n{2414, 340, 320, 4000},\n{2212, 360, 320, 4000},\n{1978, 380, 320, 4000},\n{1757, 400, 320, 4000},\n{1528, 420, 320, 4000},\n{1242, 440, 320, 4000},\n{812, 460, 320, 4000},\n{376, 480, 320, 4000},\n{4874, 0, 360, 4000},\n{4718, 20, 360, 4000},\n{4556, 40, 360, 4000},\n{4380, 60, 360, 4000},\n{4211, 80, 360, 4000},\n{4062, 100, 360, 4000},\n{3906, 120, 360, 4000},\n{3723, 140, 360, 4000},\n{3527, 160, 360, 4000},\n{3358, 180, 360, 4000},\n{3202, 200, 360, 4000},\n{3032, 220, 360, 4000},\n{2863, 240, 360, 4000},\n{2720, 260, 360, 4000},\n{2571, 280, 360, 4000},\n{2388, 300, 360, 4000},\n{2193, 320, 360, 4000},\n{2004, 340, 360, 4000},\n{1847, 360, 360, 4000},\n{1678, 380, 360, 4000},\n{1509, 400, 360, 4000},\n{1294, 420, 360, 4000},\n{1047, 440, 360, 4000},\n{688, 460, 360, 4000},\n{337, 480, 360, 4000},\n{4153, 0, 400, 4000},\n{4042, 20, 400, 4000},\n{3911, 40, 400, 4000},\n{3787, 60, 400, 4000},\n{3657, 80, 400, 4000},\n{3533, 100, 400, 4000},\n{3364, 120, 400, 4000},\n{3189, 140, 400, 4000},\n{3006, 160, 400, 4000},\n{2889, 180, 400, 4000},\n{2752, 200, 400, 4000},\n{2635, 220, 400, 4000},\n{2465, 240, 400, 4000},\n{2316, 260, 400, 4000},\n{2166, 280, 400, 4000},\n{2024, 300, 400, 4000},\n{1874, 320, 400, 4000},\n{1711, 340, 400, 4000},\n{1561, 360, 400, 4000},\n{1418, 380, 400, 4000},\n{1262, 400, 400, 4000},\n{1093, 420, 400, 4000},\n{892, 440, 400, 4000},\n{598, 460, 400, 4000},\n{292, 480, 400, 4000},\n{3664, 0, 440, 4000},\n{3541, 20, 440, 4000},\n{3437, 40, 440, 4000},\n{3332, 60, 440, 4000},\n{3221, 80, 440, 4000},\n{3091, 100, 440, 4000},\n{2948, 120, 440, 4000},\n{2805, 140, 440, 4000},\n{2674, 160, 440, 4000},\n{2544, 180, 440, 4000},\n{2420, 200, 440, 4000},\n{2303, 220, 440, 4000},\n{2192, 240, 440, 4000},\n{2062, 260, 440, 4000},\n{1919, 280, 440, 4000},\n{1782, 300, 440, 4000},\n{1652, 320, 440, 4000},\n{1522, 340, 440, 4000},\n{1398, 360, 440, 4000},\n{1255, 380, 440, 4000},\n{1105, 400, 440, 4000},\n{923, 420, 440, 4000},\n{766, 440, 440, 4000},\n{512, 460, 440, 4000},\n{265, 480, 440, 4000},\n{3077, 0, 500, 4000},\n{2974, 20, 500, 4000},\n{2948, 40, 500, 4000},\n{2877, 60, 500, 4000},\n{2799, 80, 500, 4000},\n{2629, 100, 500, 4000},\n{2498, 120, 500, 4000},\n{2446, 140, 500, 4000},\n{2388, 160, 500, 4000},\n{2349, 180, 500, 4000},\n{2161, 200, 500, 4000},\n{1991, 220, 500, 4000},\n{1815, 240, 500, 4000},\n{1704, 260, 500, 4000},\n{1593, 280, 500, 4000},\n{1470, 300, 500, 4000},\n{1354, 320, 500, 4000},\n{1236, 340, 500, 4000},\n{1125, 360, 500, 4000},\n{1001, 380, 500, 4000},\n{871, 400, 500, 4000},\n{741, 420, 500, 4000},\n{611, 440, 500, 4000},\n{379, 460, 500, 4000},\n {171, 480, 500, 4000}};\n \n for(int i = 0; i < N_SETTINGS; i++)\n for(int j = 0; j < 4; j++)\n settings[i][j] = hc_settings[i][j];\n \n}\n\n", "meta": {"hexsha": "e2d0a1ea9aed0400ad74366fd009f0e1082d88f9", "size": 47138, "ext": "c", "lang": "C", "max_stars_repo_path": "ODE_MODEL/main.c", "max_stars_repo_name": "heinekmp/MLBPF", "max_stars_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ODE_MODEL/main.c", "max_issues_repo_name": "heinekmp/MLBPF", "max_issues_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ODE_MODEL/main.c", "max_forks_repo_name": "heinekmp/MLBPF", "max_forks_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9288888889, "max_line_length": 359, "alphanum_fraction": 0.5881454453, "num_tokens": 21395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.44731831430518426}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"core_allvars.h\"\n#include \"core_proto.h\"\n\n\n\nvoid init(void)\n{\n int i;\n\n Age = mymalloc(ABSOLUTEMAXSNAPS*sizeof(*Age));\n \n random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);\n gsl_rng_set(random_generator, 42);\t // start-up seed \n\n set_units();\n srand((unsigned) time(NULL));\n\n read_snap_list();\n\n //Hack to fix deltaT for snapshot 0\n //This way, galsnapnum = -1 will not segfault.\n Age[0] = time_to_present(1000.0);//lookback time from z=1000\n Age++;\n \n for(i = 0; i < Snaplistlen; i++)\n {\n ZZ[i] = 1 / AA[i] - 1;\n Age[i] = time_to_present(ZZ[i]);\n }\n\n a0 = 1.0 / (1.0 + Reionization_z0);\n ar = 1.0 / (1.0 + Reionization_zr);\n\n read_cooling_functions();\n\n}\n\n\n\nvoid set_units(void)\n{\n\n UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;\n UnitTime_in_Megayears = UnitTime_in_s / SEC_PER_MEGAYEAR;\n G = GRAVITY / pow(UnitLength_in_cm, 3) * UnitMass_in_g * pow(UnitTime_in_s, 2);\n UnitDensity_in_cgs = UnitMass_in_g / pow(UnitLength_in_cm, 3);\n UnitPressure_in_cgs = UnitMass_in_g / UnitLength_in_cm / pow(UnitTime_in_s, 2);\n UnitCoolingRate_in_cgs = UnitPressure_in_cgs / UnitTime_in_s;\n UnitEnergy_in_cgs = UnitMass_in_g * pow(UnitLength_in_cm, 2) / pow(UnitTime_in_s, 2);\n\n EnergySNcode = EnergySN / UnitEnergy_in_cgs * Hubble_h;\n EtaSNcode = EtaSN * (UnitMass_in_g / SOLAR_MASS) / Hubble_h;\n\n // convert some physical input parameters to internal units \n Hubble = HUBBLE * UnitTime_in_s;\n\n // compute a few quantitites \n RhoCrit = 3 * Hubble * Hubble / (8 * M_PI * G);\n\n}\n\n\n\nvoid read_snap_list(void)\n{\n FILE *fd;\n char fname[1000];\n\n sprintf(fname, \"%s\", FileWithSnapList);\n\n if(!(fd = fopen(fname, \"r\")))\n {\n printf(\"can't read output list in file '%s'\\n\", fname);\n ABORT(0);\n }\n\n Snaplistlen = 0;\n do\n {\n if(fscanf(fd, \" %lg \", &AA[Snaplistlen]) == 1)\n Snaplistlen++;\n else\n break;\n }\n while(Snaplistlen < MAXSNAPS);\n\n fclose(fd);\n\n#ifdef MPI\n if(ThisTask == 0)\n#endif\n printf(\"found %d defined times in snaplist\\n\", Snaplistlen);\n}\n\n\n\ndouble time_to_present(double z)\n{\n#define WORKSIZE 1000\n gsl_function F;\n gsl_integration_workspace *workspace;\n double time, result, abserr;\n\n workspace = gsl_integration_workspace_alloc(WORKSIZE);\n F.function = &integrand_time_to_present;\n\n gsl_integration_qag(&F, 1.0 / (z + 1), 1.0, 1.0 / Hubble,\n 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS21, workspace, &result, &abserr);\n\n time = 1 / Hubble * result;\n\n gsl_integration_workspace_free(workspace);\n\n // return time to present as a function of redshift \n return time;\n}\n\n\n\ndouble integrand_time_to_present(double a, void *param)\n{\n return 1 / sqrt(Omega / a + (1 - Omega - OmegaLambda) + OmegaLambda * a * a);\n}\n\n\n\n", "meta": {"hexsha": "7c9c2f11017dfd111a2d3ba28323a6da4cce9393", "size": 2956, "ext": "c", "lang": "C", "max_stars_repo_path": "code/core_init.c", "max_stars_repo_name": "jacobseiler/SAGE", "max_stars_repo_head_hexsha": "6c6ff3b0a50108523a7666041bd1e8815126e7de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-05-22T01:22:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T12:25:06.000Z", "max_issues_repo_path": "code/core_init.c", "max_issues_repo_name": "jacobseiler/SAGE", "max_issues_repo_head_hexsha": "6c6ff3b0a50108523a7666041bd1e8815126e7de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-04-01T14:25:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T09:18:16.000Z", "max_forks_repo_path": "code/core_init.c", "max_forks_repo_name": "jacobseiler/SAGE", "max_forks_repo_head_hexsha": "6c6ff3b0a50108523a7666041bd1e8815126e7de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T06:12:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T05:50:47.000Z", "avg_line_length": 21.2661870504, "max_line_length": 87, "alphanum_fraction": 0.6806495264, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4470479536078197}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n\n#include \"../../theory/basics.c\"\n#include \"../../emu13/emu.c\"\n#include \"../../theory/parameters.c\"\n#include \"../../theory/cosmo3D.c\"\n#include \"../../theory/redshift.c\"\n\ntypedef struct {\n const gsl_interp2d_type *T = gsl_interp2d_bilinear;\n gsl_spline2d *spline;\n gsl_interp_accel *xacc;\n gsl_interp_accel *yacc;\n double *grid_values;\n} spline_interpolator;\nspline_interpolator global_baryon_spline;\n\n\nvoid init_baryon_spline_interpolation_to_TNG100(){\n \n const size_t N = 100; /* number of points to interpolate */\n const double lnk_values[] = { 0.0, 1.0 };\n const double z_values[] = { 3.71, 3.49, 3.28, 2.90, 2.44, 2.10, 1.74, 1.41, 1.04, 0.7, 0.35, 0.18, 0.0 }; /* define unit square */\n const size_t nk = sizeof(lnk_values) / sizeof(double); /* y grid points */\n const size_t nz = sizeof(z_values) / sizeof(double); /* x grid points */\n global_baryon_spline.grid_values = malloc(nk * nz * sizeof(double));\n global_baryon_spline.spline = gsl_spline2d_alloc(global_baryon_spline.T, nk, nz);\n global_baryon_spline.xacc = gsl_interp_accel_alloc();\n global_baryon_spline.yacc = gsl_interp_accel_alloc();\n size_t i, j;\n \n for(int i = 0; i < nk; i++){\n for(int j = 0; j < nz; j++){\n gsl_spline2d_set(spline, global_baryon_spline.grid_values, i, j, TNG100[i][j]);\n }\n }\n\n /* initialize interpolation */\n gsl_spline2d_init(global_baryon_spline.spline, lnk_values, z_values, Pk_ratio, nk, nz);\n \n\n}\n\n\nvoid free_baryon_spline_interpolation_to_TNG100(){\n gsl_spline2d_free(global_baryon_spline.spline);\n gsl_interp_accel_free(global_baryon_spline.xacc);\n gsl_interp_accel_free(global_baryon_spline.yacc);\n free(global_baryon_spline.grid_values);\n}\n\n\ndouble fraction_Pdelta_baryon_from_sims_DES(double k,double z)\n{\n return gsl_spline2d_eval(global_baryon_spline.spline, k, z, global_baryon_spline.xacc, global_baryon_spline.yacc);\n}\n\n\ndouble fraction_Pdelta_baryon_from_spline_DES(double k,double z)\n{\n int i;\n double val;\n static int READ_TABLE=0;\n static double **table;\n FILE *F;\n int baryon_zbin=13;\n int baryon_kbin=325;\n double logk_min = -3.3010299956639813;\n double logk_max = 3.1760912590556813;\n double dz=(redshift.shear_zdistrpar_zmax)/(10.0);\n static double dlogk=(logk_max-logk_min)/(double(baryon_kbin-1));\n val = interpol2d(AGN_DESdepth, baryon_kbin, logk_min, logk_max, dk, log(k), baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0);\n return val; \n}\n\n// if (READ_TABLE==0){\n// if (strcmp(pdeltaparams.baryons,\"AGN_DESdepth\")==0) P_type = 0;\n// if (strcmp(pdeltaparams.baryons,\"NOSN_DESdepth\")==0) P_type = 1;\n// if (strcmp(pdeltaparams.baryons,\"NOSN_NOZCOOL_DESdepth\")==0) P_type = 2;\n// if (strcmp(pdeltaparams.baryons,\"NOZCOOL_DESdepth\")==0) P_type = 3;\n// if (strcmp(pdeltaparams.baryons,\"REF_DESdepth\")==0) P_type = 4;\n// if (strcmp(pdeltaparams.baryons,\"WDENS_DESdepth\") ==0) P_type = 5;\n// if (strcmp(pdeltaparams.baryons,\"DBLIMFV1618_DESdepth\") ==0) P_type = 6;\n// if (strcmp(pdeltaparams.baryons,\"WML4_DESdepth\")==0) P_type = 7;\n// if (strcmp(pdeltaparams.baryons,\"WML1V848_DESdepth\")==0) P_type = 8;\n// if (strcmp(pdeltaparams.baryons,\"AD_DESdepth\")==0) P_type = 9;\n// if (strcmp(pdeltaparams.baryons,\"CX_DESdepth\")==0) P_type = 10;\n// if (strcmp(pdeltaparams.baryons,\"CW_DESdepth\")==0) P_type = 11;\n// if (strcmp(pdeltaparams.baryons,\"A_DESdepth\")==0) P_type = 12;\n// if (strcmp(pdeltaparams.baryons,\"CSF_DESdepth\")==0) P_type = 13;\n// }\n// switch (P_type){\n// case 0: val = interpol2d(AGN_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 1: val = interpol2d(NOSN_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 2: val = interpol2d(NOSN_NOZCOOL_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 3: val = interpol2d(NOZCOOL_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 4: val = interpol2d(REF_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 5: val = interpol2d(WDENS_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 6: val = interpol2d(DBLIMFV1618_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 7: val = interpol2d(WML4_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 8: val = interpol2d(WML1V848_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 9: val = interpol2d(AD_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 10: val = interpol2d(CX_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 11: val = interpol2d(CW_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 12: val = interpol2d(A_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n// case 13: val = interpol2d(CSF_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;\n\n// default: \n// printf(\"baryons.c: %s baryonic scenario not defined\\n\",pdeltaparams.baryons);\n\n// break;\n// }\n// kintern=k/cosmology.coverH0;\n \n// return val; \n// }\n\n\n\n\n\n\n\n// if (strcmp(pdeltaparams.baryons,\"AGN_LSSTdepth\")==0) P_type = 14;\n// if (strcmp(pdeltaparams.baryons,\"NOSN_LSSTdepth\")==0) P_type = 15;\n// if (strcmp(pdeltaparams.baryons,\"NOSN_NOZCOOL_LSSTdepth\")==0) P_type = 16;\n// if (strcmp(pdeltaparams.baryons,\"NOZCOOL_LSSTdepth\")==0) P_type = 17;\n// if (strcmp(pdeltaparams.baryons,\"REF_LSSTdepth\")==0) P_type = 18;\n// if (strcmp(pdeltaparams.baryons,\"WDENS_LSSTdepth\") ==0) P_type = 19;\n// if (strcmp(pdeltaparams.baryons,\"DBLIMFV1618_LSSTdepth\") ==0) P_type = 20;\n// if (strcmp(pdeltaparams.baryons,\"WML4_LSSTdepth\")==0) P_type = 21;\n// if (strcmp(pdeltaparams.baryons,\"WML1V848_LSSTdepth\")==0) P_type = 22;\n// if (strcmp(pdeltaparams.baryons,\"AD_LSSTdepth\")==0) P_type = 23;\n// if (strcmp(pdeltaparams.baryons,\"CX_LSSTdepth\")==0) P_type = 24;\n// if (strcmp(pdeltaparams.baryons,\"CW_LSSTdepth\")==0) P_type = 25;\n// if (table!=0) free_double_matrix(table, 0, OWLS_kbin-1, 0, OWLS_zbin-1);\n// table = create_double_matrix(0, OWLS_kbin-1, 0, OWLS_zbin-1);\n// printf(\"%s\\n\",file.DATA_FILE); \n// F=fopen(file.DATA_FILE,\"r\");\n// for(i=0;i\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\n#define SQR(x) ((x) * (x))\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\nextern double VOCCC(gsl_matrix *,int,int);\nextern double VICC(gsl_matrix *,int);\nextern double VKendall_W(gsl_matrix *,int,int);\nextern double SpearmanCorr(const float *data1,const float *data2, int n);\n\nint metric = 1;\nint verbose = 0;\n\nVDictEntry TypeDict[] = {\n { \"kendall\", 0 },\n { \"occc\", 1 },\n { NULL }\n};\n\n\n\ndouble Correlation(const float *arr1,const float *arr2,int n)\n{\n int i;\n double sx,sy,sxx,syy,sxy,rx;\n double tiny=1.0e-4;\n\n sxx = syy = sxy = sx = sy = 0;\n for (i=0; i tiny)\n rx = (nx*sxy - sx*sy)/sqrt(u*v);\n return rx;\n}\n\n\nVImage VCCM(VImage **src, VImage mask, int nsubjects, int nslices,int first,int length,int type,int otype)\n{\n VImage map=NULL,dest=NULL;\n int i,j,k,s,nvoxels,nt,len,last,b,r,c,bb,rr,cc,rad2,nrows,ncols;\n double u=0,v=0;\n gsl_matrix *data=NULL;\n gsl_matrix_float **mat=NULL;\n\n\n nrows = VImageNRows(mask);\n ncols = VImageNColumns(mask);\n\n\n /* count number of voxels, number of timesteps */\n nvoxels = nt = 0;\n for (b=0; b nt)\n\t nt = VImageNBands(src[0][b]);\n\tnvoxels++;\n }\n }\n }\n \n /* get shortest length of time series across subjects */\n nt = 99999;\n for (s=0; s= nt) last = nt-1;\n if (first < 0) first = 1;\n\n nt = last - first + 1;\n if (nt < 2) VError(\" not enough timesteps, nt= %d\",nt);\n \n fprintf(stderr,\" first= %d, last= %d, ntimesteps= %d\\n\",\n (int)first,(int)last,(int)nt);\n fprintf(stderr,\" nsubjects= %d, nvoxels= %d\\n\",nsubjects,nvoxels);\n fprintf(stderr,\" type= %s\\n\",TypeDict[type].keyword);\n \n\n\n /*\n ** store voxel addresses\n */\n map = VCreateImage(1,3,nvoxels,VIntegerRepn);\n if (map == NULL) VError(\" error allocating addr map\");\n VFillImage(map,VAllBands,0);\n\n i = 0;\n for (b=0; b= nvoxels) VError(\" nvox= %d\",i);\n\tVPixel(map,0,0,i,VInteger) = b;\n\tVPixel(map,0,1,i,VInteger) = r;\n\tVPixel(map,0,2,i,VInteger) = c;\n\ti++;\n }\n }\n }\n\n\n /*\n ** avoid casting to float, copy data to matrix\n */ \n mat = (gsl_matrix_float **) VCalloc(nsubjects,sizeof(gsl_matrix_float *));\n if (!mat) VError(\" err allocating mat\");\n\n for (s=0; s= data->size2) VError(\" len= %d %d\",len,data->size2);\n\n if (type == 0)\n v = VKendall_W(data,len,otype);\n else if (type == 1)\n v = VOCCC(data,len,verbose);\n else\n VError(\" illegal type\");\n\n b = VPixel(map,0,0,i,VInteger);\n r = VPixel(map,0,1,i,VInteger);\n c = VPixel(map,0,2,i,VInteger);\n VPixel(dest,b,r,c,VFloat) = v;\n }\n fprintf(stderr,\"\\n\");\n return dest;\n}\n\n\nint main (int argc, char *argv[])\n{\n static VArgVector in_files;\n static VString out_filename;\n static VString mask_filename;\n static VShort type = 0; \n static VShort otype = 0; \n static VShort first = 2;\n static VShort length = 0;\n static VOptionDescRec options[] = {\n {\"in\", VStringRepn, 0, & in_files, VRequiredOpt, NULL,\"Input files\" },\n {\"out\", VStringRepn, 1, & out_filename, VRequiredOpt, NULL,\"Output file\" },\n {\"mask\",VStringRepn,1,(VPointer) &mask_filename,VRequiredOpt,NULL,\"Mask file\"}, \n {\"first\",VShortRepn,1,(VPointer) &first,VOptionalOpt,NULL,\"First timestep to use\"},\n {\"length\",VShortRepn,1,(VPointer) &length,VOptionalOpt,NULL,\n \"Length of time series to use, '0' to use full length\"},\n {\"type\",VShortRepn,1,(VPointer) &type,VOptionalOpt,TypeDict,\"Type of metric\"},\n {\"gauss\",VShortRepn,1,(VPointer) &otype,VOptionalOpt,NULL,\"Use gaussian version of kendall\"},\n };\n VString in_filename;\n VAttrList list=NULL,geolist=NULL;\n int b,r,c,i=0;\n float u;\n char *prg = GetLipsiaName(\"vccm\");\n \n\n /*\n ** parse command line\n */\n if (! VParseCommand (VNumber (options), options, & argc, argv)) {\n VReportUsage (argv[0], VNumber (options), options, NULL);\n exit (EXIT_FAILURE);\n }\n if (argc > 1) {\n VReportBadArgs (argc, argv);\n exit (EXIT_FAILURE);\n }\n\n \n /*\n ** read mask\n */\n VAttrList mask_list = VReadAttrList(mask_filename,0L,TRUE,FALSE);\n if (mask_list == NULL) VError(\" error reading %s\",mask_filename);\n VImage mask = VReadImage(mask_list);\n if (mask == NULL) VError(\" no mask found\");\n\n\n\n /* \n ** read input images \n */\n int nslices=0,nt=0,nrows=0,ncols=0;\n int xslices=0,xnt=0,xrows=0,xcols=0;\n int nsubjects = (int)in_files.number;\n fprintf(stderr,\" nsubjects= %d\\n\",nsubjects);\n if (nsubjects < 2) VError(\" not enough input files (%d), CCM should be used on >= 2 data sets\",nsubjects);\n VImage **src = (VImage **) VCalloc(nsubjects,sizeof(VImage *));\n \n for (i=0; i\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n// #include \"mex.h\"\r\n\r\n#ifndef verbose\r\n#define verbose 0\r\n#endif \r\n/*\r\n $ ./fwhm > interp.dat\r\n $ graph -T ps < interp.dat > interp.ps\r\n */\r\n\r\nstruct dbg_data {\r\n double xm; // location of maxima\r\n double ym; // value at maxima\r\n double xleft;\r\n double xright;\r\n};\r\n\r\nFILE * logFile;\r\n\r\n// my_f and my_f_params defines the interpolation function that the\r\n// root-finding functions are run on\r\n\r\nstruct my_f_params {\r\n gsl_spline * spline;\r\n gsl_interp_accel * acc;\r\n double offset; // shifts the function\r\n};\r\n\r\ndouble my_f(double , void * );\r\nint findmin(double , double , gsl_spline *, gsl_interp_accel * , size_t , double * , double * );\r\nstatic void createGaussian(double * , double * , size_t , double );\r\nint fwhm(double * , double * , size_t , double * );\r\n\r\n\r\n\r\ndouble my_f(double x, void * p)\r\n{\r\n struct my_f_params * params = (struct my_f_params*) p;\r\n#if verbose > 0\r\n printf(\"f(%f) + %f= \", x, params->offset); fflush(stdout);\r\n#endif\r\n\r\n double y = -gsl_spline_eval(params->spline, x, params->acc) + params->offset;\r\n#if verbose > 0\r\n printf(\"%f\\n\", y); fflush(stdout);\r\n#endif\r\n\r\n return(y);\r\n}\r\n\r\nint findmin(double a, double b, \r\n gsl_spline *spline, gsl_interp_accel * acc, \r\n size_t N, \r\n double * xm, double * ym)\r\n{\r\n\r\n // a, b: range of function\r\n int iter = 0, max_iter = 100; \r\n double m = 0; // expected location of minima\r\n\r\n int status; \r\n const gsl_min_fminimizer_type *T; \r\n gsl_min_fminimizer *s;\r\n\r\n struct my_f_params f_params;\r\n f_params.spline = spline;\r\n f_params.acc = acc;\r\n f_params.offset = 0;\r\n\r\n gsl_function F;\r\n F.function = &my_f;\r\n F.params = (void *) &f_params;\r\n\r\n T = gsl_min_fminimizer_brent;\r\n s = gsl_min_fminimizer_alloc (T); \r\n if(gsl_min_fminimizer_set (s, &F, m, a, b) == GSL_EINVAL)\r\n {\r\n // If no minima is enclosed ... i.e. the value at (a+b)/2 isn't lower than at a and b\r\n gsl_min_fminimizer_free(s);\r\n return 1;\r\n }\r\n\r\n#if verbose > 0\r\n fflush(stdout);\r\n printf(\"Interval: [%f, %f]\\n\", a, b);\r\n double m_expected = -10; \r\n printf (\"method: '%s'\\n\", gsl_min_fminimizer_name (s));\r\n printf (\"%5s [%9s, %9s] %9s %10s %9s\\n\", \"iter\", \"lower\", \"upper\", \"min\", \"err\", \"err(est)\");\r\n printf (\"%5d [%.7f, %.7f] %.7f %+.7f %.7f\\n\", iter, a, b, m, m - m_expected, b - a); \r\n#endif\r\n\r\n do {\r\n iter++;\r\n status = gsl_min_fminimizer_iterate (s);\r\n\r\n a = gsl_min_fminimizer_x_lower (s);\r\n b = gsl_min_fminimizer_x_upper (s);\r\n\r\n status = gsl_min_test_interval (a, b, 0.001, 0.0);\r\n\r\n#if verbose > 0\r\n float m = gsl_min_fminimizer_x_minimum (s); \r\n if (status == GSL_SUCCESS) {\r\n printf (\"Converged:\\n\");\r\n } else { printf(\"No convergence %d\\n\", status); }\r\n\r\n printf (\"%5d [%.7f, %.7f] \" \"%.7f %+.7f %.7f\\n\", iter, a, b, m, m - m_expected, b - a);\r\n#endif\r\n\r\n } while (status == GSL_CONTINUE && iter < max_iter);\r\n\r\n xm[0] = (a+b)/2;\r\n ym[0] = my_f(xm[0], &f_params);\r\n\r\n gsl_min_fminimizer_free(s);\r\n\r\n#if verbose > 0\r\n printf(\"Status: %d\\n\", status);\r\n#endif \r\n\r\n return status;\r\n}\r\n\r\n\r\n\r\nint fwhm(double * x, double * y, size_t N, double * w)\r\n{\r\n\r\n int useLog = 0;\r\n\r\n if(verbose)\r\n {\r\n useLog = 1;\r\n }\r\n\r\n if(useLog)\r\n {\r\n logFile = fopen(\"/tmp/fwhmlog\", \"w\");\r\n }\r\n\r\n\r\n#ifndef debug\r\ngsl_set_error_handler_off();\r\n#endif\r\n\r\n int N2 = (N-1)/2; // even number\r\n\r\n // Set up interpolation\r\n gsl_interp_accel *acc = gsl_interp_accel_alloc(); // Neccessary?\r\n gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, N);\r\n gsl_spline_init(spline, x, y, N);\r\n\r\n // See that the correct value is given at x=0\r\n#if verbose > 0\r\n printf(\"y[%f] = %f\\n\", x[N2], gsl_spline_eval(spline, x[N2], acc));\r\n fflush(stdout);\r\n#endif\r\n\r\n // Find position of max, i.e., centre in [xmin, xmax]\r\n double xmin = -2.5;\r\n double xmax = 2.501;\r\n\r\n double xm = 10e99;\r\n double ym = 10e99;\r\n#if verbose > 0\r\n printf(\"calling findmin\\n\"); fflush(stdout);\r\n#endif\r\n if( findmin(xmin, xmax, spline, acc, N, &xm, &ym) )\r\n {\r\n#if verbose > 0\r\n printf(\"Could not find the position of the maxima!\\n\");\r\n#endif\r\n gsl_spline_free (spline);\r\n gsl_interp_accel_free (acc);\r\n\r\n if(useLog)\r\n {\r\n fclose(logFile);\r\n }\r\n return 1;\r\n }\r\n\r\n if(useLog)\r\n {\r\n fprintf(logFile, \"xm: %f, ym: %f\\n\", xm, ym);\r\n }\r\n\r\n#if verbose > 0\r\n printf(\"-> Minima: f(%f) = %f\\n\", xm, ym);\r\n#endif \r\n\r\n // Determine background\r\n double bg = (y[0]+y[N-1])/2;\r\n#if verbose > 0\r\n printf(\"Background level: %f\\n\", bg);\r\n#endif\r\n\r\n if(useLog)\r\n {\r\n fprintf(logFile, \"bg: %f\\n\", bg);\r\n }\r\n\r\n if(bg <= ym)\r\n {\r\n fprintf(logFile, \"stopping, bg <= tm\\n\");\r\n if(useLog)\r\n {\r\n fclose(logFile);\r\n }\r\n gsl_spline_free (spline);\r\n gsl_interp_accel_free (acc);\r\n\r\n return 1;\r\n }\r\n\r\n // Find intersection .5*(max-bg) for each side\r\n // ROOT FINDING\r\n\r\n const gsl_root_fsolver_type * Tsolve = gsl_root_fsolver_bisection;\r\n gsl_root_fsolver * rsolve = gsl_root_fsolver_alloc(Tsolve);\r\n\r\n // Search for left and right intersections\r\n\r\n double intersections[2];\r\n intersections[0] = 0; intersections[1] = 0;\r\n\r\n for(int dire = 0; dire<2; dire++)\r\n {\r\n // Search in range [x_lo, x_hi] \r\n double x_lo;\r\n double x_hi;\r\n\r\n if(dire==0)\r\n {\r\n x_lo = -N2;\r\n x_hi = xm;\r\n }\r\n\r\n if(dire==1)\r\n {\r\n x_lo = xm;\r\n x_hi = N2;\r\n }\r\n\r\n struct my_f_params f_params;\r\n f_params.spline = spline;\r\n f_params.acc = acc;\r\n f_params.offset = (bg+(-ym-bg)/2);\r\n\r\n if(useLog)\r\n {\r\n fprintf(logFile, \"x_lo: %f x_hi: %f\\n\", x_lo, x_hi);\r\n fprintf(logFile, \"offset: %f, bg: %f, ym: %f\\n\", f_params.offset, bg, ym);\r\n }\r\n\r\n gsl_function F;\r\n F.function = &my_f;\r\n F.params = (void *) &f_params;\r\n\r\n /* \r\n * Function: int gsl_root_fsolver_set (gsl_root_fsolver * s, gsl_function * f, double x_lower, double x_upper)\r\n * This function initializes, or reinitializes, an existing solver s to use the function f and the initial \r\n * search interval [x_lower, x_upper]\r\n */\r\n\r\n int status = gsl_root_fsolver_set(rsolve, &F, x_lo, x_hi);\r\n\r\n size_t iter = 0;\r\n size_t max_iter = 10;\r\n\r\n#if verbose > 0\r\n double r_expected = (x_lo+x_hi)/2;\r\n printf (\"using %s method\\n\", gsl_root_fsolver_name (rsolve));\r\n printf (\"%5s [%9s, %9s] %9s %10s %9s\\n\", \"iter\", \"lower\", \"upper\", \"root\", \"err\", \"err(est)\");\r\n#endif\r\n\r\n\r\n do {\r\n iter++;\r\n status = gsl_root_fsolver_iterate (rsolve);\r\n // update bounds\r\n x_lo = gsl_root_fsolver_x_lower (rsolve);\r\n x_hi = gsl_root_fsolver_x_upper (rsolve);\r\n // see if converged\r\n status = gsl_root_test_interval (x_lo, x_hi, 0, 0.001);\r\n#if verbose > 0\r\n double r = gsl_root_fsolver_root (rsolve); \r\n if (status == GSL_SUCCESS)\r\n printf (\"Converged:\\n\");\r\n printf (\"%5lu [%.7f, %.7f] %.7f %+.7f %.7f\\n\", iter, x_lo, x_hi,\r\n r, r - r_expected,\r\n x_hi - x_lo);\r\n#endif\r\n }\r\n while (status == GSL_CONTINUE && iter < max_iter); \r\n \r\n#if verbose > 0\r\n printf(\"Found intersection at %f\\n\", (x_lo+x_hi)/2);\r\n#endif\r\n intersections[dire] = (x_lo+x_hi)/2;\r\n\r\n if(useLog)\r\n {\r\n fprintf(logFile, \"intersection %d: %f\\n\", dire, (x_lo+x_hi)/2);\r\n }\r\n }\r\n\r\n gsl_root_fsolver_free(rsolve);\r\n\r\n // Clean up\r\n gsl_spline_free (spline);\r\n gsl_interp_accel_free (acc);\r\n\r\n // fwhm: right-left positions\r\n w[0] = intersections[1] - intersections[0];\r\n\r\n if(useLog)\r\n {\r\n fclose(logFile);\r\n }\r\n\r\n return 0; // Ok\r\n}\r\n\r\nstatic void createGaussian(\r\n double * x, \r\n double * y, \r\n size_t N, \r\n double x0)\r\n{\r\n /* Create a gaussian shaped test signal, y\r\n * over the domain x\r\n * x0 is the offset from center\r\n * */\r\n int N2 = (N-1)/2; // middle element\r\n\r\n for(int kk=0; kk0\r\n printf(\"%f %f\\n\", x[kk], y[kk]);\r\n#endif\r\n }\r\n}\r\n\r\n\r\nint main(int argc, char ** argv)\r\n{\r\n\r\n int N = 11; // Size of test signal\r\n double * y = malloc(N*sizeof(double));\r\n double * x = malloc(N*sizeof(double));\r\n memset(x, 0, N*sizeof(double));\r\n memset(y, 0, N*sizeof(double));\r\n createGaussian(x,y, N, 0);\r\n\r\n double w = -1; // output\r\n\r\n if(1){\r\n for(double delta = -1; delta <=1; delta +=0.1)\r\n {\r\n\r\n createGaussian(x,y, N, delta);\r\n if(fwhm(x, y, N, &w))\r\n {\r\n printf(\"Error: Could not calculate fwhm!\\n\");\r\n }\r\n\r\n printf(\"offset: % .2f pixels, fwhm: %f pixels\\n\", delta, w);\r\n }\r\n }\r\n\r\n for(int kk = 0; kk\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common.c\"\n#include \"qrsolv.c\"\n\ntypedef struct\n{\n size_t p;\n gsl_matrix *QR; /* QR factorization of J */\n gsl_vector *tau_Q; /* Householder scalars for Q */\n gsl_matrix *T; /* workspace matrix for qrsolv, p-by-p */\n gsl_permutation *perm; /* permutation matrix */\n size_t rank; /* rank of J */\n gsl_vector *residual; /* residual of LS problem [ J; sqrt(mu) D ] p = - [ f; 0 ] */\n gsl_vector *qtf; /* Q^T f */\n gsl_vector *workn; /* workspace, length n */\n gsl_vector *workp; /* workspace, length p */\n gsl_vector *work3p; /* workspace, length 3*p */\n double mu; /* LM parameter */\n} qr_state_t;\n\nstatic int qr_init(const void * vtrust_state, void * vstate);\nstatic int qr_presolve(const double mu, const void * vtrust_state, void * vstate);\nstatic int qr_solve(const gsl_vector * f, gsl_vector *x,\n const void * vtrust_state, void *vstate);\nstatic int qr_rcond(double * rcond, void * vstate);\n\nstatic void *\nqr_alloc (const size_t n, const size_t p)\n{\n qr_state_t *state;\n\n (void)n;\n \n state = calloc(1, sizeof(qr_state_t));\n if (state == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate qr state\", GSL_ENOMEM);\n }\n\n state->QR = gsl_matrix_alloc(n, p);\n if (state->QR == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for QR\", GSL_ENOMEM);\n }\n\n state->tau_Q = gsl_vector_alloc(p);\n if (state->tau_Q == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for tau_Q\",\n GSL_ENOMEM);\n }\n\n state->T = gsl_matrix_alloc(p, p);\n if (state->T == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for T\", GSL_ENOMEM);\n }\n\n state->qtf = gsl_vector_alloc(n);\n if (state->qtf == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for qtf\",\n GSL_ENOMEM);\n }\n\n state->residual = gsl_vector_alloc(n);\n if (state->residual == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for residual\",\n GSL_ENOMEM);\n }\n\n state->perm = gsl_permutation_calloc(p);\n if (state->perm == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for perm\",\n GSL_ENOMEM);\n }\n\n state->workn = gsl_vector_alloc(n);\n if (state->workn == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workn\",\n GSL_ENOMEM);\n }\n\n state->workp = gsl_vector_alloc(p);\n if (state->workp == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workp\",\n GSL_ENOMEM);\n }\n\n state->work3p = gsl_vector_alloc(3 * p);\n if (state->work3p == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for work3p\",\n GSL_ENOMEM);\n }\n\n state->p = p;\n state->mu = 0.0;\n state->rank = 0;\n\n return state;\n}\n\nstatic void\nqr_free(void *vstate)\n{\n qr_state_t *state = (qr_state_t *) vstate;\n\n if (state->QR)\n gsl_matrix_free(state->QR);\n\n if (state->tau_Q)\n gsl_vector_free(state->tau_Q);\n\n if (state->T)\n gsl_matrix_free(state->T);\n\n if (state->qtf)\n gsl_vector_free(state->qtf);\n\n if (state->residual)\n gsl_vector_free(state->residual);\n\n if (state->perm)\n gsl_permutation_free(state->perm);\n\n if (state->workn)\n gsl_vector_free(state->workn);\n\n if (state->workp)\n gsl_vector_free(state->workp);\n\n if (state->work3p)\n gsl_vector_free(state->work3p);\n\n free(state);\n}\n\n/* compute J = Q R PT */\nstatic int\nqr_init(const void * vtrust_state, void * vstate)\n{\n const gsl_multifit_nlinear_trust_state *trust_state =\n (const gsl_multifit_nlinear_trust_state *) vtrust_state;\n qr_state_t *state = (qr_state_t *) vstate;\n int signum;\n\n /* perform QR decomposition of J */\n gsl_matrix_memcpy(state->QR, trust_state->J);\n gsl_linalg_QRPT_decomp(state->QR, state->tau_Q, state->perm,\n &signum, state->workp);\n\n return GSL_SUCCESS;\n}\n\nstatic int\nqr_presolve(const double mu, const void * vtrust_state, void * vstate)\n{\n qr_state_t *state = (qr_state_t *) vstate;\n\n state->mu = mu;\n\n (void) vtrust_state;\n\n return GSL_SUCCESS;\n}\n\nstatic int\nqr_solve(const gsl_vector * f, gsl_vector *x,\n const void * vtrust_state, void *vstate)\n{\n qr_state_t *state = (qr_state_t *) vstate;\n int status;\n\n if (state->mu == 0.0)\n {\n /*\n * compute Gauss-Newton direction by solving\n * J x = f\n * with an attempt to identify rank deficiency in J\n */\n size_t rank = gsl_linalg_QRPT_rank(state->QR, -1.0);\n status = gsl_linalg_QRPT_lssolve2(state->QR, state->tau_Q, state->perm,\n f, rank, x, state->residual);\n }\n else\n {\n /*\n * solve:\n *\n * [ J ] x = [ f ]\n * [ sqrt(mu) D ] [ 0 ]\n *\n * using QRPT factorization of J\n */\n\n const gsl_multifit_nlinear_trust_state *trust_state =\n (const gsl_multifit_nlinear_trust_state *) vtrust_state;\n double sqrt_mu = sqrt(state->mu);\n\n /* compute qtf = Q^T f */\n gsl_vector_memcpy(state->qtf, f);\n gsl_linalg_QR_QTvec(state->QR, state->tau_Q, state->qtf);\n\n status = qrsolv(state->QR, state->perm, sqrt_mu, trust_state->diag,\n state->qtf, state->T, x, state->workn);\n }\n\n /* reverse step to go downhill */\n gsl_vector_scale(x, -1.0);\n\n return status;\n}\n\nstatic int\nqr_rcond(double * rcond, void * vstate)\n{\n int status;\n qr_state_t *state = (qr_state_t *) vstate;\n\n status = gsl_linalg_QRPT_rcond(state->QR, rcond, state->work3p);\n\n return status;\n}\n\nstatic const gsl_multifit_nlinear_solver qr_type =\n{\n \"qr\",\n qr_alloc,\n qr_init,\n qr_presolve,\n qr_solve,\n qr_rcond,\n qr_free\n};\n\nconst gsl_multifit_nlinear_solver *gsl_multifit_nlinear_solver_qr = &qr_type;\n", "meta": {"hexsha": "a865baf256dab1eb90949da4e7bf1d3d382b6f3e", "size": 7293, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit_nlinear/qr.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/qr.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/qr.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 25.4111498258, "max_line_length": 90, "alphanum_fraction": 0.6232003291, "num_tokens": 2033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4460407877437989}} {"text": "#include \n#include \"AFS.h\"\n#include \"AFS_ctmc_petsc.h\"\n#include \"im_clam.h\"\n#include \"sparseExp.h\"\n#include \"cs.h\"\n#include \"AFS_ctmc.h\"\n#include \"nlopt.h\"\n#include \"adkGSL.h\"\n#include \n#include \n#include \n#include \n//Functions for jointly computing CTMC transitions and embedded chain\n\n//this function fills two petsc matrices: 1) embedded Discrete MC trans Mat, 2) CTMC trans mat\n// also fills the rates vector\n\nvoid fillPetscTransMats(afsStateSpace *S, double *topol, int *moveType, int *nzCount,\n\tint *dim1, int *dim2, double theta1, double theta2, double mig1, double mig2, Mat *DTMC, Mat *CTMC, gsl_vector *rates){\n\tint i, j,k, newnz, abcount=0;\n\tint N = S->nstates,abFlag;\n\tdouble c0r[N],c1r[N],m0r[N],m1r[N],totR[N],rowSums[N], tmp;;\n\t\n\tgsl_vector_set_zero(rates);\n\t//set rates vector\n\tfor(i=0;istates[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) / theta1 ;\n\t\tif(theta2 == 0)\n\t\t\tc1r[i] = 0.0;\n\t\telse\n\t\t\tc1r[i] = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) / theta2;\n\t\n\t\tm0r[i] = S->states[i]->aCounts[0] * mig1 ;\n\t\tm1r[i] = S->states[i]->aCounts[1] * mig2 ;\n\t\ttotR[i] = c0r[i] + c1r[i] + m0r[i] + m1r[i];\n\t\n\t\t\n\t\trowSums[i] = 0.0;\n\t\tif(S->states[i]->nalleles > 1 && c0r[i] >= 0 && c1r[i] >= 0 && totR[i] != 0.0)\n\t\t\tgsl_vector_set(rates,i,1.0/totR[i]);\n\t\telse\n\t\t\tgsl_vector_set(rates,i,0);\n\t}\n\n\tnewnz=0;\n\tfor(k=0;k<*nzCount;k++){\n\t\ti = dim1[k];\n\t\tj= dim2[k];\n//\t\tprintf(\"i: %d, j:%d, movetype: %d\\n\",i,j,moveType[k]);\n\t\tif(S->states[i]->nalleles ==1 || S->states[j]->nalleles ==1 )abFlag=1;\n\t//\tif(S->states[i]->nalleles ==1 )abFlag=1;\n\t\telse abFlag = 0;\n\t\tswitch(moveType[k]){\n\t\t\tcase 0: //coal pop0\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = c0r[i] / totR[i] * topol[k];\n\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)MatSetValue(*DTMC,i,j,tmp,INSERT_VALUES);\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase 1: //coal pop1\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = c1r[i] / totR[i] * topol[k];\n\t\t\t\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)MatSetValue(*DTMC,i,j,tmp,INSERT_VALUES);\t\t\t\n\t\t\tbreak;\n\t\t\tcase 2: //mig pop0\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = m0r[i] / totR[i] * topol[k];\n\t\t\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)MatSetValue(*DTMC,i,j,tmp,INSERT_VALUES);\t\t\t\n\t\t\tbreak;\n\t\t\tcase 3: //mig pop1\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = m1r[i] / totR[i] * topol[k];\t\t\t\n\t\t\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)MatSetValue(*DTMC,i,j,tmp,INSERT_VALUES);\t\t\n\t\t\tbreak;\n\t\t\tcase -1:\n\t\t\tabcount+=1;\n\t\t\tbreak;\t\t\t\n\t\t}\n\t}\n\tnewnz=*nzCount ;\n\t//now add diagonal elements; topol pre-set to -1\n\tfor(k=0;knstates,abFlag;\n\tdouble c0r[N],c1r[N],m0r[N],m1r[N],totR[N],rowSums[N], tmp;;\n\tstruct cs_di_sparse *triplet, *tmat;\n\t\n\t//allocate new cs_sparse obj\n\ttriplet = cs_spalloc(N, N, *nzCount + N , 1, 1); //alloc sparse mat with extra space for nonzero identity mats\n\t\n\tgsl_vector_set_zero(rates);\n\t//set rates vector\n\tfor(i=0;istates[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) / theta1 ;\n\t\tif(theta2 == 0)\n\t\t\tc1r[i] = 0.0;\n\t\telse\n\t\t\tc1r[i] = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) / theta2;\n\t\tm0r[i] = S->states[i]->aCounts[0] * mig1 ;\n\t\tm1r[i] = S->states[i]->aCounts[1] * mig2 ;\n\t\ttotR[i] = c0r[i] + c1r[i] + m0r[i] + m1r[i];\n\t\n\t\t\n\t\trowSums[i] = 0.0;\n\t\tif(S->states[i]->nalleles > 1 && c0r[i] >= 0 && c1r[i] >= 0 && totR[i] != 0.0)\n\t\t\tgsl_vector_set(rates,i,1.0/totR[i]);\n\t\telse\n\t\t\tgsl_vector_set(rates,i,0);\n\t}\n\n\tnewnz=0;\n\tfor(k=0;k<*nzCount;k++){\n\t\ti = dim1[k];\n\t\tj= dim2[k];\n//\t\tprintf(\"i: %d, j:%d, movetype: %d\\n\",i,j,moveType[k]);\n\t\tif(S->states[i]->nalleles ==1 || S->states[j]->nalleles ==1 )abFlag=1;\n\t//\tif(S->states[i]->nalleles ==1 )abFlag=1;\n\t\telse abFlag = 0;\n\t\tswitch(moveType[k]){\n\t\t\tcase 0: //coal pop0\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = c0r[i] / totR[i] * topol[k];\n\t\t//\tprintf(\"here--- i:%d j:%d tmp*totR[i]:%f\",i,j,tmp*totR[i]);\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)cs_entry(triplet,i,j,tmp);\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase 1: //coal pop1\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = c1r[i] / totR[i] * topol[k];\n\t\t\t\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)cs_entry(triplet,i,j,tmp);\t\t\t\n\t\t\tbreak;\n\t\t\tcase 2: //mig pop0\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = m0r[i] / totR[i] * topol[k];\n\t\t\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)cs_entry(triplet,i,j,tmp);\t\t\t\n\t\t\tbreak;\n\t\t\tcase 3: //mig pop1\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = m1r[i] / totR[i] * topol[k];\t\t\t\n\t\t\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)cs_entry(triplet,i,j,tmp);\t\t\n\t\t\tbreak;\n\t\t\tcase -1:\n\t\t\tabcount+=1;\n\t\t\tbreak;\t\t\t\n\t\t}\n\t}\n\tnewnz=*nzCount ;\n\t//now add diagonal elements; topol pre-set to -1\n\tfor(k=0;knstates,abFlag;\n\tdouble *c0r,*c1r,*m0r,*m1r,*totR,*rowSums, tmp;\n\tstruct cs_di_sparse *tmat;\n\t\n\tc0r = malloc(sizeof(double)*N);\n\tc1r = malloc(sizeof(double)*N);\n\tm0r = malloc(sizeof(double)*N);\n\tm1r = malloc(sizeof(double)*N);\n\ttotR = malloc(sizeof(double)*N);\n\trowSums = malloc(sizeof(double)*N);\n\t\n\tgsl_vector_set_zero(rates);\n\t//set rates vector\n\tfor(i=0;istates[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) / theta1 ;\n\t\tif(theta2 == 0)\n\t\t\tc1r[i] = 0.0;\n\t\telse\n\t\t\tc1r[i] = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) / theta2;\n\t\tm0r[i] = S->states[i]->aCounts[0] * mig1 ;\n\t\tm1r[i] = S->states[i]->aCounts[1] * mig2 ;\n\t\ttotR[i] = c0r[i] + c1r[i] + m0r[i] + m1r[i];\n\t\n\t\t\n\t\trowSums[i] = 0.0;\n\t\tif(S->states[i]->nalleles > 1 && c0r[i] >= 0 && c1r[i] >= 0 && totR[i] != 0.0)\n\t\t\tgsl_vector_set(rates,i,1.0/totR[i]);\n\t\telse\n\t\t\tgsl_vector_set(rates,i,0);\n\t}\n\n\tnewnz=0;\n\tfor(k=0;k<*nzCount;k++){\n\t\ti = dim1[k];\n\t\tj= dim2[k];\n//\t\tprintf(\"i: %d, j:%d, movetype: %d\\n\",i,j,moveType[k]);\n\t\tif(S->states[i]->nalleles ==1 || S->states[j]->nalleles ==1 )abFlag=1;\n\t//\tif(S->states[i]->nalleles ==1 )abFlag=1;\n\t\telse abFlag = 0;\n\t\tswitch(moveType[k]){\n\t\t\tcase 0: //coal pop0\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = c0r[i] / totR[i] * topol[k];\n\t\t//\tprintf(\"here--- i:%d j:%d tmp*totR[i]:%f\",i,j,tmp*totR[i]);\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)cs_entry(triplet,i,j,tmp);\t\t\t\t\n\t\t\tbreak;\n\t\t\tcase 1: //coal pop1\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = c1r[i] / totR[i] * topol[k];\n\t\t\t\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)cs_entry(triplet,i,j,tmp);\t\t\t\n\t\t\tbreak;\n\t\t\tcase 2: //mig pop0\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = m0r[i] / totR[i] * topol[k];\n\t\t\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)cs_entry(triplet,i,j,tmp);\t\t\t\n\t\t\tbreak;\n\t\t\tcase 3: //mig pop1\n\t\t\tif(totR[i]==0)tmp=0;\n\t\t\telse tmp = m1r[i] / totR[i] * topol[k];\t\t\t\n\t\t\n\t\t\tMatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES);\t\n\t\t\trowSums[i] += tmp* totR[i];\n\t\t\tif(abFlag==0)cs_entry(triplet,i,j,tmp);\t\t\n\t\t\tbreak;\n\t\t\tcase -1:\n\t\t\tabcount+=1;\n\t\t\tbreak;\t\t\t\n\t\t}\n\t}\n\tnewnz=*nzCount ;\n\t//now add diagonal elements; topol pre-set to -1\n\tfor(k=0;kstateSpace->nstates;\n \tcs *spMat, *mt, *tmpMat ;\n \tdouble timeV, sum, thetaA, theta2, mig1, mig2;\n \tPetscInt Na;\n \tgsl_vector *tmpStates;\n \tcss *S ;\n\tcsn *NN ;\n\tPetscInt n,Ntmp ;\n\tdouble *xx;\n \tPetscInt iStart,iEnd, *idx;\n\tconst PetscInt *idx2;\n\tPetscScalar *tmpArray;\n\tconst PetscScalar *tmpArrayC;\n\tPetscErrorCode ierr;\n\tMFNConvergedReason reason;\n\t\n \t//initialize some vectors\n \tgsl_vector_set_zero(params->rates);\n\tMatZeroEntries(params->C);\n\tMatZeroEntries(params->C2);\n \ttmpStates = gsl_vector_alloc(N);\n\tNtmp=N;\n\tNa=params->Na;\n \t//For straight MLE the paramVector takes the form [N2,NA,m1,m2,t]\n \ttheta2 = gsl_vector_get(params->paramVector,0);\n \tthetaA = gsl_vector_get(params->paramVector,1);\n \tmig1 = gsl_vector_get(params->paramVector,2);\n \tmig2 = gsl_vector_get(params->paramVector,3);\n \ttimeV = gsl_vector_get(params->paramVector,4);\n// \tprintf(\"params-> %f %f %f %f %f\\n\",theta2,thetaA,mig1,mig2,timeV);\n// \tprintf(\"nnz %d nnzA%d \\n\",params->nnz,params->nnzA);\n \n\t//fill transMat\n //\ttmpMat = fillPetscCsparseTransMats_prealloc(params->stateSpace, params->top, params->move, ¶ms->nnz,\n //\t\tparams->dim1, params->dim2, 1, theta2, mig1, mig2, ¶ms->C, params->rates,params->triplet);\n \n\ttmpMat = fillPetscCsparseTransMats(params->stateSpace, params->top, params->move, ¶ms->nnz,\n\t \t\tparams->dim1, params->dim2, 1, theta2, mig1, mig2, ¶ms->C, params->rates);\t\n\t//using CSparse\n\t// S = (I-P)^-1\n\t//add negative ident\n//\tident = cs_spalloc(N,N,N,1,1);\n//\tfor(i=0;ieye,tmpMat,1.0,-1.0);\n\t//cs_print_adk(spMat);\n\tmt = cs_transpose(spMat,1);\n\t//cs_print_adk(mt);\n\t\n\n\tn = mt->n ;\n\tS = cs_sqr (0, mt, 0) ; /* ordering and symbolic analysis */\n\tNN = cs_lu (mt, S, 1e-12) ; /* numeric LU factorization */\n\txx = cs_malloc (n, sizeof (double)) ; /* get workspace */\n\t\n\tMatGetOwnershipRange(params->denseMat1,&iStart,&iEnd);\n\tPetscMalloc1(N,&idx);\n\tfor(j=0;jb[i] = 0.0;\n\t\tparams->b[j]=1.0;\n\t\t//factor outside loop leads to ~40x speedup\n\t\tcs_ipvec (NN->pinv, params->b, xx, n) ; /* x = b(p) */\n\t\tcs_lsolve (NN->L, xx) ; /* x = L\\x */\n\t\tcs_usolve (NN->U, xx) ; /* x = U\\x */\n\t\tcs_ipvec (S->q, xx, params->b, n) ; /* b(q) = x */\n\t//\tif(!rank)printf(\"row %d\\n\",j);\n\t\tMatSetValues(params->denseMat1,1,&j,N,idx,params->b,INSERT_VALUES);\n\t}\n\tMatAssemblyBegin(params->denseMat1,MAT_FINAL_ASSEMBLY);\n\tMatAssemblyEnd(params->denseMat1,MAT_FINAL_ASSEMBLY);\n\t//temporary clean up\n\tfree(xx);\n\tcs_spfree(spMat);\n\tcs_spfree(mt);\n//\tcs_spfree(ident);\n//\tcs_spfree(eye);\n\tcs_spfree(tmpMat);\n\tcs_nfree(NN);\n\tcs_sfree(S);\n\tPetscFree(idx);\n\n//\tMatView(params->denseMat1,PETSC_VIEWER_STDOUT_WORLD);\n\n\t//broadcast the invMat[0,] as vector to each processor\n\tif(params->rank==0){\n\t\tMatGetRow(params->denseMat1,0,&N,&idx2,&tmpArrayC);\n\t\tfor (j = 0; j < N; j++) params->b[j] = tmpArrayC[j];\n\t\tMatRestoreRow(params->denseMat1,0,&Ntmp,&idx2,&tmpArrayC);\t//have to use Ntmp here as MatRestoreRow does something funky\n\t}\n\tMPI_Bcast(params->b,N,MPI_DOUBLE,0,PETSC_COMM_WORLD);\n\t\n\n\t//Get Island Time 0-INF Unnormal\n\tgsl_matrix_set_zero(params->expAFS);\n\tfillExpectedAFS_unnorm(params->stateSpace, params->b,params->rates,params->expAFS);\n\t// printf(\"////////////////////Island Time 0 - INF unnormalized\\n\");\n\t// for(i=0;i< (params->n1+1) ;i++){\n\t// \tfor(j=0;j< (params->n2+1);j++){\n\t// \t\tprintf(\"%.5f \",gsl_matrix_get(params->expAFS,i,j));\n\t// \t}\n\t// \tprintf(\"\\n\");\n\t// }\n\t\n\t//Matrix Exponentiation to get state vector at time t\n\t//SLEPC Stuff ahead!\n\t/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n\tCreate the solver and set various options\n\t- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */\n\n\t/* \n\tSet operator matrix, the function to compute, and other options\n\t*/\n\t//transpose\n\tMatTranspose(params->C,MAT_REUSE_MATRIX,¶ms->C);\n\tierr = MFNSetOperator(params->mfn,params->C);CHKERRV(ierr);\n\t/*\n\tSet solver parameters at runtime\n\t*/\n\t\n\tierr = MFNSetScaleFactor(params->mfn,timeV); CHKERRV(ierr);\n\tierr = MFNSetFromOptions(params->mfn);CHKERRV(ierr);\n\n\t/* set v = e_1 */\n\tierr = MatGetVecs(params->C,PETSC_NULL,¶ms->y);CHKERRV(ierr);\n\tierr = MatGetVecs(params->C,¶ms->v, PETSC_NULL);CHKERRV(ierr);\n\tierr = VecSetValue(params->v,0,1.0,INSERT_VALUES);CHKERRV(ierr);\n\n\tierr = VecAssemblyBegin(params->v);CHKERRV(ierr);\n\tierr = VecAssemblyEnd(params->v);CHKERRV(ierr);\n\tierr = MFNSolve(params->mfn,params->v,params->y);CHKERRV(ierr);\n\tierr = MFNGetConvergedReason(params->mfn,&reason);CHKERRV(ierr);\n\tif (reason!=MFN_CONVERGED_TOL) ierr = 1; CHKERRV(ierr);\n\n\t//retranspose for later use\n\tMatTranspose(params->C,MAT_REUSE_MATRIX,¶ms->C);\n\n\t//state vector at time t stored in y\n\t//scatter y and store in expoArray\n\tVecScatterCreateToAll(params->y,¶ms->ctx,¶ms->v_seq);\n\tVecScatterBegin(params->ctx,params->y,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\tVecScatterEnd(params->ctx,params->y,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\tVecGetArray(params->v_seq,&tmpArray);\n\tfor (j = 0; j < N; j++){\n\t\tparams->expoArray[j] = tmpArray[j];\n\t\t//printf(\"%.5f\\n\",expoArray[j]);\t\n\t} \n\n\tVecRestoreArray(params->v_seq,&tmpArray);\n\tVecScatterDestroy(¶ms->ctx);\n\tVecDestroy(¶ms->v_seq);\n\tVecDuplicate(params->y,¶ms->x);\n\t\n\t//VecView(y, PETSC_VIEWER_STDOUT_WORLD);\n\tMatMultTranspose(params->denseMat1,params->y,params->x);\n\tVecScatterCreateToAll(params->x,¶ms->ctx,¶ms->v_seq);\n\tVecScatterBegin(params->ctx,params->x,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\tVecScatterEnd(params->ctx,params->x,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\tVecGetArray(params->v_seq,&tmpArray);\n\tfor (j = 0; j < N; j++){\n\t\tparams->b[j] = tmpArray[j];\n\t\t//printf(\"rank %d expoArray[%d]:%.5f\\n\",rank,j,expoArray[j]);\t\n\t\t//printf(\"rank %d b[%d]:%.5f\\n\",rank,j,b[j]);\t\n\t} \n\n\tVecRestoreArray(params->v_seq,&tmpArray);\n\tVecScatterDestroy(¶ms->ctx);\n\tVecDestroy(¶ms->v_seq);\n\n\n\tfillExpectedAFS_unnorm(params->stateSpace, params->b,params->rates,params->expAFS2);\n\t//now subtract older AFS (t_t - t_INF) from total AFS (t_0 - t_INF)\n\t/////////////////\n\t///////\n\n\tgsl_matrix_sub(params->expAFS,params->expAFS2);\n\t\n\t//////////////////////\n\t//Final phase, collapse popns, reset rates\n\t//now collapse populations\n\t//state vector at time t stored in st[] for largerStateSpace; use reverseMap\n\tfor(i=0;ist[i]=0.0;\n\tfor(i=0;ist[params->map[i]]+=params->expoArray[i];\n\t//\tprintf(\"expoArray[%d]:%f\\n\",i,expoArray[i]);\n\t}\n\tfor(i=0; ireducedStateSpace->nstates; i++){\n\t\tVecSetValue(params->ancStateVec,i,params->st[params->reverseMap[i]],INSERT_VALUES );\n\t}\n\n\t//Re-Fill trans mats for Ancestral Params\n\n\tparams->nnzA = coalMarkovChainTopologyMatrix_sparse(params->reducedStateSpace,params->topA,params->moveA, params->dim1A, params->dim2A);\n\t\n\ttmpMat=fillPetscCsparseTransMats(params->reducedStateSpace, params->topA, params->moveA, ¶ms->nnzA,\n\t\tparams->dim1A, params->dim2A, thetaA, 0, 0, 0, ¶ms->C2, params->rates);\n\t//////////////////////\n\t//\n\t// S = (I-P)^-1\n\t//\n\t/////////\n\t//////\n\t//add negative ident\n//\tident = cs_spalloc(Na,Na,Na,1,1);\n//\tfor(i=0;ieyeAnc,tmpMat,1.0,-1.0);\n\n\t//cs_print_adk(spMat);\n\tmt = cs_transpose(spMat,1);\n\t//VecView(y,PETSC_VIEWER_STDOUT_WORLD);\n\tn = mt->n ;\n\tS = cs_sqr (0, mt, 0) ; /* ordering and symbolic analysis */\n\tNN = cs_lu (mt, S, 1e-12) ; /* numeric LU factorization */\n\txx = cs_malloc (n, sizeof (double)) ; /* get workspace */\n\tMatGetOwnershipRange(params->denseMat2,&iStart,&iEnd);\n//\tprintf(\"here\\n\");\n\tPetscFree(idx);\n\tPetscMalloc1(Na,&idx);\n\tfor(j=0;jb[i] = 0.0;\n\t\tparams->b[j]=1.0;\n\t\t//factor outside loop leads to ~40x speedup\n\t\tcs_ipvec (NN->pinv, params->b, xx, n) ; /* x = b(p) */\n\t\tcs_lsolve (NN->L, xx) ; /* x = L\\x */\n\t\tcs_usolve (NN->U, xx) ; /* x = U\\x */\n\t\tcs_ipvec (S->q, xx, params->b, n) ; /* b(q) = x */\n\t//\tif(!rank)printf(\"row %d\\n\",j);\n\t\tMatSetValues(params->denseMat2,1,&j,Na,idx,params->b,INSERT_VALUES);\n\t}\n\tMatAssemblyBegin(params->denseMat2,MAT_FINAL_ASSEMBLY);\n\tMatAssemblyEnd(params->denseMat2,MAT_FINAL_ASSEMBLY);\n\tfree(xx);\n\t\n\tMatMultTranspose(params->denseMat2,params->ancStateVec,params->ancResVec);\n\tVecScatterCreateToAll(params->ancResVec,¶ms->ctx,¶ms->v_seq);\n\tVecScatterBegin(params->ctx,params->ancResVec,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\tVecScatterEnd(params->ctx,params->ancResVec,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\n\n\tVecGetArray(params->v_seq,&tmpArray);\n\tfor (j = 0; j < Na; j++){\n\t\tparams->expoArray[j] = tmpArray[j];\n\t\t//printf(\"%.5f\\n\",expoArray[j]);\t\n\t}\n\n\tVecRestoreArray(params->v_seq,&tmpArray);\n\tVecScatterDestroy(¶ms->ctx);\n\tVecDestroy(¶ms->v_seq);\n\n\t//get contribution starting at st\n\tgsl_matrix_set_zero(params->expAFS2);\n\tfillExpectedAFS_unnorm(params->reducedStateSpace, params->expoArray,params->rates,params->expAFS2);\n\n\n\t// printf(\"////////////////////--Ancestral bit\\n\");\n\t// for(i=0;i< (n1+1) ;i++){\n\t// \tfor(j=0;j< (n2+1);j++){\n\t// \t\tprintf(\"%.5f \",gsl_matrix_get(expAFS2,i,j));\n\t// \t}\n\t// \tprintf(\"\\n\");\n\t// }\n\n\t//if(params->rank==0)printf(\"////////////////////normalized IM:\\n\");\n\t\t\t\n\tgsl_matrix_add(params->expAFS,params->expAFS2);\n\tsum = matrixSumDouble(params->expAFS);\n\tgsl_matrix_scale(params->expAFS, 1.0 / sum);\n\tparams->meanTreeLength = sum;\n\t// for(i=0;i< (params->n1+1) ;i++){\n\t// \t\tfor(j=0;j< (params->n2+1);j++){\n\t// \t\t\tif(params->rank==0)printf(\"%.5f \",gsl_matrix_get(params->expAFS,i,j));\n\t// \t\t}\n\t// \t\tif(params->rank==0)printf(\"\\n\");\n\t// \t}\n\t// \t\n\t\n\t//clean up\n\tPetscFree(idx);\n\tVecDestroy(¶ms->y);\n\tVecDestroy(¶ms->x);\n\tVecDestroy(¶ms->v);\n\tPetscFree(tmpArray);\n\tcs_spfree(spMat);\n\tcs_spfree(mt);\n//\tcs_spfree(ident);\n//\tcs_spfree(eye);\n\tcs_spfree(tmpMat);\n\tgsl_vector_free(tmpStates);\n\tcs_nfree(NN);\n\tcs_sfree(S);\n\t\n}\n\n\n//calcLogAFS_IM_allPETSC -- returns the expects log AFS from an IM model; only uses PETSC\nvoid calcLogAFS_IM_allPETSC(void * p){\n\tstruct clam_lik_params * params = (struct clam_lik_params *) p;\n\tPetscInt i,j, N = params->stateSpace->nstates;\n\tcs *spMat, *mt, *ident, *eye, *tmpMat ;\n\tdouble timeV, sum, thetaA, theta2, mig1, mig2;\n\tPetscInt Na;\n\tgsl_vector *tmpStates;\n\tcss *S ;\n\tcsn *NN ;\n\tPetscInt n,Ntmp ;\n\tdouble *xx;\n\tPetscInt iStart,iEnd, *idx;\n\tconst PetscInt *idx2;\n\tPetscScalar *tmpArray;\n\tPetscScalar negOne = -1.0;\n//\tPetscScalar one = 1.0;\n\n\tconst PetscScalar *tmpArrayC;\n\tPetscErrorCode ierr;\n\tIS perm,iperm;\n\tMatFactorInfo info;\n\tMFNConvergedReason reason;\n\n\n\t//initialize some vectors\n\tgsl_vector_set_zero(params->rates);\n\tMatZeroEntries(params->C);\n\tMatZeroEntries(params->C2);\n\tMatZeroEntries(params->D);\n\ttmpStates = gsl_vector_alloc(N);\n\tNtmp=N;\n\tNa=params->Na;\n\n\t//For straight MLE the paramVector takes the form [N2,NA,m1,m2,t]\n\ttheta2 = gsl_vector_get(params->paramVector,0);\n\tthetaA = gsl_vector_get(params->paramVector,1);\n\tmig1 = gsl_vector_get(params->paramVector,2);\n\tmig2 = gsl_vector_get(params->paramVector,3);\n\ttimeV = gsl_vector_get(params->paramVector,4);\n// \tprintf(\"params-> %f %f %f %f %f\\n\",theta2,thetaA,mig1,mig2,timeV);\n// \tprintf(\"nnz %d nnzA%d \\n\",params->nnz,params->nnzA);\n\n\t//fill transMat\n\tfillPetscTransMats(params->stateSpace, params->top, params->move, ¶ms->nnz,\n\t\tparams->dim1, params->dim2, 1, theta2, mig1, mig2, ¶ms->D, ¶ms->C, params->rates);\n\n\t//using CSparse\n\t// S = (I-P)^-1\n\t//subtract DTMC mat from identity\n\t\n\tMatZeroEntries(params->D_copy);\n\tMatCopy(params->ident,params->D_copy,DIFFERENT_NONZERO_PATTERN);\n\tMatAXPY(params->D_copy,negOne,params->D,DIFFERENT_NONZERO_PATTERN);\n//\tMatTranspose(params->D_copy,MAT_REUSE_MATRIX,¶ms->D);\n\n\tierr = MatGetOrdering(params->D_copy, MATORDERINGNATURAL, &perm, &iperm);\n\t \n\tierr = MatFactorInfoInitialize(&info); \n\tierr = MatGetFactor(params->D_copy,MATSOLVERSUPERLU_DIST,MAT_FACTOR_LU,¶ms->F); \n\tPetscInt icntl_7 = 5;\n\t//ierr = MatMumpsSetIcntl(params->F,7,icntl_7);\n\tinfo.fill = 5.0; \n\tierr = MatLUFactorSymbolic(params->F,params->D_copy,perm,iperm,&info);\n\tierr = MatLUFactorNumeric(params->F,params->D_copy,&info);\n\n\n\t//ierr = MatLUFactor(params->D_copy, perm, iperm, &info); \n\n\t////Compute Entire Inverse Mat\n\tierr = MatMatSolve(params->F,params->denseIdent,params->denseMat1); \n\n\n\t//MatView(params->denseMat1,PETSC_VIEWER_STDOUT_SELF);\t\n\n//\tMatGetOwnershipRange(params->denseMat1,&iStart,&iEnd);\n//\tPetscMalloc1(N,&idx);\n//\tfor(j=0;jbInv);\n// \t\tVecZeroEntries(params->xInv);\n// \t\tVecSetValue(params->bInv,j,one,INSERT_VALUES);\n// \t\tVecAssemblyBegin(params->bInv);\n// \t\tVecAssemblyEnd(params->bInv);\n// \n// \t\tKSPSolve(params->ksp,params->bInv,params->xInv);\n// \t\tVecGetValues(params->x,N,idx,hold);\n// \t\tMatSetValues(params->denseMat1,1,&j,N,idx,hold,INSERT_VALUES);\n// \t}\n// \tMatAssemblyBegin(params->denseMat1,MAT_FINAL_ASSEMBLY);\n// \tMatAssemblyEnd(params->denseMat1,MAT_FINAL_ASSEMBLY);\n// \t//temporary clean up\n// //\tfree(xx);\n// //\tcs_spfree(spMat);\n// //\tcs_spfree(mt);\n// //\tcs_spfree(ident);\n// //\tcs_spfree(eye);\n// //\tcs_spfree(tmpMat);\n// //\tcs_nfree(NN);\n// //\tcs_sfree(S);\n// \tPetscFree(idx);\n// \tKSPDestroy(¶ms->ksp);\n//\tMatView(params->denseMat1,PETSC_VIEWER_STDOUT_WORLD);\n\n\n\tMatDestroy(¶ms->F);\n\t//broadcast the invMat[0,] as vector to each processor\n\tif(params->rank==0){\n\t\tMatGetRow(params->denseMat1,0,&N,&idx2,&tmpArrayC);\n\t\tfor (j = 0; j < N; j++) params->b[j] = tmpArrayC[j];\n\t\tMatRestoreRow(params->denseMat1,0,&Ntmp,&idx2,&tmpArrayC);\t//have to use Ntmp here as MatRestoreRow does something funky\n\t}\n\tMPI_Bcast(params->b,N,MPI_DOUBLE,0,PETSC_COMM_WORLD);\n\n\n\t//Get Island Time 0-INF Unnormal\n\tgsl_matrix_set_zero(params->expAFS);\n\tfillExpectedAFS_unnorm(params->stateSpace, params->b,params->rates,params->expAFS);\n\t// printf(\"////////////////////Island Time 0 - INF unnormalized\\n\");\n\t// for(i=0;i< (params->n1+1) ;i++){\n\t// \tfor(j=0;j< (params->n2+1);j++){\n\t// \t\tprintf(\"%.5f \",gsl_matrix_get(params->expAFS,i,j));\n\t// \t}\n\t// \tprintf(\"\\n\");\n\t// }\n\n\t//Matrix Exponentiation to get state vector at time t\n\t//SLEPC Stuff ahead!\n\t/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n\tCreate the solver and set various options\n\t- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */\n\n\t/* \n\tSet operator matrix, the function to compute, and other options\n\t*/\n\t//transpose\n\tMatTranspose(params->C,MAT_REUSE_MATRIX,¶ms->C);\n\tierr = MFNSetOperator(params->mfn,params->C);CHKERRV(ierr);\n\t/*\n\tSet solver parameters at runtime\n\t*/\n\n\tierr = MFNSetScaleFactor(params->mfn,timeV); CHKERRV(ierr);\n\tierr = MFNSetFromOptions(params->mfn);CHKERRV(ierr);\n\n\t/* set v = e_1 */\n\tierr = MatGetVecs(params->C,PETSC_NULL,¶ms->y);CHKERRV(ierr);\n\tierr = MatGetVecs(params->C,¶ms->v, PETSC_NULL);CHKERRV(ierr);\n\tierr = VecSetValue(params->v,0,1.0,INSERT_VALUES);CHKERRV(ierr);\n\n\tierr = VecAssemblyBegin(params->v);CHKERRV(ierr);\n\tierr = VecAssemblyEnd(params->v);CHKERRV(ierr);\n\tierr = MFNSolve(params->mfn,params->v,params->y);CHKERRV(ierr);\n\tierr = MFNGetConvergedReason(params->mfn,&reason);CHKERRV(ierr);\n\tif (reason!=MFN_CONVERGED_TOL) ierr = 1; CHKERRV(ierr);\n\n\t//retranspose for later use\n\tMatTranspose(params->C,MAT_REUSE_MATRIX,¶ms->C);\n\n\t//state vector at time t stored in y\n\t//scatter y and store in expoArray\n\tVecScatterCreateToAll(params->y,¶ms->ctx,¶ms->v_seq);\n\tVecScatterBegin(params->ctx,params->y,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\tVecScatterEnd(params->ctx,params->y,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\tVecGetArray(params->v_seq,&tmpArray);\n\tfor (j = 0; j < N; j++){\n\t\tparams->expoArray[j] = tmpArray[j];\n\t\t//printf(\"%.5f\\n\",expoArray[j]);\t\n\t} \n\n\tVecRestoreArray(params->v_seq,&tmpArray);\n\tVecScatterDestroy(¶ms->ctx);\n\tVecDestroy(¶ms->v_seq);\n\tVecDuplicate(params->y,¶ms->x);\n\n\t//VecView(y, PETSC_VIEWER_STDOUT_WORLD);\n\tMatMultTranspose(params->denseMat1,params->y,params->x);\n\tVecScatterCreateToAll(params->x,¶ms->ctx,¶ms->v_seq);\n\tVecScatterBegin(params->ctx,params->x,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\tVecScatterEnd(params->ctx,params->x,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\tVecGetArray(params->v_seq,&tmpArray);\n\tfor (j = 0; j < N; j++){\n\t\tparams->b[j] = tmpArray[j];\n\t\t//printf(\"rank %d expoArray[%d]:%.5f\\n\",rank,j,expoArray[j]);\t\n\t\t//printf(\"rank %d b[%d]:%.5f\\n\",rank,j,b[j]);\t\n\t} \n\n\tVecRestoreArray(params->v_seq,&tmpArray);\n\tVecScatterDestroy(¶ms->ctx);\n\tVecDestroy(¶ms->v_seq);\n\n\n\tfillExpectedAFS_unnorm(params->stateSpace, params->b,params->rates,params->expAFS2);\n\t//now subtract older AFS (t_t - t_INF) from total AFS (t_0 - t_INF)\n\t/////////////////\n\t///////\n\n\tgsl_matrix_sub(params->expAFS,params->expAFS2);\n\n\t//////////////////////\n\t//Final phase, collapse popns, reset rates\n\t//now collapse populations\n\t//state vector at time t stored in st[] for largerStateSpace; use reverseMap\n\tfor(i=0;ist[i]=0.0;\n\tfor(i=0;ist[params->map[i]]+=params->expoArray[i];\n\t//\tprintf(\"expoArray[%d]:%f\\n\",i,expoArray[i]);\n\t}\n\tfor(i=0; ireducedStateSpace->nstates; i++){\n\t\tVecSetValue(params->ancStateVec,i,params->st[params->reverseMap[i]],INSERT_VALUES );\n\t}\n\n\t//Re-Fill trans mats for Ancestral Params\n\n\tparams->nnzA = coalMarkovChainTopologyMatrix_sparse(params->reducedStateSpace,params->topA,params->moveA, params->dim1A, params->dim2A);\n\n\ttmpMat=fillPetscCsparseTransMats(params->reducedStateSpace, params->topA, params->moveA, ¶ms->nnzA,\n\t\tparams->dim1A, params->dim2A, thetaA, 0, 0, 0, ¶ms->C2, params->rates);\n\t//////////////////////\n\t//\n\t// S = (I-P)^-1\n\t//\n\t/////////\n\t//////\n\t//add negative ident\n\tident = cs_spalloc(Na,Na,Na,1,1);\n\tfor(i=0;in ;\n\tS = cs_sqr (0, mt, 0) ; /* ordering and symbolic analysis */\n\tNN = cs_lu (mt, S, 1e-12) ; /* numeric LU factorization */\n\txx = cs_malloc (n, sizeof (double)) ; /* get workspace */\n\tMatGetOwnershipRange(params->denseMat2,&iStart,&iEnd);\n//\tprintf(\"here\\n\");\n//\tPetscFree(idx);\n\tPetscMalloc1(Na,&idx);\n\tfor(j=0;jb[i] = 0.0;\n\t\tparams->b[j]=1.0;\n\t\t//factor outside loop leads to ~40x speedup\n\t\tcs_ipvec (NN->pinv, params->b, xx, n) ; /* x = b(p) */\n\t\tcs_lsolve (NN->L, xx) ; /* x = L\\x */\n\t\tcs_usolve (NN->U, xx) ; /* x = U\\x */\n\t\tcs_ipvec (S->q, xx, params->b, n) ; /* b(q) = x */\n\t//\tif(!rank)printf(\"row %d\\n\",j);\n\t\tMatSetValues(params->denseMat2,1,&j,Na,idx,params->b,INSERT_VALUES);\n\t}\n\tMatAssemblyBegin(params->denseMat2,MAT_FINAL_ASSEMBLY);\n\tMatAssemblyEnd(params->denseMat2,MAT_FINAL_ASSEMBLY);\n\tfree(xx);\n\n\tMatMultTranspose(params->denseMat2,params->ancStateVec,params->ancResVec);\n\tVecScatterCreateToAll(params->ancResVec,¶ms->ctx,¶ms->v_seq);\n\tVecScatterBegin(params->ctx,params->ancResVec,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\tVecScatterEnd(params->ctx,params->ancResVec,params->v_seq,INSERT_VALUES,SCATTER_FORWARD);\n\n\n\tVecGetArray(params->v_seq,&tmpArray);\n\tfor (j = 0; j < Na; j++){\n\t\tparams->expoArray[j] = tmpArray[j];\n\t\t//printf(\"%.5f\\n\",expoArray[j]);\t\n\t}\n\n\tVecRestoreArray(params->v_seq,&tmpArray);\n\tVecScatterDestroy(¶ms->ctx);\n\tVecDestroy(¶ms->v_seq);\n\n\t//get contribution starting at st\n\tgsl_matrix_set_zero(params->expAFS2);\n\tfillExpectedAFS_unnorm(params->reducedStateSpace, params->expoArray,params->rates,params->expAFS2);\n\n\n\t// printf(\"////////////////////--Ancestral bit\\n\");\n\t// for(i=0;i< (n1+1) ;i++){\n\t// \tfor(j=0;j< (n2+1);j++){\n\t// \t\tprintf(\"%.5f \",gsl_matrix_get(expAFS2,i,j));\n\t// \t}\n\t// \tprintf(\"\\n\");\n\t// }\n\n\t//if(params->rank==0)printf(\"////////////////////normalized IM:\\n\");\n\n\tgsl_matrix_add(params->expAFS,params->expAFS2);\n\tsum = matrixSumDouble(params->expAFS);\n\tgsl_matrix_scale(params->expAFS, 1.0 / sum);\n\t// for(i=0;i< (params->n1+1) ;i++){\n\t// \t\tfor(j=0;j< (params->n2+1);j++){\n\t// \t\t\tif(params->rank==0)printf(\"%.5f \",gsl_matrix_get(params->expAFS,i,j));\n\t// \t\t}\n\t// \t\tif(params->rank==0)printf(\"\\n\");\n\t// \t}\n\t// \t\n\n\t//clean up\n\tPetscFree(idx);\n\tVecDestroy(¶ms->y);\n\tVecDestroy(¶ms->x);\n\tVecDestroy(¶ms->v);\n\tierr = ISDestroy(&perm);\n \tierr = ISDestroy(&iperm);\n\tPetscFree(tmpArray);\n\tcs_spfree(spMat);\n\tcs_spfree(mt);\n\tcs_spfree(ident);\n\tcs_spfree(eye);\n\tcs_spfree(tmpMat);\n\tgsl_vector_free(tmpStates);\n\tcs_nfree(NN);\n\tcs_sfree(S);\n\n}\ndouble calcLikNLOpt(unsigned n, const double *point, double *gradients, void *p){\n\tint i,j;\n\tstruct clam_lik_params * params = (struct clam_lik_params *) p;\n\tdouble localNNZ = params->nnz;\n\tdouble output = 666.0; \n\tdouble lik=0.0;\n\tdouble x[5];\n\t\n\tfor(i = 0;i<5;i++) x[i] = point[i];\n\tMPI_Bcast(x,5,MPI_DOUBLE,0,PETSC_COMM_WORLD);\n\t\n\tfor(i = 0;i<5;i++) gsl_vector_set(params->paramVector, i, x[i]);\n\t\n\t//fill in the expAFS table\n\tcalcLogAFS_IM(p);\n\tparams->nnz = localNNZ;\n\t//compute lik\n\tfor(i=0;iobsData->size1;i++){\n\t\tfor(j=0;jobsData->size2;j++){\n\t\t\tif (gsl_matrix_get(params->expAFS,i,j) > 0.0) //corners of AFS are zero prob\n\t\t\t\tlik += gsl_matrix_get(params->obsData,i,j) * (log(gsl_matrix_get(params->expAFS,i,j)));\n\t\t}\n\t}\n\toutput = -1.0* lik;\n\tMPI_Bcast(&output,1,MPI_DOUBLE,0,PETSC_COMM_WORLD);\n\tif(params->rank == 0 && vbse){\n\t\tfor(i = 0;i<5;i++) printf(\"x[%d]: %lf\\t\",i,x[i]);\n\t\tprintf(\"lik: %lf\\n\",lik);\n\t}\n\tparams->fEvals += 1;\n//\tgsl_matrix_prettyPrint(params->expAFS);\n\treturn(output);\n}\n\ndouble calcLikNLOpt_gradients(unsigned n, const double *point, double *gradients, void *p){\n\tint i,j;\n\t//struct clam_lik_params * params = (struct clam_lik_params *) p;\n\t//double localNNZ = params->nnz;\n\tdouble output = 666.0; \n\tdouble lik=0.0;\n\tdouble newF;\n\tdouble x[5];\n\tdouble temp[5];\n\tdouble epsilon=1e-5;\n\t\n\t\n\tfor(i = 0;i<5;i++) x[i] = point[i];\n\tMPI_Bcast(x,5,MPI_DOUBLE,0,PETSC_COMM_WORLD);\n\t\n\tlik = calcLikNLOpt(n, point, NULL, p);\n\tif (gradients != NULL){\n\t\tfor(i=0; iexpAFS);\n\treturn(output);\n}\n\n//maximizeLik-- maximizes the logLikFunction function using constraints via\n// nlOpt library\n\nvoid maximizeLikNLOpt(double *lik, void *p, double *mle){\n\t//struct clam_lik_params * params = (struct clam_lik_params *) p;\n\tint np = 5;\n\tint err;\n\t//double x[5] = {1.0,1.0,1.0,1.0,1.5};\n\tdouble minimum=666.6;\n\tnlopt_opt opt;\n\t\n\topt = nlopt_create(NLOPT_LD_LBFGS, np);\n\t//define constraints\n\n\n\tnlopt_set_lower_bounds(opt, lowerBounds);\n\tnlopt_set_upper_bounds(opt, upperBounds);\n\tnlopt_set_min_objective(opt, calcLikNLOpt_gradients, (void *) p);\n\t\n\tnlopt_set_xtol_rel(opt, 1e-6);\n\t//set the seed for deterministic sequence in COBYLA alg\n\t//nlopt_srand(1232333);\n\terr = nlopt_optimize(opt, mle, &minimum);\n\tif (err < 0) {\n\t fprintf(stderr,\"nlopt failed with code %d!\\n\",err);\n\t}\n//\tMPI_Barrier(MPI_COMM_WORLD);\n\t*lik=minimum;\n\tnlopt_destroy(opt);\n\t\n}\n\n//maximizeLikNLOpt_twoStage-- begins with coarse global, then goes local\n\nvoid maximizeLikNLOpt_twoStage(double *lik, void *p, double *mle){\n\t//struct clam_lik_params * params = (struct clam_lik_params *) p;\n\tint np = 5;\n\tint err;\n\t//double x[5] = {1.0,1.0,1.0,1.0,1.5};\n\tdouble minimum=666.6;\n\tnlopt_opt opt;\n\t\n\topt = nlopt_create(NLOPT_GN_DIRECT_L_RAND, np);\n\n\n\tnlopt_set_lower_bounds(opt, lowerBounds);\n\tnlopt_set_upper_bounds(opt, upperBounds);\n\tnlopt_set_min_objective(opt, calcLikNLOpt_gradients, (void *) p);\n\t\n\n\n\t\n\t//nlopt_set_xtol_rel(opt, 0.25);\n\t//set the seed for deterministic sequence in COBYLA alg\n\t//nlopt_srand(1232333);\n\terr = nlopt_optimize(opt, mle, &minimum);\n\tif (err < 0) {\n\t fprintf(stderr,\"nlopt failed with code %d!\\n\",err);\n\t}\n//\tMPI_Barrier(MPI_COMM_WORLD);\n\t*lik=minimum;\n\tnlopt_destroy(opt);\n\t\n\t\n}\n\n//maximizeLikNLOpt_MLSL-- multi-level restarts\n\nvoid maximizeLikNLOpt_MLSL(double *lik, void *p, double *mle){\n\tint np = 5;\n\tint err;\n\t//double x[5] = {1.0,1.0,1.0,1.0,1.5};\n\tdouble minimum=666.6;\n\tnlopt_opt opt, l_opt;\n\t\n\topt = nlopt_create(NLOPT_G_MLSL, np);\n\n\n\tnlopt_set_lower_bounds(opt, lowerBounds);\n\tnlopt_set_upper_bounds(opt, upperBounds);\n\tnlopt_set_min_objective(opt, calcLikNLOpt_gradients, (void *) p);\n\t\n\tl_opt = nlopt_create(NLOPT_LD_LBFGS, np);\n\tnlopt_set_lower_bounds(l_opt, lowerBounds);\n\tnlopt_set_upper_bounds(l_opt, upperBounds);\n\tnlopt_set_min_objective(l_opt, calcLikNLOpt_gradients, (void *) p);\n\t//define constraints\n\n\n\tnlopt_set_local_optimizer(opt, l_opt);\n\t\n\t//nlopt_set_xtol_rel(opt, 0.25);\n\t//set the seed for deterministic sequence in COBYLA alg\n\t//nlopt_srand(1232333);\n\terr = nlopt_optimize(opt, mle, &minimum);\n\tif (err < 0) {\n\t fprintf(stderr,\"nlopt failed with code %d!\\n\",err);\n\t}\n//\tMPI_Barrier(MPI_COMM_WORLD);\n\t*lik=minimum;\n\tnlopt_destroy(l_opt);\n\tnlopt_destroy(opt);\n\t\n\t\n}\n\n\n///////////////// Hessian stuff ///////////////////\n\ndouble hessianMatrix_element(double lik, double *mle, int i, int j, double hi, double hj, void *p){\n\t//struct clam_lik_params * params = (struct clam_lik_params *) p;\n\tdouble Pi0, Pj0,output,fpp,fpm,fmp,fmm;\n\t\n\tPi0 = mle[i]; Pj0 = mle[j];\n\t\n\t//printf(\"mle: %f\\n\",lik);\t\n\tif(i==j){\n\t\tmle[i] = Pi0 + hi;\n\t\tfpp = calcLikNLOpt(5,mle,NULL,p);\n\t\tmle[i] = Pj0 - hi;\n\t\tfmm = calcLikNLOpt(5,mle,NULL,p);\n\t\toutput = ((fpp - lik) + (fmm - lik))/(hi*hi);\n\t}\n\telse{\n\t\t// f(xi + hi, xj + h)\n\t\tmle[i] = Pi0 + hi;\n\t\tmle[j] = Pj0 + hj;\n\t\tfpp = calcLikNLOpt(5,mle,NULL,p);\n\n\t // f(xi + hi, xj - hj)\n\t\tmle[i] = Pi0 + hi;\n\t\tmle[j] = Pj0 - hj;\n\t\tfpm = calcLikNLOpt(5,mle,NULL,p);\n\n\t // f(xi - hi, xj + hj)\n\t\tmle[i] = Pi0 - hi;\n\t\tmle[j] = Pj0 + hj;\n\t\tfmp = calcLikNLOpt(5,mle,NULL,p);\n\n\t // f(xi - hi, xj - hj)\n\t\tmle[i] = Pi0 - hi;\n\t\tmle[j] = Pj0 - hj;\n\t\tfmm = calcLikNLOpt(5,mle,NULL,p);\n\n\t\toutput = (fpp - fpm - fmp + fmm)/(4 * hi * hj);\n\t}\n\tmle[i]=Pi0; mle[j]=Pj0;\n\treturn output;\n}\n\ngsl_matrix *hessian(double *mle, double lik, void *p){\n\tint i, j;\n\tdouble eps;\n\tgsl_matrix *H;\n\t\n\t\n\tH = gsl_matrix_alloc(5,5);\n\teps = 0.01;\n\tfor(i=0;i<5;i++){\n\t\tfor (j=i;j<5;j++){\n\t\t\tgsl_matrix_set(H,i,j,hessianMatrix_element(lik, mle, i, j, eps, eps, p));\n\t\t\tgsl_matrix_set(H,j,i,gsl_matrix_get(H,i,j));\n\t\t}\n\t}\n\treturn(H);\n}\n\ngsl_matrix *getFisherInfoMatrix(double *mle, double lik, void *p){\n\tgsl_matrix *H;\n\tgsl_matrix *fi;\n\tgsl_permutation *perm = gsl_permutation_alloc(5);\n\tint s;\n\t\n\tH = hessian(mle,lik,p);\n\t//gsl_matrix_prettyPrint(H);printf(\"\\n\");\n\tfi = gsl_matrix_alloc(5,5);\n\tgsl_matrix_scale(H,-1.0);\n\tgsl_linalg_LU_decomp (H, perm, &s); \n\tgsl_linalg_LU_invert (H, perm, fi);\n\t//gsl_matrix_prettyPrint(fi);printf(\"\\n\");\n\treturn(fi);\n}\n\ngsl_matrix *getGodambeInfoMatrix(double *mle, double lik, void *p){\n\tgsl_matrix *H;\n\tgsl_matrix *J,*Jtemp, *Jinv, *origData, *boot;\n\tgsl_vector *cU, *grad_temp;\n\tstruct clam_lik_params * params = (struct clam_lik_params *) p;\n\tgsl_permutation *perm = gsl_permutation_alloc(5);\n\tint s,i, nBoot;\n\t\n\torigData = params->obsData;\n\tnBoot = 100;\n\t\n\tH = hessian(mle,lik,p);\n\tgsl_matrix_scale(H,-1.0);\n\t//gsl_matrix_prettyPrint(H);printf(\"\\n\");\n\tJ = gsl_matrix_alloc(5,5);\n\tJinv = gsl_matrix_alloc(5,5);\n\tJtemp = gsl_matrix_alloc(5,5);\n\tboot = gsl_matrix_alloc(origData->size1,origData->size2);\n\t\n\tgsl_matrix_set_zero(J);\n\tgsl_matrix_set_zero(Jinv);\n\tgsl_matrix_set_zero(Jtemp);\n\tcU = gsl_vector_alloc(5);\n\tgsl_vector_set_zero(cU);\n\t\n\t//do bootstraps, estimate J\n\tfor(i=0;irng);\n\t\tparams->obsData = boot;\n\t\tgrad_temp = getGradient(mle,p);\n\t\tgsl_vector_outer_product(grad_temp,grad_temp,Jtemp);\n\t\tgsl_matrix_add(J,Jtemp);\n\t\tgsl_vector_add(cU,grad_temp);\n\t\t//gsl_matrix_prettyPrint(Jtemp);\n\t\tgsl_vector_free(grad_temp);\n\t}\n\tgsl_vector_scale(cU,1.0/(float)nBoot);\n\tgsl_matrix_scale(J,1.0/(float)nBoot);\n\t//printf(\"cU:\\n\");\n\t//gsl_vector_fprintf(stdout,cU,\"%f\");\n\t//printf(\"J:\\n\");\n\t//gsl_matrix_prettyPrint(J);printf(\"\\n\");\n\t//G = H*J^-1*H\n\tgsl_linalg_LU_decomp (J, perm, &s); \n\tgsl_linalg_LU_invert (J, perm, Jinv);\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, H, Jinv, 0.0, Jtemp);\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Jtemp, H, 0.0, J);\n\t//printf(\"godambe:\\n\");\n\t//gsl_matrix_prettyPrint(J);printf(\"\\n\");\n\t//need to invert this to get the Godambe information matrix\n\tgsl_linalg_LU_decomp (J, perm, &s); \n\tgsl_linalg_LU_invert (J, perm, Jinv);\n\treturn(Jinv);\n}\n\ngsl_vector *getGradient(double *mle, void *p){\n\tint i, j;\n\tdouble eps, epsVals[5], paramTemp[5], fp, fm;\n\tgsl_vector *gradient;\n\t\n\tgradient = gsl_vector_alloc(5);\n\teps = 0.01;\n\tfor(i=0;i<5;i++){\n\t\tif( mle[i] != 0){\n\t\t\tepsVals[i] = mle[i] * eps;\n\t\t\t//printf(\"eps[%d]=%f\\n\",i,epsVals[i]);\n\t\t}\n\t\telse{\n\t\t\tepsVals[i] = eps;\n\t\t}\n\t\tparamTemp[i] = mle[i];\n\t}\n\tfor(i=0;i<5;i++){\n\t\tfor(j=0;j<5;j++) paramTemp[j] = mle[j];\n\t\tif( mle[i] != 0){\n\t\t\tparamTemp[i] = mle[i] + epsVals[i];\n\t\t\tfp = calcLikNLOpt(5,paramTemp,NULL,p);\n\t\t\tparamTemp[i] = mle[i] - epsVals[i];\n\t\t\tfm = calcLikNLOpt(5,paramTemp,NULL,p);\n\t\t\tgsl_vector_set(gradient,i,(fp-fm)/(2*epsVals[i]));\n\t\t}\n\t\telse{\n\t\t\tparamTemp[i] = mle[i] + epsVals[i];\n\t\t\tfp = calcLikNLOpt(5,paramTemp,NULL,p);\n\t\t\tparamTemp[i] = mle[i];\n\t\t\tfm = calcLikNLOpt(5,paramTemp,NULL,p);\n\t\t\tgsl_vector_set(gradient,i,(fp-fm)/epsVals[i]);\n\t\t}\n\t}\n\treturn(gradient);\n}\n\n", "meta": {"hexsha": "3e3e61b526d4f215854e1fc5730e6621426051b1", "size": 39760, "ext": "c", "lang": "C", "max_stars_repo_path": "AFS_ctmc_petsc.c", "max_stars_repo_name": "dortegadelv/IMaDNA", "max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-22T13:06:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T17:22:14.000Z", "max_issues_repo_path": "AFS_ctmc_petsc.c", "max_issues_repo_name": "dortegadelv/IMaDNA", "max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z", "max_forks_repo_path": "AFS_ctmc_petsc.c", "max_forks_repo_name": "kern-lab/im_clam", "max_forks_repo_head_hexsha": "e1643d7489106d5e040329bd0b7db75d80ce21d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.086786552, "max_line_length": 150, "alphanum_fraction": 0.6512323944, "num_tokens": 13965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4460022887937084}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// ***************************************************************************************\n// * Pre-Port Entwicklung und Testen eines OMP-parallisierten, adaptiven Simpson-integrators für \n// * die fiesen doppelintgrale in imd_colrad.c\n// ***************************************************************************************\nint num_threads;\nint simpson_error;\nint funcevals;\nint iter;\n\nconst double tolmax=1e-30;\n#define INITIAL_STACK_SIZE 128; //128 /* initial size of new stacks */\n\n\nconst double alpha=0.816496580927726;\nconst double beta=0.447213595499958; \nstatic const double xgkq[12] = \n{\n 0.0,\n -0.942882415695480,\n -0.816496580927726,\n -0.641853342345781,\n -0.447213595499958,\n -0.236383199662150,\n 0.0,\n 0.236383199662150,\n 0.447213595499958,\n 0.641853342345781,\n 0.816496580927726,\n 0.942882415695480\n};\n\n\n\n\n\n\n/* the stack structure */\nstruct stack_s{ \n int el_count; /* count of elements on stack */ \n int el_size; /* size of an element */\n int mem_reserve; /* allocated memory for stack */\n void* elements; /* pointer to begin of stack */\n};\n\n\nstruct my_f_params { double ne; double T;double mu; double E;double DeltaE; int allowed;};\n\n\n\ntypedef struct _work_t{\n double a;\n double b;\n double tol;\n double S;\n double fa;\n double fb;\n double fm;\n double rec;\n int iter;\n struct my_f_params * p; //pointer auf params\n} work_t;\n\n\ntypedef struct stack_s* stack_t;\n\ntypedef struct _work_t_gkq{\n double a;\n double b;\n double toler;\n double I_13;\n double fa;\n double fb;\n struct my_f_params * p; //pointer auf params\n double (*f)(double, struct my_f_params*);\n stack_t stack_inner;\n short int is_parent;\n short int subtask_nr; //inner task nr\n short int task_nr; //outer task nr\n short int subtasks_left; //erst pop'n wenn aller inner tasks (intergals) vollständig!\n double inner_integrals[5];\n} work_gkq;\n\n\n\n\n\n// **************************************** FUNCTION DEFS *************************************************\nvoid create_stack(stack_t* stack, int element_size);\nint empty_stack(stack_t stack);\nvoid push_stack(stack_t stack, void* element);\nvoid pop_stack(stack_t stack, void* element);\n\n\ndouble \nintegral2( double (*f)(double, struct my_f_params*), /* function to integrate */\n stack_t stack);\n\n\ndouble gkq_adapt_double(stack_t stack);\ndouble gkq_adapt_single(stack_t stack); //for single integral, first integral\n\ndouble gkq_double(double (*f)(double, struct my_f_params*), double (*finner)(double, struct my_f_params*), \n double a, double b, \n double TOL, struct my_f_params* p,stack_t stack);\n\ndouble gkq_adapt_serial(double (*f)(double, struct my_f_params*), double a, double b, double fa,double fb, double toler,double I_13, struct my_f_params* p);\n\nwork_gkq gkq_create_inner_task(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p);\ndouble gkq_single(double (*f)(double, struct my_f_params*), double a, double b, \n double TOL, struct my_f_params* p,stack_t stack);\n\nint terminate_serial;\nint terminate_gkq;\n\n// static double myfun(double x,struct my_f_params* p)\n// { \n// double T=p->T; \n// double fermi=1/(1+exp(-x/T));\n// double fermi2=1- 1/(1+exp(-x/T));\n// double sigma=x/T*log(x/T*2)/pow(1/x,2.0); //einfach nur ärger machen\n\n// // return exp(-x*x)/p->T+log(x*pow(p->T,2.0))/p->ne;\n// return fermi*fermi2*sigma;\n// }\n\n// static double myfun2(double x,void* pv)\n// { \n// struct my_f_params *p= (struct my_f_params*) pv; \n\n// double T=p->T; \n// double fermi=1/(1+exp(-x/T));\n// double fermi2=1- 1/(1+exp(-x/T));\n// double sigma=x/T*log(x/T*2)/pow(1/x,2.0); //einfach nur ärger machen\n\n \n// // return exp(-x*x)/p->T+log(x*pow(p->T,2.0))/p->ne;\n// return fermi*fermi2*sigma;\n// }\n\n\nstatic double inner_integrand(double x,void *pv)\n{\n struct my_f_params *p= (struct my_f_params*) pv; \n double T=p->T; \n double fermi=1/(1+exp(-x/T));\n double fermi2=1- 1/(1+exp(-x/T)); \n return exp(-x*x); //fermi*fermi2;\n}\nstatic double inner_integrand2(double x,struct my_f_params* p)\n{\n double T=p->T; \n double fermi=1/(1+exp(-x/T));\n double fermi2=1- 1/(1+exp(-x/T));\n return fermi*fermi2;\n}\nvoid get_integ_bounds_inner(double *integ_bnd, double x, struct my_f_params *p)\n{\n integ_bnd[0]=-4;\n integ_bnd[1]=4;\n}\n\ngsl_integration_workspace * gsinner;\ngsl_integration_workspace * gsinner2;\n\nstatic double myfun(double x,struct my_f_params* p)\n{ \n double T=p->T; \n double fermi=1/(1+exp(-x/T));\n double fermi2=1- 1/(1+exp(-x/T));\n double sigma=x/T*log(x/T*2)/pow(1/x,2.0); //einfach nur ärger machen\n\n // double result, err;\n // gsl_function gslfun;\n // gslfun.function=&inner_integrand;\n // gslfun.params=p; \n\n // gsl_integration_qag(&gslfun, x, 300, 0.0, 1e-3, 1000,1,\n // gsinner2, &result, &err); \n\n // gsl_integration_workspace_free(gsinner2);\n // stack_t stack2; \n // create_stack(&stack2, sizeof(work_gkq));\n\n //double result=gkq(inner_integrand2, x, 600, 1e-3, p);//, stack);\n // free(stack2->elements);\n\n\n return sigma;\n //return exp(-x*x);\n}; \n\n\nstatic double myfun_gsl(double x,void* pv)\n{ \n struct my_f_params *p= (struct my_f_params*) pv; \n\n double T=p->T; \n double fermi=1/(1+exp(-x/T));\n double fermi2=1- 1/(1+exp(-x/T));\n double sigma=x/T*log(x/T*2)/pow(1/x,2.0); //einfach nur ärger machen\n\n\n gsl_function gslfun;\n gslfun.function=&inner_integrand;\n gslfun.params=pv; \n double result, err;\n gsl_integration_qag(&gslfun, x, 600, 0.0, 1e-3, 1000,1,\n gsinner, &result, &err); \n\n return sigma*result;\n}\n\n\n// static double myfun2(double x,void* pv)\n// { \n// struct my_f_params *p= (struct my_f_params*) pv; \n// static float sinfc(float x) { return sinf(x); } \n// static double frand48c(double x) { funcevals++; return (double) drand48(); } \n\n// *************************************************************************************************************\nint main(int argc,char** argv)\n{\n iter=0;\n num_threads=omp_get_num_threads();\n funcevals=0;\n simpson_error=0;\n\n struct timeval start, end;\n \n double gsltime, simpsontime;\n // ************************************************\n gsinner= gsl_integration_workspace_alloc (1000); \n \n \n\n // double gslinteg=0.0;\n // double integ_err;\n\n // gsl_function gslfun;\n // gslfun.function=&myfun;\n\n\n // **********************************************\n\n double pi=3.141592653589793;\n double xmin, xmax;\n double answer = 0.0;\n\n int i;\n\n xmin=2;\n xmax=100; \n \n // ***********************************************\n double T0=1;\n double ne0=1e5;\n\n struct my_f_params ptest;\n ptest.T=T0;\n ptest.ne=ne0;\n\n // *************************************************\n int method=GSL_INTEG_GAUSS61;\n gsl_function gslfun;\n gslfun.function=&myfun_gsl;\n gslfun.params=&ptest; \n gsl_integration_workspace * gswork=NULL;\n gswork= gsl_integration_workspace_alloc (1000); \n double gslinteg=0.0;\n double integ_err;\n\n gettimeofday(&start, NULL); \n gsl_integration_qag(&gslfun, xmin, xmax, 0.0, 1e-8, 1000,1,\n gswork, &gslinteg, &integ_err); \n gettimeofday(&end, NULL);\n gsltime = ((end.tv_sec - start.tv_sec) * 1000000u + \n end.tv_usec - start.tv_usec) /1.e6;\n\n printf(\"gslres:%.12e, gsltime:%.4e\\n\", gslinteg, gsltime);\n // *************************************************\n\n stack_t stack; //global stack\n create_stack(&stack, sizeof(work_gkq));\n\n gettimeofday(&start, NULL); \n double integ=gkq_double(myfun,inner_integrand2, xmin, xmax, 1e-2, &ptest,stack);\n \n gettimeofday(&end, NULL);\n free(stack->elements);\n free(stack);\n\n double partime = ((end.tv_sec - start.tv_sec) * 1000000u + \n end.tv_usec - start.tv_usec) /1.e6;\n\n printf(\"my:%.12e, partime:%.4e\\n\", integ,partime);\n\n return 0;\n}\n\n\n\n/******************************************\n * create new stack\n ******************************************/\nvoid create_stack(\n stack_t* stack, /* stack to create */\n int element_size) /* size of a stack element */\n{\n int initial_size = INITIAL_STACK_SIZE;\n\n /* allocate memory for new stack struct */\n (*stack) = (stack_t) malloc(sizeof(struct stack_s));\n if (!(*stack)){\n fprintf(stderr, \"error: could not allocate memory for stack.. Abort.\\n\"); \n exit(1);\n } \n\n /* allocate memory for stack elements */\n (*stack)->elements = (void*) malloc(element_size * initial_size);\n (*stack)->mem_reserve = initial_size; \n if (!(*stack)->elements){\n fprintf(stderr, \"error: could not allocate memory for stack.. Abort.\\n\");\n exit(1);\n }\n\n (*stack)->el_size = element_size;\n (*stack)->el_count = 0;\n\n}\n\n/*****************************************\n * check if the stack is empty \n *****************************************/\nint empty_stack(stack_t stack)\n{\n //MYMOD\n if(stack==NULL)\n return 1;\n //ENDOF MYMOD\n return stack->el_count <= 0;\n}\n\n\n/*****************************************\n * push a element on stack\n *****************************************/\nvoid push_stack(\n stack_t stack, /* target stack */\n void* element) /* element to push */\n{\n int i, new_reserve;\n int log2_count;\n\n /* check if we need more memory for stack */ \n if (stack->el_count >= stack->mem_reserve)\n {\n\n /* calculate new size for the stack\n it should be a power of two */\n // for (i = stack->el_count, log2_count = 0; i > 0; i>>1, log2_count++);\n // new_reserve = 1 << log2_count;\n\n log2_count=0;\n for(i=stack->el_count;i>0; i=i*0.5) //i>>1)\n {\n log2_count++;\n }\n new_reserve= 1 << log2_count;\n \n /* reallocate memory for phase thread tables \n and nullify new values */\n stack->elements = (void *) realloc(stack->elements, \n stack->el_size * new_reserve);\n if (!stack->elements){\n fprintf(stderr, \"error: can't reallocate stack.. Aborting\\n\");\n exit(1);\n }\n\n stack->mem_reserve = new_reserve;\n }\n \n /* now push the element on top of the stack */\n memcpy((char*)stack->elements + stack->el_count*stack->el_size, \n element, stack->el_size);\n stack->el_count++;\n\n}\n\n\n/*****************************************\n * pop an element from stack\n *****************************************/\nvoid pop_stack(\n stack_t stack, /* target stack */\n void* element) /* where poped el. should be stored */\n{\n if (stack->el_count <= 0){\n fprintf(stderr, \"error: trying to pop from empty stack.\\n\");\n exit(2);\n }\n\n stack->el_count--;\n memcpy(element, \n (char*)stack->elements + stack->el_count*stack->el_size, \n stack->el_size);\n\n \n}\n\n\n\n\n\n// ***************************************************************************\n// * Gauss-kronard quadrature\n// ***************************************************************************\nwork_gkq gkq_create_inner_task(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p)\n{\n work_gkq work;\n\n work.f=f;\n struct my_f_params* pinner;\n pinner=(struct my_f_params*) malloc(sizeof(struct my_f_params)); //ACHTUNG: Muss wieder gefreed werden\n pinner->mu= p->mu;\n pinner->T=p->T;\n pinner->ne=p->ne;\n work.p=pinner;\n work.a=a;\n work.b=b;\n work.subtasks_left=0;//beliebig!\n\n double m=0.5*(a+b);\n double h=0.5*(b-a);\n double y[13];\n double fa=y[0]=f(a,p);\n double fb=y[12]=f(b,p);\n int i;\n for(i=1;i<12;i++)\n y[i]=f(m+xgkq[i]*h,p);\n\n double I_4= (h/6.0)*(y[0]+y[12]+5.0*(y[4]+y[8])); // 4-point gauss-lobatto\n double I_7= (h/1470.0)*(77.0*(y[0]+y[12])+432.0*(y[2]+y[10])+ // 7-point kronrod\n 625.0*(y[4]+y[8])+672.0*y[6]);\n\n double I_13= h*(0.0158271919734802*(y[0]+y[12])+0.0942738402188500*(y[1]+y[11])+0.155071987336585*(y[2]+y[10])+\n 0.188821573960182*(y[3]+y[9])+0.199773405226859*(y[4]+y[8])+0.224926465333340*(y[5]+y[7])+\n 0.242611071901408*y[6]); //13-point Kronrod\n\n \n double Err1=fabs(I_7-I_13);\n double Err2=fabs(I_4-I_13);\n\n double r=(Err2 != 0.0) ? Err1/Err2 : 1.0;\n double toler=(r > 0.0 && r < 1.0) ? TOL/r : TOL; \n\n if(I_13 == 0)\n I_13=b-a;\n I_13=fabs(I_13);\n\n// printf(\"create inner task: a:%f, b:%f, I4:%f,I7:%f,I13:%f\\n\",a,b,I_4,I_7,I_13);\n work.toler = toler;\n work.I_13=I_13;\n work.fa=fa;\n work.fb=fb;\n \n work.is_parent=0;\n for(i=0;i<5;i++)\n work.inner_integrals[i]=0.0;\n return work;\n\n}\n\n\n\ndouble gkq_double(double (*f)(double, struct my_f_params*), double (*finner)(double, struct my_f_params*), \n double a, double b, \n double TOL, struct my_f_params* p,stack_t stack)\n{\n //1st integration\n //create parent task\n\n double result=0.0;\n// ********************************************* \n\n double m=0.5*(a+b);\n double h=0.5*(b-a);\n int i;\n\n\n double y[13];\n\n stack_t st;\n create_stack(&st, sizeof(work_gkq));\n\n double integ_bnd[2];\n\n get_integ_bounds_inner(integ_bnd, a, p);\n y[0]=f(a,p)* gkq_single(finner,integ_bnd[0],integ_bnd[1],1e-3, p, st);\n\n for(i=1;i<12;i++)\n {\n get_integ_bounds_inner(integ_bnd, m+xgkq[i]*h, p);\n y[i]=f(m+xgkq[i]*h,p)*gkq_single(finner,integ_bnd[0],integ_bnd[1],1e-3,p,st);\n }\n\n get_integ_bounds_inner(integ_bnd, b, p);\n y[12]=f(b,p)*gkq_single(finner,integ_bnd[0],integ_bnd[1],1e-3, p, st);\n\n\n free(st->elements);\n free(st);\n\n\n \n double fa=y[0];\n double fb=y[12];\n\n\n double I_4= (h/6.0)*(y[0]+y[12]+5.0*(y[4]+y[8])); // 4-point gauss-lobatto\n double I_7= (h/1470.0)*(77.0*(y[0]+y[12])+432.0*(y[2]+y[10])+ // 7-point kronrod\n 625.0*(y[4]+y[8])+672.0*y[6]);\n\n double I_13= h*(0.0158271919734802*(y[0]+y[12])+0.0942738402188500*(y[1]+y[11])+0.155071987336585*(y[2]+y[10])+\n 0.188821573960182*(y[3]+y[9])+0.199773405226859*(y[4]+y[8])+0.224926465333340*(y[5]+y[7])+\n 0.242611071901408*y[6]); //13-point Kronrod\n\n \n \n\n double Err1=fabs(I_7-I_13);\n double Err2=fabs(I_4-I_13);\n\n double r=(Err2 != 0.0) ? Err1/Err2 : 1.0;\n double toler=(r > 0.0 && r < 1.0) ? TOL/r : TOL; \n\n if(I_13 == 0)\n I_13=b-a;\n I_13=fabs(I_13);\n\n printf(\"First approx I_13:%.4e\\n\",I_13); \n \n //Prepare work and push onto stack\n work_gkq work;\n work.a = a;\n work.b = b;\n work.toler = toler;\n work.I_13=I_13;\n work.fa=fa;\n work.fb=fb;\n\n work.p=p;\n work.f=f;\n work.is_parent=1;\n work.task_nr=0; //fange bei 0 das zählen an\n \n\n for(i=0;i<5;i++)\n work.inner_integrals[i]=0.0;\n \n // ALLOC INNER WS FOR INTEGR.\n // gsl_integration_workspace *gsinner2= gsl_integration_workspace_alloc (1000); \n \n stack_t stack_inner; \n create_stack(&stack_inner, sizeof(work_gkq));\n work.stack_inner=stack_inner;\n\n //push work on inner stack\n //for comp of 5 inner intgrals\n work_gkq winner;\n double m_inner, h_inner, mll_inner,ml_inner, mr_inner, mrr_inner;\n\n m_inner= (work.a+work.b)/2;\n h_inner= (work.a+work.b)/2;\n mll_inner=(m_inner-alpha*h_inner);\n ml_inner= (m_inner-beta*h_inner);\n mr_inner= (m_inner+beta*h_inner);\n mrr_inner=(m_inner+alpha*h_inner); \n\n\n //1st subtask\n get_integ_bounds_inner(integ_bnd, mll_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0], integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=0; \n winner.task_nr=work.task_nr;\n\n push_stack(work.stack_inner,&winner);\n\n //2nd subtask\n get_integ_bounds_inner(integ_bnd, ml_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0], integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=1;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner); \n\n //3rd subtask\n get_integ_bounds_inner(integ_bnd, m_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0], integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=2;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner); \n\n //4th subtask\n get_integ_bounds_inner(integ_bnd, mr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0], integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=3;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner); \n\n //5th subtask\n get_integ_bounds_inner(integ_bnd, mrr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0], integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=4;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n\n //push outer integtand work on outer stack\n work.subtasks_left=5;\n push_stack(stack, &work); \n\n\n/*\n int elemsinner=work.stack_inner->el_count;\n int elout=stack->el_count;\n\n\n work_gkq* top=(work_gkq*) stack->elements +(stack->el_count-1); //get top element\n \n int inner2=0;\n inner2=top->stack_inner->el_count;\n*/\n // printf(\"elemsinner:%d,ou:%d,in2:%d\\n\",elemsinner,elout, inner2);\n \n\n // int in2= top->stack_inner->el_count;\n\n\n result=gkq_adapt_double(stack);//,stack);\n\n\n\n // result=gkq_adapt_serial(f,a,b,fa,fb,toler,I_13, p); \n // gsl_integration_workspace_free(gsinner2);\n \n\n // free(stack->elements);\n\n return result;\n}\n\n\n\ndouble gkq_single(double (*f)(double, struct my_f_params*), double a, double b, \n double TOL, struct my_f_params* p,stack_t stack)\n{\n double result=0.0;\n// ********************************************* \n\n double m=0.5*(a+b);\n double h=0.5*(b-a);\n int i;\n\n\n double y[13];\n double fa=y[0]=f(a,p);\n double fb=y[12]=f(b,p);\n \n for(i=1;i<12;i++) //hier müssen direkt 13 integrale berechnet werden!!!\n y[i]=f(m+xgkq[i]*h,p); //auch das sollte parallel erfolgen (pragma parfor?)\n\n\n double I_4= (h/6.0)*(y[0]+y[12]+5.0*(y[4]+y[8])); // 4-point gauss-lobatto\n double I_7= (h/1470.0)*(77.0*(y[0]+y[12])+432.0*(y[2]+y[10])+ // 7-point kronrod\n 625.0*(y[4]+y[8])+672.0*y[6]);\n\n double I_13= h*(0.0158271919734802*(y[0]+y[12])+0.0942738402188500*(y[1]+y[11])+0.155071987336585*(y[2]+y[10])+\n 0.188821573960182*(y[3]+y[9])+0.199773405226859*(y[4]+y[8])+0.224926465333340*(y[5]+y[7])+\n 0.242611071901408*y[6]); //13-point Kronrod\n\n \n double Err1=fabs(I_7-I_13);\n double Err2=fabs(I_4-I_13);\n\n double r=(Err2 != 0.0) ? Err1/Err2 : 1.0;\n double toler=(r > 0.0 && r < 1.0) ? TOL/r : TOL; \n\n if(I_13 == 0)\n I_13=b-a;\n I_13=fabs(I_13);\n\n \n \n //Prepare work and push onto stack\n work_gkq work;\n work.a = a;\n work.b = b;\n work.toler = toler;\n work.I_13=I_13;\n work.fa=fa;\n work.fb=fb;\n work.p=p;\n work.a=a;\n work.f=f;\n\n\n push_stack(stack, &work); \n result=gkq_adapt_single(stack);//,stack);\n\n return result;\n}\n\ndouble gkq_adapt_serial(double (*f)(double, struct my_f_params*), double a, double b, \n double fa,double fb, double toler,double I_13, struct my_f_params* p)\n{\n double m = (a+b)/2;\n double h = (b-a)/2;\n double mll=m-alpha*h;\n double ml=m-beta*h;\n double mr=m+beta*h;\n double mrr=m+alpha*h;\n\n double fmll=f(mll,p);\n double fml=f(ml,p);\n double fm=f(m,p);\n double fmr=f(mr,p);\n double fmrr=f(mrr,p);\n double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula.\n double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm);\n \n\n if (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr) \n {\n if ((mll <= a || b <= mrr) && !terminate_serial) //Error\n {\n // out_of_tolerance=true; // Interval contains no more machine numbers\n printf(\"OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e\\n\", mll,b,b,mrr);\n terminate_serial=1; \n }\n\n// printf(\"me ok:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f\\n\", omp_get_thread_num(), a,b,toler,I_4,I_7); \n\n return I_7;\n }\n else\n {\n\n // printf(\"me NOOOO:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f\\n\", omp_get_thread_num(), a,b,toler,I_4,I_7);\n\n return gkq_adapt_serial(f, a,mll,fa,fmll,toler,I_13,p) +\n gkq_adapt_serial(f, mll,ml,fmll,fml,toler,I_13,p) +\n gkq_adapt_serial(f, ml,m,fml,fm,toler,I_13,p) +\n gkq_adapt_serial(f, m,mr,fm,fmr,toler,I_13,p) +\n gkq_adapt_serial(f, mr,mrr,fmr,fmrr,toler,I_13,p) +\n gkq_adapt_serial(f, mrr,b,fmrr,fb,toler,I_13,p);\n }\n\n\n}\n\n\ndouble gkq_adapt_single(stack_t stack)\n{\n work_gkq work;\n // work.iter=0;\n int ready, idle, busy;\n double integral_result = 0.0; \n\n busy = 0;\n terminate_gkq=0;\n\n#pragma omp parallel default(none) \\\n shared(stack, integral_result,busy) \\\n private(work, idle, ready)\n { \n// printf(\"me:%d, err:%d\\n\",omp_get_thread_num(),simpson_error); \n\n ready = 0;\n idle = 1;\n\n while(!ready) // && !terminate_gkq)// && !simpson_error) //<-- so NICHT!\n {\n #pragma omp critical (stack)\n {\n if (!empty_stack(stack))\n {\n /* we have new work */ \n pop_stack(stack, &work);\n if (idle)\n {\n /* say others i'm busy */\n busy += 1;\n idle = 0;\n }\n }\n else\n {\n /* no new work on stack */\n if (!idle){\n busy -= 1;\n idle = 1;\n }\n\n /* nobody has anything to do; let us leave the loop */\n if (busy == 0)\n {\n ready = 1; \n }\n }\n } /* end critical(stack) */\n\n if (idle)\n continue; //if ready==1 --> leave loop\n// double I_prev=work.I_prev;\n\ndouble (*f)(double, struct my_f_params*)=work.f; \n\n double a = work.a;\n double b = work.b; \n double toler = work.toler; \n double I_13=work.I_13; \n double fa=work.fa;\n double fb=work.fb;\n // int iter=work.iter;\n // double *y= work.y; // brauch ich nicht!\n struct my_f_params * p = work.p;\n \n double m = (a+b)/2;\n double h = (b -a)/2;\n double mll=m-alpha*h;\n double ml=m-beta*h;\n double mr=m+beta*h;\n double mrr=m+alpha*h;\n\n double fmll=f(mll,p);\n double fml=f(ml,p);\n double fm=f(m,p);\n double fmr=f(mr,p);\n double fmrr=f(mrr,p);\n double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula.\n double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm);\n \n// if(myid==1)\n// printf(\"I_7:%.4e, I_13:%.4e,I_4:%.4e, minus:%.4e, to:%.4e\\n\",I_7,I_13,I_4,I_7-I_4, toler*I_13);\n// int maxiter=50; //max. subdivisions\n// double abstol=1e-30;\n// work.I_prev=I_7; // für abstolcheck in nächster recursion\n\n if (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr) // || iter > maxiter || fabs(I_7-I_prev) < abstol ) \n {\n if ((mll <= a || b <= mrr)) //Error\n {\n // out_of_tolerance=true; // Interval contains no more machine numbers\n // printf(\"OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e,I_7-I_4:%.4e, tol:%.4e,I_13:%.4e\\n\", \n // mll,b,b,mrr,I_7-I_4, toler*I_13,I_13);\n\n }\n #pragma omp critical (integral_result) \n {\n integral_result += I_7; //Terminate recursion. \n } \n }\n else //subdivide interval and push new work on stack\n {\n #pragma omp critical (stack)\n { \n // work.iter=iter+1;\n\n work.a=a;\n work.b=mll;\n work.fa=fa;\n work.fb=fmll;\n push_stack(stack, &work); \n\n work.a=mll;\n work.b=ml;\n work.fa=fmll;\n work.fb=fml;\n push_stack(stack, &work); \n\n work.a=ml;\n work.b=m;\n work.fa=fml;\n work.fb=fm;\n push_stack(stack, &work); \n\n work.a=m;\n work.b=mr;\n work.fa=fm;\n work.fb=fmr;\n push_stack(stack, &work); \n\n work.a=mr;\n work.b=mrr;\n work.fa=fmr;\n work.fb=fmrr;\n push_stack(stack, &work); \n\n work.a=mrr;\n work.b=b;\n work.fa=fmrr;\n work.fb=fb;\n\n push_stack(stack, &work); \n\n } // pragma critical stack\n } // else ..non-acceptable error\n } // while\n } /* end omp parallel */\n return integral_result; \n}\n\ndouble gkq_adapt_double(stack_t stack)\n{\n work_gkq work;\n work_gkq* pwork_outer;\n\n int ready, idle, busy;\n double integral_result = 0.0; \n busy = 0;\n int myid;\n int elcnt; //nr of outer task elements on stack\n\n#pragma omp parallel default(none) \\\n shared(stack, integral_result,busy,iter,elcnt) \\\n private(work, idle, ready,myid,pwork_outer)\n { \n\n myid=omp_get_thread_num();\n\n ready = 0;\n idle = 1;\n\n while(!ready) // && !terminate_gkq)// && !simpson_error) //<-- so NICHT!\n {\n\n\n// printf(\"\\n NEXT, curapprox:%.4e\\n\",integral_result);\n #pragma omp critical (stack)\n {\n //pointer to outer work element\n //work_gkq* pwork=(work_gkq*) stack->elements + stack->el_count*stack->el_size;\n\n elcnt=stack->el_count;\n \n\n// if(elcnt>1)\n// getchar();\n \n stack_t stack_inner;\n if(elcnt>0)\n {\n pwork_outer=(work_gkq*) stack->elements +(elcnt-1); //get top element\n\n //IST WOHL SUBOPTIMAL\n while(pwork_outer->task_nr > 0 && pwork_outer->subtasks_left==0) //this task is complete, goto next outer task\n {\n printf(\"myid:%d, outer task nr:%d, complete:subs:%d, decrement\\n\",myid,pwork_outer->task_nr,pwork_outer->subtasks_left);\n pwork_outer--;\n }\n stack_inner=pwork_outer->stack_inner;\n }\n else\n {\n stack_inner=NULL;\n pwork_outer=NULL;\n }\n\n printf(\"myid:%d,elcnt:%d,sinner:%p,pwout:%p\\n\",myid,elcnt,stack_inner,pwork_outer); \n\n { //stackinner gehört zu work, und work ist private! \n if(!empty_stack(stack_inner))\n { \n printf(\"myid:%d,iter:%d, inner stack not empty,pop..\\n\",myid,iter); \n pop_stack(stack_inner, &work);\n//if letztes inner-work elem, blockiere outer work elem bis ich das integral hab\n\n iter++;\n\n if (idle)\n { \n busy += 1;\n idle = 0;\n } \n }\n else //inner stack is empty, pop from outer\n {\n printf(\"myid:%d,iter:%d, inner stack is empty?\\n\",myid,iter);\n if (!empty_stack(stack)) //work elem ist blockiert solange inner integs nicht vollständig\n { \n // printf(\"myid:%d,iter:%d, inner stack empty. work on outer with cnt=%d\\n\",myid,iter,pwork_outer->subtasks_left);\n if(pwork_outer->subtasks_left==0)\n {\n printf(\"myid:%d,iter:%d, outer stack not empty\\n\",myid,iter);\n pop_stack(stack, &work);\n iter++;\n if (idle)\n { \n busy += 1;\n idle = 0;\n } \n }\n else\n {\n printf(\"myid:%d,iter:%d, inner integs not complete:%d\\n\",myid,iter,pwork_outer->subtasks_left);\n if (!idle)\n {\n busy -= 1;\n idle = 1;\n }\n\n\n }\n }\n else //auch outer stack ist leer\n { \n printf(\"myid:%d,iter:%d, outer stack empty too\\n\",myid,iter); \n if (!idle)\n {\n busy -= 1;\n idle = 1;\n }\n if (busy == 0)\n {\n ready = 1; \n }\n }\n } \n } // critical inner stack\n } //critical outer stack\n\n\n if (idle)\n {\n printf(\"myid:%d,iter:%d, noth8ing to do\\n\",myid,iter);\n continue; //if ready==1 --> leave loop\n }\n\n\n //work on inner tasks first, if available\n if(work.is_parent==0)\n {\n printf(\"myid:%d,iter:%d,tasknr:%d,innertask:%d, left subs:%d\\n\",\n myid,iter,work.task_nr,work.subtask_nr,pwork_outer->subtasks_left); //subtasks nr nicht immer aktuell!\n\n// getchar();\n\n double (*f)(double, struct my_f_params*) = work.f;\n double a = work.a;\n double b = work.b; \n double toler = work.toler; \n double I_13=work.I_13; \n double fa=work.fa;\n double fb=work.fb;\n // double *y= work.y; // brauch ich nicht!\n struct my_f_params * p = work.p;\n \n double m = (a+b)/2;\n double h = (b -a)/2;\n double mll=m-alpha*h;\n double ml=m-beta*h;\n double mr=m+beta*h;\n double mrr=m+alpha*h;\n\n double fmll=f(mll,p);\n double fml=f(ml,p);\n double fm=f(m,p);\n double fmr=f(mr,p);\n double fmrr=f(mrr,p);\n double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula.\n double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm);\n \n// printf(\"myid:%d,iter:%d non parent checkpoint 1 passed\\n\",myid,iter);\n\n if (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr) \n {\n if ((mll <= a || b <= mrr))// && !terminate_gkq) //Error\n { \n printf(\"OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e\\n\", mll,a,b,mrr);\n }\n \n// printf(\"myid:%d,iter:%d non parent checkpoint 2.1 passed\\n\",myid,iter);\n\n int tasknr=work.subtask_nr;\n\n printf(\"myid:%d,iter:%d, winner error acceptable: I_7:%.4e, I_4:%.4e, I_13:%.4e,toler*I_13:%.4e,toler:%.4e\\n\",\n myid,iter,I_7,I_4, I_13,toler*I_13,toler);\n\n\n #pragma omp critical (innerinteg) // workers greifen auf selbes array zu.nur an anderer Stelle..evtl. besser 6 versch.doubles statt array?\n {\n double *inner_integrals=pwork_outer->inner_integrals;\n inner_integrals[tasknr]+=I_7;\n pwork_outer->subtasks_left=pwork_outer->subtasks_left-1; //hier sollte subtasks_left aktuell sein\n\n printf(\"myid:%d,iter:%d, inner_integral[%d]:%.4e added:%.4e,subtask left:%d\\n\",\n myid,iter,tasknr,inner_integrals[tasknr],I_7,pwork_outer->subtasks_left);\n } \n }\n else //subdivide interval and push new work on stack\n {\n \n stack_t stack_inner; \n #pragma omp critical //(stack) //(stack_inner)\n { \n stack_inner = pwork_outer->stack_inner;\n pwork_outer->subtasks_left=pwork_outer->subtasks_left-1;//weil dieser stack durch 6 andere ersetzt wird\n\n\n work.task_nr=pwork_outer->task_nr; //inner task soll auch wissen wer sein outer task is (bisher nur für debug)\n //subtasknr bleibt dieselbe (bezogen auf parent task)\n work.a=a;\n work.b=mll;\n work.fa=fa;\n work.fb=fmll;\n \n push_stack(stack_inner, &work); \n\n work.a=mll;\n work.b=ml;\n work.fa=fmll;\n work.fb=fml;\n \n push_stack(stack_inner, &work); \n\n work.a=ml;\n work.b=m;\n work.fa=fml;\n work.fb=fm;\n \n push_stack(stack_inner, &work); \n\n work.a=m;\n work.b=mr;\n work.fa=fm;\n work.fb=fmr;\n \n push_stack(stack_inner, &work); \n\n work.a=mr;\n work.b=mrr;\n work.fa=fmr;\n work.fb=fmrr;\n \n push_stack(stack_inner, &work); \n\n work.a=mrr;\n work.b=b;\n work.fa=fmrr;\n work.fb=fb;\n \n push_stack(stack_inner, &work); \n\n pwork_outer->subtasks_left=pwork_outer->subtasks_left+6;\n\n printf(\"myid:%d,iter:%d, inner_integral approx not accurate..subdivided: I_4:%f,I_7:%f,I_13:%f,left subs:%d\\n\",\n myid,iter,I_4,I_7,I_13,pwork_outer->subtasks_left);\n\n } // pragma critical stack_inner\n } // else ..non-acceptable error\n }// !isparent\n else //parent task without any inner tasks\n {\n\nprintf(\"myid:%d,iter:%d, work is parent,subs left:%d\\n\",myid,iter,work.subtasks_left);\n\n // stack_t stack_inner = work.stack_inner; //brauch ich hier nicht\n // free(stack_inner->elements);\n // free(stack_inner);\n\n double (*f)(double, struct my_f_params*) = work.f;\n double a = work.a;\n double b = work.b; \n double toler = work.toler; \n double I_13=work.I_13; \n double fa=work.fa;\n double fb=work.fb;\n // double *y= work.y; // brauch ich nicht!\n struct my_f_params * p = work.p;\n \n double m = (a+b)/2;\n double h = (b -a)/2;\n double mll=m-alpha*h;\n double ml=m-beta*h;\n double mr=m+beta*h;\n double mrr=m+alpha*h;\n\n //the inner intergrals are pre-calculated and saved in an array\n //the function only calculates a prefactor...\n double fmll=f(mll,p)*work.inner_integrals[0];\n double fml= f(ml,p)*work.inner_integrals[1];\n double fm= f(m,p)*work.inner_integrals[2];\n double fmr= f(mr,p)*work.inner_integrals[3];\n double fmrr= f(mrr,p)*work.inner_integrals[4];\n\n double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula.\n double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm); \n\n if (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr) \n {\n if ((mll <= a || b <= mrr))// && !terminate_gkq) //Error\n {\n // out_of_tolerance=true; // Interval contains no more machine numbers\n printf(\"outer task OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e\\n\", mll,b,b,mrr);\n }\n //#pragma omp critical(integal_result)\n {\n #pragma omp atomic\n integral_result += I_7;\n printf(\"myid:%d,iter:%d, I7 added, integs: 0=%f,1=%f,2=%f,3=%f,4=%f\\n\", myid,iter, \n work.inner_integrals[0],work.inner_integrals[1],work.inner_integrals[2],\n work.inner_integrals[3],work.inner_integrals[4]);\n }\n }\n else //subdivide interval and push new work on stack\n {\n\nprintf(\"myid:%d,iter:%d, iouter_integral approx not accurate: I_7=%.4e,I_4=%.4e,I_13=%.4e, toler*I_13:%.4e\\n\"\n \"integs: 0=%f,1=%f,2=%f,3=%f,4=%f..subdivide\\n\",\n myid,iter,I_7,I_4,I_13,I_13*toler,work.inner_integrals[0],work.inner_integrals[1],work.inner_integrals[2],\n work.inner_integrals[3],work.inner_integrals[4] );\n\n stack_t stack_inner = work.stack_inner;\n #pragma omp critical (stack) \n { \n //create sub-stack for inner-integrals\n \n work.subtasks_left=5; //for all new outer work elements\n\n create_stack(&stack_inner, sizeof(work_gkq)); \n work.is_parent=1;\n\n work_gkq winner; \n\n //outer task elem\n work.a=a;\n work.b=mll;\n work.fa=fa;\n work.fb=fmll; \n \n double m_inner= (work.a+work.b)/2;\n double h_inner= (work.a+work.b)/2;\n double mll_inner=(m_inner-alpha*h_inner);\n double ml_inner= (m_inner-beta*h_inner);\n double mr_inner= (m_inner+beta*h_inner);\n double mrr_inner=(m_inner+alpha*h_inner);\n\n //Jedes subinterval bekommt 5 inner tasks für die inneren integrale!\n\n int curcnt=stack->el_count;\n work.task_nr=curcnt; //weil ich bei 0 anfange zu zählen und push_stack gleich el_count incrementiert\n\n double integ_bnd[2]; \n\n //1st subtask\n get_integ_bounds_inner(integ_bnd, mll_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.task_nr=work.task_nr;\n winner.subtask_nr=0;\n push_stack(work.stack_inner,&winner);\n\n //2nd subtask\n get_integ_bounds_inner(integ_bnd, ml_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=1;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n\n //3rd subtask\n get_integ_bounds_inner(integ_bnd, m_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=2;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner); \n\n //4th subtask\n get_integ_bounds_inner(integ_bnd, mr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=3;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner); \n\n //5th subtask\n get_integ_bounds_inner(integ_bnd, mrr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=4;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n push_stack(stack, &work);\n\n\n // *************************\n // * 2nd subinterval\n // **************************\n work.a=mll;\n work.b=ml;\n work.fa=fmll;\n work.fb=fml;\n work.task_nr++;\n\n m_inner= (work.a+work.b)/2;\n h_inner= (work.a+work.b)/2;\n mll_inner=(m_inner-alpha*h_inner);\n ml_inner= (m_inner-beta*h_inner);\n mr_inner= (m_inner+beta*h_inner);\n mrr_inner=(m_inner+alpha*h_inner);\n\n\n //1st subtask\n get_integ_bounds_inner(integ_bnd, mll_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=0;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //2nd subtask\n get_integ_bounds_inner(integ_bnd, ml_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=1;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //3rd subtask\n get_integ_bounds_inner(integ_bnd, m_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=2;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //4th subtask\n get_integ_bounds_inner(integ_bnd, mr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=3;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //5th subtask\n get_integ_bounds_inner(integ_bnd, mrr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=4;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n\n // #pragma omp critical (stack)\n // {\n push_stack(stack, &work);\n // } \n\n // *************************\n // * 3rd subinterval\n // **************************\n work.a=ml;\n work.b=m;\n work.fa=fml;\n work.fb=fm;\n work.task_nr++;\n\n m_inner= (work.a+work.b)/2;\n h_inner= (work.a+work.b)/2;\n mll_inner=(m_inner-alpha*h_inner);\n ml_inner= (m_inner-beta*h_inner);\n mr_inner= (m_inner+beta*h_inner);\n mrr_inner=(m_inner+alpha*h_inner); \n\n //1st subtask\n get_integ_bounds_inner(integ_bnd, mll_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=0;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //2nd subtask\n get_integ_bounds_inner(integ_bnd, ml_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=1;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //3rd subtask\n get_integ_bounds_inner(integ_bnd, m_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=2;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //4th subtask\n get_integ_bounds_inner(integ_bnd, mr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=3;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //5th subtask\n get_integ_bounds_inner(integ_bnd, mrr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=4;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n\n // #pragma omp critical (stack)\n // {\n push_stack(stack, &work);\n // }\n \n\n\n\n // *************************\n // * 4th subinterval\n // **************************\n work.a=m;\n work.b=mr;\n work.fa=fm;\n work.fb=fmr;\n work.task_nr++;\n\n m_inner= (work.a+work.b)/2;\n h_inner= (work.a+work.b)/2;\n mll_inner=(m_inner-alpha*h_inner);\n ml_inner= (m_inner-beta*h_inner);\n mr_inner= (m_inner+beta*h_inner);\n mrr_inner=(m_inner+alpha*h_inner); \n\n //1st subtask\n get_integ_bounds_inner(integ_bnd, mll_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=0;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //2nd subtask\n get_integ_bounds_inner(integ_bnd, ml_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=1;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //3rd subtask\n get_integ_bounds_inner(integ_bnd, m_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=2;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //4th subtask\n get_integ_bounds_inner(integ_bnd, mr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=3;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //5th subtask\n get_integ_bounds_inner(integ_bnd, mrr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=4;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n\n // #pragma omp critical (stack)\n {\n push_stack(stack, &work);\n } \n\n // *************************\n // * 5th subinterval\n // **************************\n work.a=mr;\n work.b=mrr;\n work.fa=fmr;\n work.fb=fmrr;\n work.task_nr++;\n\n m_inner= (work.a+work.b)/2;\n h_inner= (work.a+work.b)/2;\n mll_inner=(m_inner-alpha*h_inner);\n ml_inner= (m_inner-beta*h_inner);\n mr_inner= (m_inner+beta*h_inner);\n mrr_inner=(m_inner+alpha*h_inner); \n\n //1st subtask\n get_integ_bounds_inner(integ_bnd, mll_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=0;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //2nd subtask\n get_integ_bounds_inner(integ_bnd, ml_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=1;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //3rd subtask\n get_integ_bounds_inner(integ_bnd, m_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=2;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //4th subtask\n get_integ_bounds_inner(integ_bnd, mr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=3;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //5th subtask\n get_integ_bounds_inner(integ_bnd, mrr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=4;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n\n // #pragma omp critical (stack)\n {\n push_stack(stack, &work);\n }\n\n // *************************\n // * 6th subinterval\n // **************************\n work.a=mrr;\n work.b=b;\n work.fa=fmrr;\n work.fb=fb;\n work.task_nr++;\n\n m_inner= (work.a+work.b)/2;\n h_inner= (work.a+work.b)/2;\n mll_inner=(m_inner-alpha*h_inner);\n ml_inner= (m_inner-beta*h_inner);\n mr_inner= (m_inner+beta*h_inner);\n mrr_inner=(m_inner+alpha*h_inner); \n\n //1st subtask\n get_integ_bounds_inner(integ_bnd, mll_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=0;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //2nd subtask\n get_integ_bounds_inner(integ_bnd, ml_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=1;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //3rd subtask\n get_integ_bounds_inner(integ_bnd, m_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=2;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //4th subtask\n get_integ_bounds_inner(integ_bnd, mr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=3;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n \n\n //5th subtask\n get_integ_bounds_inner(integ_bnd, mrr_inner, work.p); \n winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);\n winner.subtask_nr=4;\n winner.task_nr=work.task_nr;\n push_stack(work.stack_inner,&winner);\n\n // #pragma omp critical (stack)\n {\n push_stack(stack, &work);\n } \n\n printf(\"myid:%d,iter:%d, 6 subinvtervals with 5 subtasks each pushed to stack outer\\n\",myid,iter);\n\n\n } // pragma critical\n } // else ..non-acceptable error\n\n\n }\n\n\n } // while\n } /* end omp parallel */\n\n\n\n return integral_result; \n}\n\n\n\n\n\n\n\n\n\n//SIMPSON\n\n // *****************************************************************************************************************************************\n// double integral2(double (*f)(double, struct my_f_params*), stack_t stack)\n// {\n// work_t work;\n// int ready, idle, busy;\n// double integral_result = 0.0;\n\n// busy = 0;\n \n// #pragma omp parallel default(none) \\\n// shared(stack, integral_result,f,busy,simpson_error) \\\n// private(work, idle, ready)\n// {\n\n// // printf(\"me:%d, err:%d\\n\",omp_get_thread_num(),simpson_error); \n\n// ready = 0;\n// idle = 1;\n\n// while(!ready && !simpson_error) //<-- so NICHT!\n// {\n// #pragma omp critical (stack)\n// {\n// if (!empty_stack(stack))\n// {\n// /* we have new work */ \n// pop_stack(stack, &work);\n// if (idle)\n// {\n// /* say others i'm busy */\n// busy += 1;\n// idle = 0;\n// }\n// }\n// else{\n// /* no new work on stack */\n// if (!idle){\n// busy -= 1;\n// idle = 1;\n// }\n\n// /* nobody has anything to do; let us leave the loop */\n// if (busy == 0)\n// {\n// ready = 1; \n// }\n// }\n// } /* end critical(stack) */\n\n// if (idle)\n// continue; //if ready==1 --> leave loop\n\n// double b = work.b;\n// double a = work.a;\n// double tol = work.tol;\n// double S=work.S; // previous TOTAL integral\n// double fa=work.fa;\n// double fb=work.fb;\n// double fm=work.fm;\n// int rec=work.rec;\n\n// double h = (b - a)/2;\n// double mid = (a+b)/2;\n// double lm=(a+mid)/2;\n// double rm=(mid+b)/2; \n\n// double flm=f(lm,work.p);\n// double frm=f(rm,work.p);\n \n// double Sl=h/6*(fa+4*flm+fm);\n// double Sr=h/6*(fm+4*frm+fb);\n\n// double delta=Sl+Sr-S;\n\n// // serious numerical trouble: it won't converge\n// if ((tol/2 == tol) || fabs(a-lm) <= tol) // || tol < tolmax) \n// { \n// simpson_error = 1; \n// #pragma omp critical (integral_result) \n// integral_result = S; \n// }\n// //need something against spurious convergence\n// //for now: iter > 5 (c.f. numerical recipes)\n// if( work.iter > 5 && (rec <= 0 || fabs(delta) <= 15*tol)) //error acceptable\n// {\n// #pragma omp critical (integral_result)\n// integral_result += Sl+Sr+delta/15;\n// }\n// else // error not acceptable\n// { \n// //push new subintervals to stack\n// work.a = a;\n// work.b = mid;\n// work.tol = tol/2;\n// work.S = Sl;\n// work.fa=fa;\n// work.fb=fm;\n// work.fm=flm;\n// work.rec=rec-1;\n// work.iter=work.iter+1;\n\n// #pragma omp critical (stack)\n// {\n// //LEFT\n// push_stack(stack, &work); \n// //prepare RIGHT side and push to stack\n// work.a = mid;\n// work.b = b;\n// work.tol = tol/2;\n// work.S=Sr;\n// work.fa=fm;\n// work.fb=fb;\n// work.fm=frm;\n// work.rec=rec-1;\n// push_stack(stack, &work);\n\n// } \n// }\n// } /* while */\n// } /* end omp parallel */\n\n\n// return integral_result;\n// }", "meta": {"hexsha": "ff471e5ec64b45f7b10b410406dac0fe1f07dbbd", "size": 53468, "ext": "c", "lang": "C", "max_stars_repo_path": "simpson_omp.c", "max_stars_repo_name": "fmqeisfeld/IMD", "max_stars_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-30T08:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T07:49:51.000Z", "max_issues_repo_path": "simpson_omp.c", "max_issues_repo_name": "fmqeisfeld/IMD", "max_issues_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simpson_omp.c", "max_forks_repo_name": "fmqeisfeld/IMD", "max_forks_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4834663626, "max_line_length": 156, "alphanum_fraction": 0.5365078178, "num_tokens": 15410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4458589110125863}} {"text": "/* specfunc/bessel_Yn.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n#include \"bessel.h\"\n#include \"bessel_amp_phase.h\"\n#include \"bessel_olver.h\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n/* assumes n >= 1 */\nstatic int bessel_Yn_small_x(const int n, const double x, gsl_sf_result * result)\n{\n int k;\n double y = 0.25 * x * x;\n double ln_x_2 = log(0.5*x);\n gsl_sf_result ln_nm1_fact;\n double k_term;\n double term1, sum1, ln_pre1;\n double term2, sum2, pre2;\n\n gsl_sf_lnfact_e((unsigned int)(n-1), &ln_nm1_fact);\n\n ln_pre1 = -n*ln_x_2 + ln_nm1_fact.val;\n if(ln_pre1 > GSL_LOG_DBL_MAX - 3.0) GSL_ERROR (\"error\", GSL_EOVRFLW);\n\n sum1 = 1.0;\n k_term = 1.0;\n for(k=1; k<=n-1; k++) {\n k_term *= y/(k * (n-k));\n sum1 += k_term;\n }\n term1 = -exp(ln_pre1) * sum1 / M_PI;\n \n pre2 = -exp(n*ln_x_2) / M_PI;\n if(fabs(pre2) > 0.0) {\n const int KMAX = 20;\n gsl_sf_result psi_n;\n gsl_sf_result npk_fact;\n double yk = 1.0;\n double k_fact = 1.0;\n double psi_kp1 = -M_EULER;\n double psi_npkp1;\n gsl_sf_psi_int_e(n, &psi_n);\n gsl_sf_fact_e((unsigned int)n, &npk_fact);\n psi_npkp1 = psi_n.val + 1.0/n;\n sum2 = (psi_kp1 + psi_npkp1 - 2.0*ln_x_2)/npk_fact.val;\n for(k=1; kval = term1 + term2;\n result->err = GSL_DBL_EPSILON * (fabs(ln_pre1)*fabs(term1) + fabs(term2));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\n return GSL_SUCCESS;\n}\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\n\nint\ngsl_sf_bessel_Yn_e(int n, const double x, gsl_sf_result * result)\n{\n int sign = 1;\n\n if(n < 0) {\n /* reduce to case n >= 0 */\n n = -n;\n if(GSL_IS_ODD(n)) sign = -1;\n }\n\n /* CHECK_POINTER(result) */\n\n if(n == 0) {\n int status = gsl_sf_bessel_Y0_e(x, result);\n result->val *= sign;\n return status;\n }\n else if(n == 1) {\n int status = gsl_sf_bessel_Y1_e(x, result);\n result->val *= sign;\n return status;\n }\n else {\n if(x <= 0.0) {\n DOMAIN_ERROR(result);\n }\n if(x < 5.0) {\n int status = bessel_Yn_small_x(n, x, result);\n result->val *= sign;\n return status;\n }\n else if(GSL_ROOT3_DBL_EPSILON * x > (n*n + 1.0)) {\n int status = gsl_sf_bessel_Ynu_asympx_e((double)n, x, result);\n result->val *= sign;\n return status;\n }\n else if(n > 50) {\n int status = gsl_sf_bessel_Ynu_asymp_Olver_e((double)n, x, result);\n result->val *= sign;\n return status;\n }\n else {\n double two_over_x = 2.0/x;\n gsl_sf_result r_by;\n gsl_sf_result r_bym;\n int stat_1 = gsl_sf_bessel_Y1_e(x, &r_by);\n int stat_0 = gsl_sf_bessel_Y0_e(x, &r_bym);\n double bym = r_bym.val;\n double by = r_by.val;\n double byp;\n int j;\n\n for(j=1; jval = sign * by;\n result->err = fabs(result->val) * (fabs(r_by.err/r_by.val) + fabs(r_bym.err/r_bym.val));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\n return GSL_ERROR_SELECT_2(stat_1, stat_0);\n }\n }\n}\n\n\nint\ngsl_sf_bessel_Yn_array(const int nmin, const int nmax, const double x, double * result_array)\n{\n /* CHECK_POINTER(result_array) */\n\n if(nmin < 0 || nmax < nmin || x <= 0.0) {\n int j;\n for(j=0; j<=nmax-nmin; j++) result_array[j] = 0.0;\n GSL_ERROR (\"error\", GSL_EDOM);\n }\n else {\n gsl_sf_result r_Ynm1;\n gsl_sf_result r_Yn;\n int stat_nm1 = gsl_sf_bessel_Yn_e(nmin, x, &r_Ynm1);\n int stat_n = gsl_sf_bessel_Yn_e(nmin+1, x, &r_Yn);\n double Ynp1;\n double Yn = r_Yn.val;\n double Ynm1 = r_Ynm1.val;\n int n;\n\n int stat = GSL_ERROR_SELECT_2(stat_nm1, stat_n);\n\n if(stat == GSL_SUCCESS) {\n for(n=nmin+1; n<=nmax+1; n++) {\n result_array[n-nmin-1] = Ynm1;\n Ynp1 = -Ynm1 + 2.0*n/x * Yn;\n Ynm1 = Yn;\n Yn = Ynp1;\n }\n }\n else {\n for(n=nmin; n<=nmax; n++) {\n result_array[n-nmin] = 0.0;\n }\n }\n\n return stat;\n }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_Yn(const int n, const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_Yn_e(n, x, &result));\n}\n\n", "meta": {"hexsha": "3dc1a99b0d4491d7381f67a8e17bfad88f693d33", "size": 5500, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/bessel_Yn.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_Yn.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_Yn.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 25.2293577982, "max_line_length": 95, "alphanum_fraction": 0.5925454545, "num_tokens": 1907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.44564921917288325}} {"text": "/* movstat/movmad.c\n * \n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\ngsl_movstat_mad()\n Apply a moving MAD to an input vector (with scale factor to make an\nunbiased estimate of sigma)\n\nInputs: endtype - how to handle end points\n x - input vector, size n\n xmedian - (output) vector of median values of x, size n\n xmedian_i = median of window centered on x_i\n xmad - (output) vector of estimated standard deviations of x, size n\n xmad_i = MAD of i-th window: 1.4826 * median(|x_i - xmedian_i|)\n w - workspace\n*/\n\nint\ngsl_movstat_mad(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * xmedian, gsl_vector * xmad,\n gsl_movstat_workspace * w)\n{\n if (x->size != xmedian->size)\n {\n GSL_ERROR(\"x and xmedian vectors must have same length\", GSL_EBADLEN);\n }\n else if (x->size != xmad->size)\n {\n GSL_ERROR(\"x and xmad vectors must have same length\", GSL_EBADLEN);\n }\n else\n {\n double scale = 1.482602218505602;\n int status = gsl_movstat_apply_accum(endtype, x, gsl_movstat_accum_mad, &scale, xmedian, xmad, w);\n return status;\n }\n}\n\n/*\ngsl_movstat_mad0()\n Apply a moving MAD to an input vector (without scale factor to make an\nunbiased estimate of sigma)\n\nInputs: endtype - how to handle end points\n x - input vector, size n\n xmedian - (output) vector of median values of x, size n\n xmedian_i = median of window centered on x_i\n xmad - (output) vector of estimated standard deviations of x, size n\n xmad_i = MAD of i-th window: median(|x_i - xmedian_i|)\n w - workspace\n*/\n\nint\ngsl_movstat_mad0(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * xmedian, gsl_vector * xmad,\n gsl_movstat_workspace * w)\n{\n if (x->size != xmedian->size)\n {\n GSL_ERROR(\"x and xmedian vectors must have same length\", GSL_EBADLEN);\n }\n else if (x->size != xmad->size)\n {\n GSL_ERROR(\"x and xmad vectors must have same length\", GSL_EBADLEN);\n }\n else\n {\n double scale = 1.0;\n int status = gsl_movstat_apply_accum(endtype, x, gsl_movstat_accum_mad, &scale, xmedian, xmad, w);\n return status;\n }\n}\n", "meta": {"hexsha": "d1b7233eff64cc349e5551eb9ec9635b043ffd63", "size": 3225, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/movstat/movmad.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/movstat/movmad.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/movstat/movmad.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 33.2474226804, "max_line_length": 112, "alphanum_fraction": 0.6663565891, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.44532234194113923}} {"text": "/*\n * emu.c\n * Edited and renamed to fr_emu.c for cosmo_pmc by Martin Kilbinger 2013.\n * \n *\n * Created by Earl Lawrence on 9/17/09.\n * Update 10/9/2012\n *\n * This program was prepared by Los Alamos National Security, LLC at Los Alamos National Laboratory (LANL) \n * under contract No. DE-AC52-06NA25396 with the U.S. Department of Energy (DOE). All rights in the program \n * are reserved by the DOE and Los Alamos National Security, LLC. Permission is granted to the public to \n * copy and use this software without charge, provided that this Notice and any statement of authorship are \n * reproduced on all copies. Neither the U.S. Government nor LANS makes any warranty, express or implied, \n * or assumes any liability or responsibility for the use of this software. \n *\n * \n */\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"coyote.h\"\n#include \"fr_constants.h\"\n\n/* Copy parameters to emulator input array */\nvoid fill_xstar6_wo_z(double omega_m, double omega_b, double n_spec, double sigma_8, double w0_de, double h_100,\n double xstar[])\n{\n /* Orders reversed: (omega_b <-> omega_m), (w0_de <-> sigma_8), compared to v1 */\n xstar[0] = omega_b;\n xstar[1] = omega_m;\n xstar[2] = n_spec;\n xstar[3] = h_100 * 100;\n xstar[4] = w0_de;\n xstar[5] = sigma_8;\n}\n\n\n/* ============================================================ *\n * Returns the Coyote non-linear power spectrum. k is in units *\n * of h/Mpc, h_100 is now an independent parameter (Coyote v2). *\n * It is also used to transform it to [1/Mpc] as *\n * needed by the Coyote emulator. *\n * Six parameters, for coyote13.\t\t\t\t*\n * ============================================================ */\ndouble P_NL_coyote6(double omega_m, double omega_b, double n_spec, double sigma_8, double w0_de,\n\t\t double h_100, double a, double k, double **ystar_allz, error **err)\n{\n double xstar[p], ystar[2*fr_nsim], val, k_invMpc;\n int ihi, ilo, i;\n\n /* Copy cosmological parameters */\n fill_xstar6_wo_z(omega_m, omega_b, n_spec, sigma_8, w0_de, h_100, xstar);\n\n /* Redshift */\n xstar[p] = 1.0/a - 1.0;\n\n /* Input k is [h/Mpc], Coyote interpolates on k_invMpc in [1/Mpc] */\n k_invMpc = k * h_100;\n\n /* Check k-range */\n testErrorRetVA(k_invMpc < fr_ksim[0] || k_invMpc > fr_ksim[fr_nsim-1], coyote_range,\n \"Fourier mode k=%g 1/Mpc out of range [%g;%g]\",\n *err, __LINE__, -1.0, k_invMpc, fr_ksim[0], fr_ksim[fr_nsim-1]);\n\n if (*ystar_allz == NULL) {\n *ystar_allz = malloc_err(sizeof(double) * fr_rs * fr_nsim, err);\n forwardError(*err, __LINE__, -1.0);\n\n /* The actual emulator, filling the array in (k, z) */\n //testErrorRet(ystar_allz == NULL, io_null, \"Coyote13: array for (k,z) 'ystar_allz' not initialised\",\n //\t *err, __LINE__,);\n fr_fill_ystar_allz(*ystar_allz, xstar, err);\n forwardError(*err, __LINE__, -1.0);\n }\n\n /* ystar: first half = k, second half = P(k) */\n fr_emu(xstar, ystar, *ystar_allz, err);\n forwardError(*err, __LINE__, -1.0);\n\n /* Looking for right k-index with bisection */\n ilo = 0;\n ihi = fr_nsim-1;\n while (ihi - ilo > 1) {\n i = (ihi + ilo) >> 1;\n if (ystar[i] > k_invMpc) ihi = i;\n else ilo = i;\n }\n testErrorRetVA(ihi == ilo, math_wrongValue, \"Bisection failed, both indices equal (%d)\", *err, __LINE__, -1.0, ihi);\n\n /* Linear interpolation */\n val = (k_invMpc - ystar[ilo]) / (ystar[ihi] - ystar[ilo]) * (ystar[fr_nsim + ihi]\n - ystar[fr_nsim + ilo]) + ystar[fr_nsim + ilo];\n\n /* Coyote P(k) [Mpc^3] -> output P(k) [(Mpc/h)^3] */\n val *= h_100 * h_100 * h_100;\n \n return val;\n}\n\n\nvoid fr_check_range(const double *xstar, error **err)\n{\n int i;\n\n for(i=0; i fr_xmin[i]+fr_xrange[i]), coyote_range,\n\t\t \"Coyote FrankenEmu parameter #%d (%g) out of range [%g; %g]\",\n\t\t *err, __LINE__,, i, xstar[i], fr_xmin[i], fr_xmin[i] + fr_xrange[i]);\n } // for(i=0; i 4), coyote_range,\n\t\t \"Redshift %g out of range [%g;%g]\", *err, __LINE__,, xstar[p], 0.0, 4.0);\n}\n\n/* ============================================================ *\n * The actual emulation. Fills the array ystar_allz for (k, z). *\n * Cosmological parameters, placeholder for the output, type of *\n * output.\n * xstar[p] = redshift is not used here, only the p=6 cosmo. *\n * parameters.\t\t\t\t\t\t\t*\n * ============================================================ */\nvoid fr_fill_ystar_allz(double *ystar_allz, const double *xstar, error **err)\n{\n const double sd = 0.16002;\n int i, j, k;\n double xstarstd[p], wstar[peta], Sigmastar[peta][m], ystaremu[neta];\n double logc;\n\n // Interpolation stuff for k\n gsl_spline *lininterp_k = gsl_spline_alloc(gsl_interp_linear, neta/rs);\n gsl_interp_accel *accel = gsl_interp_accel_alloc();\n\n\n //fprintf(stderr, \"MKDEBUG: Filling ystar_allz for (%g, %g, %g, %g, %g, %g)\\n\",\n //\t xstar[0], xstar[1], xstar[2], xstar[3], xstar[4], xstar[5]);\n\n // Standardize the inputs\n for(i=0; i\n#include \n#include \nstruct params {\n double r, mdot, n, C1, C2;\n};\ndouble rfunc(double T, void *params)\n{\n struct params *p = (struct params *) params;\n //double r = p->r;\n double r = MY_MAX(2.5, p->r); // Solution breaks inside event horizon\n double mdot = p->mdot;\n double n = p->n;\n double C1 = p->C1;\n double C2 = p->C2;\n\n double resid = (pow(1. + (1. + n)*T,2)*(1. - 2.*mdot/r + pow(C1,2)/\n (pow(r,4)*pow(T,2*n))) - C2);\n\n //printf(\"r = %e T = %e resid = %e\\n\", r, T, resid);\n return resid;\n //return (pow(1. + (1. + n)*T,2)*(1. - 2.*mdot/r + pow(C1,2)/\n // (pow(r,4)*pow(T,2*n))) - C2);\n}\n\ndouble C1, C2, T_bondi[N1+2*NG][N2+2*NG], n;\n\n// Adapted from M. Chandra\ndouble get_Tfunc(double T, double r)\n{\n return pow(1.+(1.+n)*T,2.)*(1.-2./r+pow(C1/r/r/pow(T,n),2.))-C2;\n}\n\ndouble get_T(double r)\n{\n double rtol = 1.e-12;\n double ftol = 1.e-14;\n double Tmin = 0.6*(sqrt(C2) - 1.)/(n + 1);\n double Tmax = pow(C1*sqrt(2./r/r/r),1./n);\n double f0, f1, fh;\n double T0, T1, Th;\n T0 = 0.6*Tmin;\n f0 = get_Tfunc(T0, r);\n T1 = Tmax;\n f1 = get_Tfunc(T1, r);\n\n if (f0*f1 > 0.) {\n printf(\"Failed solving for T at r = %e C1 = %e C2 = %e\\n\", r, C1, C2);\n exit(-1);\n }\n\n Th = (f1*T0 - f0*T1)/(f1 - f0);\n fh = get_Tfunc(Th, r);\n double epsT = rtol*(Tmin + Tmax);\n while (fabs(Th - T0) > epsT && fabs(Th - T1) > epsT && fabs(fh) > ftol) {\n if (fh*f0 < 0.) {\n T0 = Th;\n f0 = fh;\n } else {\n T1 = Th;\n f1 = fh;\n }\n\n Th = (f1*T0 - f0*T1)/(f1 - f0);\n fh = get_Tfunc(Th, r);\n }\n\n return Th;\n}\n\nvoid bl_to_ks(double X[NDIM], double ucon_bl[NDIM], double ucon_ks[NDIM])\n{\n double r, th;\n bl_coord(X, &r, &th);\n\n double trans[NDIM][NDIM];\n DLOOP2 trans[mu][nu] = 0.;\n DLOOP1 trans[mu][mu] = 1.;\n trans[0][1] = 2.*r/(r*r - 2.*r + a*a);\n trans[3][1] = a/(r*r - 2.*r + a*a);\n\n DLOOP1 ucon_ks[mu] = 0.;\n DLOOP2 ucon_ks[mu] += trans[mu][nu]*ucon_bl[nu];\n}\n\nvoid fourvel_to_prim(double ucon[NDIM], double prim[NVAR],\n struct of_geom *geom)\n{\n double alpha, beta[NDIM], gamma;\n alpha = 1.0/sqrt(-geom->gcon[0][0]);\n beta[1] = alpha*alpha*geom->gcon[0][1];\n beta[2] = alpha*alpha*geom->gcon[0][2];\n beta[3] = alpha*alpha*geom->gcon[0][3];\n gamma = ucon[0]*alpha;\n\n prim[U1] = ucon[1] + beta[1]*gamma/alpha;\n prim[U2] = ucon[2] + beta[2]*gamma/alpha;\n prim[U3] = ucon[3] + beta[3]*gamma/alpha;\n}\n\nvoid set_ut(double ucon[NDIM], struct of_geom *geom)\n{\n double AA, BB, CC;\n\n AA = geom->gcov[0][0];\n BB = 2.*(geom->gcov[0][1]*ucon[1] +\n geom->gcov[0][2]*ucon[2] +\n geom->gcov[0][3]*ucon[3]);\n CC = 1. + geom->gcov[1][1]*ucon[1]*ucon[1] +\n geom->gcov[2][2]*ucon[2]*ucon[2] +\n geom->gcov[3][3]*ucon[3]*ucon[3] +\n 2. *(geom->gcov[1][2]*ucon[1]*ucon[2] +\n geom->gcov[1][3]*ucon[1]*ucon[3] +\n geom->gcov[2][3]*ucon[2]*ucon[3]);\n\n double discr = BB*BB - 4.*AA*CC;\n ucon[0] = (-BB - sqrt(discr))/(2.*AA);\n}\n\nvoid get_prim_bondi(int i, int j, int k, double P[NVAR])\n{\n double r, th, X[NDIM];\n coord(i, j, k, CENT, X);\n bl_coord(X, &r, &th);\n\n while (r < Reh) {\n i++;\n coord(i, j, k, CENT, X);\n bl_coord(X, &r, &th);\n }\n\n double T = T_bondi[i][j];\n double ur = -C1/(pow(T,n)*pow(r,2));\n double rho = pow(T,n);\n double u = rho*T/(gam - 1.);\n double ucon_bl[NDIM], ucon_ks[NDIM], ucon_mks[NDIM];\n struct of_geom geom_bl, *geom_mks;\n\n blgset(i, j, &geom_bl);\n\n DLOOP1 {\n ucon_bl[mu] = 0.;\n ucon_ks[mu] = 0.;\n ucon_mks[mu] = 0.;\n }\n ucon_bl[1] = ur;\n\n set_ut(ucon_bl, &geom_bl);\n bl_to_ks(X, ucon_bl, ucon_ks);\n\n double dxdX[NDIM][NDIM], dXdx[NDIM][NDIM];\n set_dxdX(X, dxdX);\n invert(&dxdX[0][0], &dXdx[0][0]);\n DLOOP2 {\n ucon_mks[mu] += dXdx[mu][nu]*ucon_ks[nu];\n }\n\n geom_mks = get_geometry(i, j, k, CENT);\n fourvel_to_prim(ucon_mks, P, geom_mks);\n //printf(\"[%i %i %i] r = %e ucons = %e %e %e vr = %e\\n\", \n // i, j, k, r, ucon_bl[1], ucon_ks[1], ucon_mks[1], P[U1]);\n\n P[RHO] = rho;\n P[UU] = u;\n P[B1] = 0.;\n P[B2] = 0.;\n P[B3] = 0.;\n\n /*if (j == N2/2){\n printf(\"\\nu[1]: %e %e %e\\n\", ucon_bl[1], ucon_ks[1], ucon_mks[1]);\n printf(\"T rho ur u = %e %e %e %e\\n\", T, rho, ur, u);\n printf(\"P[] = %e %e %e %e\\n\", P[0], P[1], P[2], P[3]);\n }*/\n\n /*double gcov[NDIM][NDIM];\n bl_gcov_func(r, th, gcov);\n double ut = -sqrt((-1. - gcov[1][1]*ur*ur)/gcov[0][0]);\n double ucon[NDIM] = {ut, ur, 0, 0};\n\n\n\n// if ( j == NG)\n// printf(\"ucon[] = %e %e %e %e\\n\", ucon[0], ucon[1], ucon[2], ucon[3]);\n\n double trans[NDIM][NDIM];\n // transform to Kerr-Schild\n // Make transform matrix\n memset(trans, 0, 16*sizeof(double));\n for (int mu = 0; mu < NDIM; mu++) {\n trans[mu][mu] = 1.;\n }\n trans[0][1] = 2. * r / (r * r - 2. * r + a * a);\n trans[3][1] = a / (r * r - 2. * r + a * a);\n\n // Transform from BL to KS coordinates\n double tmp[NDIM];\n for (int mu = 0; mu < NDIM; mu++) tmp[mu] = 0.;\n for (int mu = 0; mu < NDIM; mu++) {\n for (int nu = 0; nu < NDIM; nu++) {\n tmp[mu] += trans[mu][nu]*ucon[nu];\n }\n }\n for (int mu = 0; mu < NDIM; mu++) ucon[mu] = tmp[mu];\n\n // Transform from KS to MKS coordinates\n set_dxdX(X, trans);\n for (int mu = 0; mu < NDIM; mu++) tmp[mu] = 0.;\n for (int mu = 0; mu < NDIM; mu++) {\n for (int nu = 0; nu < NDIM; nu++) {\n tmp[mu] += trans[mu][nu]*ucon[nu];\n }\n }\n for (int mu = 0; mu < NDIM; mu++) ucon[mu] = tmp[mu];\n\n struct of_geom *geom = get_geometry(i, j, k, CENT);\n double alpha = 1.0 / sqrt( -geom->gcon[0][0] ) ;\n double gamma = ucon[0] * alpha;\n\n double beta[NDIM];\n beta[1] = alpha * alpha * geom->gcon[0][1];\n beta[2] = alpha * alpha * geom->gcon[0][2];\n beta[3] = alpha * alpha * geom->gcon[0][3];\n\n P[RHO] = rho;\n P[UU] = u;\n P[U1] = ucon[1] + beta[1] * gamma / alpha;\n P[U2] = 0.;\n P[U3] = 0.;\n P[B1] = 0.;\n P[B2] = 0.;\n P[B3] = 0.;\n if (r < 5.) P[U1] = 0.;\n\n //P[U1] *= 0.;*/\n}\n\n/*void get_bondi_prim(double r, double P[NDIM])\n{\n double T, rho, ur, ut;\n if (r > 2. + 1.e-8) {\n T = get_T(r);\n rho = pow(T, n);\n ur = -C1/r/r/pow(T,n);\n ut = (2.*ur/r+sqrt(ur*ur+1.-2./r))/(1.-2./r);\n } else {\n T = 1.;\n rho = RHOMIN;\n ur = 0.;\n ut = 1.;\n }\n\n P[RHO] = rho;\n P[UU] = n*rho*T;\n P[U1] = (ur + 2.*ut/(r + 2.))/r;\n P[U2] = 0.;\n P[U3] = 0.;\n P[B1] = 0.;\n P[B2] = 0.;\n P[B3] = 0.;\n}*/\n\nvoid init_prob()\n{\n double r, th, X[NDIM];\n\n double mdot = 1.;\n double rs = 8.;\n n = 1./(gam - 1.);\n\n // Solution constants\n double uc = sqrt(mdot/(2.*rs));\n double Vc = -sqrt(pow(uc,2)/(1. - 3.*pow(uc,2)));\n double Tc = -n*pow(Vc,2)/((n + 1.)*(n*pow(Vc,2) - 1.));\n C1 = uc*pow(rs,2)*pow(Tc,n);\n C2 = pow(1. + (1. + n)*Tc,2)*(1. - 2.*mdot/rs + pow(C1,2)/\n (pow(rs,4)*pow(Tc,2*n)));\n\n printf(\"a = %e Reh = %e\\n\", a, Reh);\n\n printf(\"mdot = %e\\n\", mdot);\n printf(\"rs = %e\\n\", rs);\n printf(\"n = %e\\n\", n);\n printf(\"uc = %e\\n\", uc);\n printf(\"Vc = %e\\n\", Vc);\n printf(\"Tc = %e\\n\", Tc);\n printf(\"C1 = %e\\n\", C1);\n printf(\"C2 = %e\\n\", C2);\n\n ZSLOOP(-NG,N1+NG-1,-NG,N2+NG-1,-NG,N3+NG-1) {\n coord(i, j, k, CENT, X);\n bl_coord(X, &r, &th);\n\n T_bondi[i][j] = get_T(r);\n }\n\n ZLOOP {\n get_prim_bondi(i, j, k, P[i][j][k]);\n } // ZSLOOP\n}\n\n// Convert Boyer-Lindquist four-velocity to MKS 3-velocity\nvoid coord_transform(double *Pr, int ii, int jj)\n{\n double X[NDIM], r, th, ucon[NDIM], trans[NDIM][NDIM], tmp[NDIM];\n double AA, BB, CC, discr;\n double alpha, gamma, beta[NDIM];\n struct of_geom *geom, blgeom;\n\n coord(ii, jj, 0, CENT, X);\n bl_coord(X, &r, &th);\n blgset(ii, jj, &blgeom);\n\n ucon[1] = Pr[U1];\n ucon[2] = Pr[U2];\n ucon[3] = Pr[U3];\n\n AA = blgeom.gcov[0][0];\n BB = 2. * (blgeom.gcov[0][1] * ucon[1] +\n blgeom.gcov[0][2] * ucon[2] +\n blgeom.gcov[0][3] * ucon[3]);\n CC = 1. +\n blgeom.gcov[1][1] * ucon[1] * ucon[1] +\n blgeom.gcov[2][2] * ucon[2] * ucon[2] +\n blgeom.gcov[3][3] * ucon[3] * ucon[3] +\n 2. * (blgeom.gcov[1][2] * ucon[1] * ucon[2] +\n blgeom.gcov[1][3] * ucon[1] * ucon[3] +\n blgeom.gcov[2][3] * ucon[2] * ucon[3]);\n\n discr = BB * BB - 4. * AA * CC;\n ucon[0] = (-BB - sqrt(discr)) / (2. * AA);\n // This is ucon in BL coords\n\n // transform to Kerr-Schild\n // Make transform matrix\n memset(trans, 0, 16*sizeof(double));\n for (int mu = 0; mu < NDIM; mu++) {\n trans[mu][mu] = 1.;\n }\n trans[0][1] = 2. * r / (r * r - 2. * r + a * a);\n trans[3][1] = a / (r * r - 2. * r + a * a);\n\n // Transform from BL to KS coordinates\n for (int mu = 0; mu < NDIM; mu++) tmp[mu] = 0.;\n for (int mu = 0; mu < NDIM; mu++) {\n for (int nu = 0; nu < NDIM; nu++) {\n tmp[mu] += trans[mu][nu]*ucon[nu];\n }\n }\n for (int mu = 0; mu < NDIM; mu++) ucon[mu] = tmp[mu];\n\n // Transform from KS to MKS coordinates\n set_dxdX(X, trans);\n for (int mu = 0; mu < NDIM; mu++) tmp[mu] = 0.;\n for (int mu = 0; mu < NDIM; mu++) {\n for (int nu = 0; nu < NDIM; nu++) {\n tmp[mu] += trans[mu][nu]*ucon[nu];\n }\n }\n for (int mu = 0; mu < NDIM; mu++) ucon[mu] = tmp[mu];\n\n //ucon[1] *= (1. / (r - R0));\n //ucon[1] /= dr_dx(X[1]);\n //ucon[2] *=\n // (1. / (M_PI + (1. - hslope) * M_PI * cos(2. * M_PI * X[2])));\n //ucon[2] /= dth_dx(X[2]);\n\n // Solve for v. Use same u^t, unchanged under KS -> KS'\n geom = get_geometry(ii, jj, 0, CENT) ;\n alpha = 1.0 / sqrt( -geom->gcon[0][0] ) ;\n gamma = ucon[0] * alpha;\n\n beta[1] = alpha * alpha * geom->gcon[0][1];\n beta[2] = alpha * alpha * geom->gcon[0][2];\n beta[3] = alpha * alpha * geom->gcon[0][3];\n\n Pr[U1] = ucon[1] + beta[1] * gamma / alpha;\n Pr[U2] = ucon[2] + beta[2] * gamma / alpha;\n Pr[U3] = ucon[3] + beta[3] * gamma / alpha;\n}\n\ndouble lfish_calc(double r)\n{\n return (((pow(a, 2) - 2. * a * sqrt(r) + pow(r, 2)) *\n ((-2. * a * r *\n (pow(a, 2) - 2. * a * sqrt(r) +\n pow(r,\n 2))) / sqrt(2. * a * sqrt(r) + (-3. + r) * r) +\n ((a + (-2. + r) * sqrt(r)) * (pow(r, 3) + pow(a, 2) *\n (2. + r))) / sqrt(1 + (2. * a) / pow (r, 1.5) - 3. / r)))\n / (pow(r, 3) * sqrt(2. * a * sqrt(r) + (-3. + r) * r) *\n (pow(a, 2) + (-2. + r) * r))\n );\n}\n\nvoid bound_gas_prob_x1r(int i, int j, int k, grid_prim_type P)\n{\n get_prim_bondi(i, j, k, P[i][j][k]);\n}\n\n", "meta": {"hexsha": "3f103e4bd09f047810a83a718a80e59def08bb48", "size": 10968, "ext": "c", "lang": "C", "max_stars_repo_path": "prob/bondi/problem.c", "max_stars_repo_name": "soumide1102/nubhlight", "max_stars_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-02-05T22:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:05:37.000Z", "max_issues_repo_path": "prob/bondi/problem.c", "max_issues_repo_name": "soumide1102/nubhlight", "max_issues_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T02:10:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T20:00:30.000Z", "max_forks_repo_path": "prob/bondi/problem.c", "max_forks_repo_name": "soumide1102/nubhlight", "max_forks_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-02-21T04:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T21:42:12.000Z", "avg_line_length": 26.1766109785, "max_line_length": 80, "alphanum_fraction": 0.4815827863, "num_tokens": 4629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4449277621746952}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"mpi.h\"\n\nint numTasks, mpiRank;\n\n#include \"myFunc.h\"\n\nvoid writeParam(char *filename, int nParam, double *x)\n{\n FILE *fn=fopen(filename,\"w\");\n if(!fn) {\n fprintf(stderr,\"Cannot open %s\\n\",filename);\n exit(1);\n }\n\n uint32_t n=nParam; // ensure size is uint32_t\n fwrite(&n,sizeof(uint32_t), 1, fn);\n for(int i=0; i < nParam; i++) {\n float tmp=x[i];\n fwrite(&tmp,sizeof(float), 1, fn);\n }\n fclose(fn);\n}\n\nint masterOP=1;\nvoid startClient(void * restrict my_func_data)\n{\n int op;\n double xFromMPI[N_PARAM];\n double partialError,sum;\n \n for(;;) { // loop until the master says I am done - then exit\n MPI_Bcast(&op, 1, MPI_INT, 0, MPI_COMM_WORLD); // receive the op code\n if(op==0) { // we are done, normal exit\n break;\n }\n MPI_Bcast(xFromMPI, N_PARAM, MPI_DOUBLE, 0, MPI_COMM_WORLD); // receive the parameters\n partialError = objFunc(N_PARAM, xFromMPI, NULL, my_func_data);\n MPI_Reduce(&partialError, &sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);\n }\n}\n\ndouble mpiObjFunc(unsigned n, const double * restrict x, double * restrict grad,\n\t\t void * restrict my_func_data)\n{\n int op;\n double partialError, totalError=0.;\n\n MPI_Bcast(&masterOP, 1, MPI_INT, 0, MPI_COMM_WORLD); // Send the master op code\n MPI_Bcast((void*) x, N_PARAM, MPI_DOUBLE, 0, MPI_COMM_WORLD); // Send the parameters\n partialError = objFunc(N_PARAM, x, NULL, my_func_data);\n MPI_Reduce(&partialError, &totalError, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); // get the totalError\n\n return(totalError);\n}\n\nint main(int argc, char* argv[])\n{\n nlopt_opt opt;\n userData_t uData = {0};\n FILE *fout_mpi;\n\n if(argc < 4) {\n fprintf(stderr,\"Use: datafile paramFile mpiTimingFile\\n\");\n return -1;\n }\n\n int ret = MPI_Init(&argc,&argv);\n if (ret != MPI_SUCCESS) {\n printf (\"Error in MPI_Init()!\\n\");\n MPI_Abort(MPI_COMM_WORLD, ret);\n }\n \n MPI_Comm_size(MPI_COMM_WORLD,&numTasks);\n MPI_Comm_rank(MPI_COMM_WORLD,&mpiRank);\n\n#if defined(NO_IO_EXAMPLES)\n#pragma message \"TEST case: Clients use random memory values\"\n init_noIO(NO_IO_EXAMPLES,&uData); \n#else\n#pragma message \"TEST case: all clients perform file reads\"\n { // for simplicity, append the mpiRank to the data filename\n char filename[256];\n sprintf(filename,\"%s.%d\",argv[1],mpiRank);\n //fprintf(stderr,\"Loading %s into coprocessor %d\\n\", filename, MIC_DEV);\n init(filename,&uData); \n }\n#endif\n\n if(mpiRank > 0) {\n startClient(&uData);\n } else { // Master code\n\n { // open MPI results file for this size run\n char buf[256];\n sprintf(buf, \"%s.%04d.txt\",argv[3],numTasks);\n fout_mpi = fopen(buf,\"w\");\n if(!fout_mpi) {\n\tfprintf(stderr,\"Cannot open file %s\\n\",buf);\n\treturn -1;\n }\n }\n\n printf (\"Number of tasks= %d My rank= %d, number clients %d\\n\", numTasks,mpiRank,numTasks);\n#ifdef MPI_NUM_COPROC_PER_NODE\n printf (\"Number of coprocessors per node= %d\\n\", MPI_NUM_COPROC_PER_NODE);\n#endif\n printf(\"myFunc %s\\n\", desc);\n printf(\"nExamples %d\\n\", uData.nExamples);\n printf(\"Number Parameters %d\\n\", N_PARAM);\n \n opt = nlopt_create(NLOPT_LN_PRAXIS, N_PARAM); // algorithm and dimensionality\n // NOTE: alternative optimization methods ...\n //opt = nlopt_create(NLOPT_LN_NEWUOA, N_PARAM);\n //opt = nlopt_create(NLOPT_LN_COBYLA, N_PARAM);\n //opt = nlopt_create(NLOPT_LN_BOBYQA, N_PARAM);\n //opt = nlopt_create(NLOPT_LN_AUGLAG, N_PARAM);\n \n nlopt_set_min_objective(opt, mpiObjFunc, (void*) &uData);\n/*\n#if defined(MAX_RUNTIME) \n fprintf(stderr,\"Warning: performing a quick %d second test!\\n\", MAX_RUNTIME);\n nlopt_set_maxtime(opt, MAX_RUNTIME); // Use for running quick tests\n#else\n fprintf(stderr,\"MAX runtime %d seconds!\\n\", 120*60);\n nlopt_set_maxtime(opt, (120. * 60.)); // maximum runtime in seconds\n#endif\n*/\n double minf; /* the minimum objective value, upon return */\n \n __declspec(align(64)) double x[N_PARAM];\n for(int i=0; i < N_PARAM; i++) x[i] = 0.1*(random()/(double)RAND_MAX);\n \n double startTime=getTime();\n ret=nlopt_optimize(opt, x, &minf);\n printf(\"Optimization Time %g\\n\",getTime()-startTime);\n \n if (ret < 0) {\n printf(\"nlopt failed! ret %d\\n\", ret);\n } else {\n printf(\"found minimum %0.10g ret %d\\n\", minf,ret);\n }\n writeParam(argv[2],N_PARAM, x);\n\n nlopt_destroy(opt);\n \n masterOP = 0; // signal completion\n MPI_Bcast(&masterOP, 1, MPI_INT, 0, MPI_COMM_WORLD); // Send the master op code\n printf(\"----------- performance times for the Master ----------\\n\");\n fini(&uData);\n }\n\n int client_nExamples[numTasks];\n double client_timeObjFunc[numTasks];\n int client_countObjFunc[numTasks];\n double client_timeDataLoad[numTasks];\n double client_minTime[numTasks];\n double client_maxTime[numTasks];\n \n MPI_Gather(&uData.nExamples, 1, MPI_INT, client_nExamples, 1, MPI_INT, 0, MPI_COMM_WORLD);\n MPI_Gather(&uData.countObjFunc, 1, MPI_INT, client_countObjFunc, 1, MPI_INT, 0, MPI_COMM_WORLD);\n MPI_Gather(&uData.timeDataLoad, 1, MPI_DOUBLE, client_timeDataLoad, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n MPI_Gather(&uData.timeObjFunc, 1, MPI_DOUBLE, client_timeObjFunc, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n MPI_Gather(&uData.minTime, 1, MPI_DOUBLE, client_minTime, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n MPI_Gather(&uData.maxTime, 1, MPI_DOUBLE, client_maxTime, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\n if(mpiRank==0) {\n printf(\"----------- performance times for the MPI run ----------\\n\");\n printf(\"function: %s\\n\",desc);\n \n uint64_t totalExamples=0;\n for(int i=0; i < numTasks; i++) totalExamples += client_nExamples[i];\n printf(\"totalExamples %g\\n\",(double) totalExamples);\n \n printf(\"AveObjTime %g, countObjFunc %d, totalObjTime %g\\n\",\n\t uData.timeObjFunc/uData.countObjFunc, uData.countObjFunc, uData.timeObjFunc);\n#ifdef FLOP_ESTIMATE\n printf(\"Estimated flops in myFunc %d, estimated average TFlop/s %g, nClients %d\\n\", FLOP_ESTIMATE,\n\t (((double)totalExamples * (double)FLOP_ESTIMATE)/(uData.timeObjFunc/uData.countObjFunc)/1.e12),\n\t numTasks);\n printf(\"Estimated maximum TFlop/s %g, minimum TFLop/s %g\\n\",\n\t (((double)totalExamples*(double)FLOP_ESTIMATE)/(uData.minTime)/1.e12),\n\t (((double)totalExamples*(double)FLOP_ESTIMATE)/(uData.maxTime)/1.e12) );\n#endif\n \n fprintf(fout_mpi, \"nExamples countObjFunc timeDataLoad timeObjFunc minObjFcnTime maxObjFcnTime\\n\");\n for(int i=0; i < numTasks; i++) {\n fprintf(fout_mpi, \"%g %g %g %g %g %g\\n\",\n\t (double) client_nExamples[i], (double) client_countObjFunc[i], client_timeDataLoad[i],\n\t client_timeObjFunc[i], client_minTime[i], client_maxTime[i]);\n }\n }\n\n MPI_Finalize();\n \n return 0;\n}\n", "meta": {"hexsha": "2fcadfa410feb4d70be932ef51c94129570a630c", "size": 6782, "ext": "c", "lang": "C", "max_stars_repo_path": "nlpca_exp/program/farbOpt/mpiTrain.c", "max_stars_repo_name": "puckbee/PhiBench", "max_stars_repo_head_hexsha": "bf2fa1a4459d72f42cf39d772bf49d6965335b78", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-08-14T12:32:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-17T17:51:55.000Z", "max_issues_repo_path": "pca_exp/program/farbOpt/mpiTrain.c", "max_issues_repo_name": "puckbee/PhiBench", "max_issues_repo_head_hexsha": "bf2fa1a4459d72f42cf39d772bf49d6965335b78", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pca_exp/program/farbOpt/mpiTrain.c", "max_forks_repo_name": "puckbee/PhiBench", "max_forks_repo_head_hexsha": "bf2fa1a4459d72f42cf39d772bf49d6965335b78", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5742574257, "max_line_length": 106, "alphanum_fraction": 0.6763491595, "num_tokens": 2037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4449277545396777}} {"text": "/* monte/miser.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* MISER. Based on the algorithm described in the following article,\n\n W.H. Press, G.R. Farrar, \"Recursive Stratified Sampling for\n Multidimensional Monte Carlo Integration\", Computers in Physics,\n v4 (1990), pp190-195.\n\n*/\n\n/* Author: MJB */\n/* Modified by Brian Gough 12/2000 */\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nstatic int\nestimate_corrmc (gsl_monte_function * f,\n\t\t const double xl[], const double xu[],\n\t\t size_t dim, size_t calls,\n\t\t gsl_rng * r,\n\t\t gsl_monte_miser_state * state,\n\t\t double *result, double *abserr,\n\t\t const double xmid[], double sigma_l[], double sigma_r[]);\n\n\nint\ngsl_monte_miser_integrate (gsl_monte_function * f,\n\t\t\t const double xl[], const double xu[],\n\t\t\t size_t dim, size_t calls,\n\t\t\t gsl_rng * r,\n\t\t\t gsl_monte_miser_state * state,\n\t\t\t double *result, double *abserr)\n{\n size_t n, estimate_calls, calls_l, calls_r;\n const size_t min_calls = state->min_calls;\n size_t i;\n size_t i_bisect;\n int found_best;\n\n double res_est = 0, err_est = 0;\n double res_r = 0, err_r = 0, res_l = 0, err_l = 0;\n double xbi_l, xbi_m, xbi_r, s;\n\n double vol;\n double weight_l, weight_r;\n\n double *x = state->x;\n double *xmid = state->xmid;\n double *sigma_l = state->sigma_l, *sigma_r = state->sigma_r;\n\n if (dim != state->dim)\n {\n GSL_ERROR (\"number of dimensions must match allocated size\", GSL_EINVAL);\n }\n\n for (i = 0; i < dim; i++)\n {\n if (xu[i] <= xl[i])\n\t{\n\t GSL_ERROR (\"xu must be greater than xl\", GSL_EINVAL);\n\t}\n\n if (xu[i] - xl[i] > GSL_DBL_MAX)\n\t{\n\t GSL_ERROR (\"Range of integration is too large, please rescale\",\n\t\t GSL_EINVAL);\n\t}\n }\n\n if (state->alpha < 0)\n {\n GSL_ERROR (\"alpha must be non-negative\", GSL_EINVAL);\n }\n\n /* Compute volume */\n\n vol = 1;\n\n for (i = 0; i < dim; i++)\n {\n vol *= xu[i] - xl[i];\n }\n\n if (calls < state->min_calls_per_bisection)\n {\n double m = 0.0, q = 0.0;\n\n if (calls < 2)\n\t{\n\t GSL_ERROR (\"insufficient calls for subvolume\", GSL_EFAILED);\n\t}\n\n for (n = 0; n < calls; n++)\n\t{\n\t /* Choose a random point in the integration region */\n\n\t for (i = 0; i < dim; i++)\n\t {\n\t x[i] = xl[i] + gsl_rng_uniform_pos (r) * (xu[i] - xl[i]);\n\t }\n\n\t {\n\t double fval = GSL_MONTE_FN_EVAL (f, x);\n\n\t /* recurrence for mean and variance */\n\n\t double d = fval - m;\n\t m += d / (n + 1.0);\n\t q += d * d * (n / (n + 1.0));\n\t }\n\t}\n\n *result = vol * m;\n\n *abserr = vol * sqrt (q / (calls * (calls - 1.0)));\n\n return GSL_SUCCESS;\n }\n\n estimate_calls = GSL_MAX (min_calls, calls * (state->estimate_frac));\n\n if (estimate_calls < 4 * dim)\n {\n GSL_ERROR (\"insufficient calls to sample all halfspaces\", GSL_ESANITY);\n }\n\n /* Flip coins to bisect the integration region with some fuzz */\n\n for (i = 0; i < dim; i++)\n {\n s = (gsl_rng_uniform (r) - 0.5) >= 0.0 ? state->dither : -state->dither;\n state->xmid[i] = (0.5 + s) * xl[i] + (0.5 - s) * xu[i];\n }\n\n /* The idea is to chose the direction to bisect based on which will\n give the smallest total variance. We could (and may do so later)\n use MC to compute these variances. But the NR guys simply estimate\n the variances by finding the min and max function values \n for each half-region for each bisection. */\n\n estimate_corrmc (f, xl, xu, dim, estimate_calls,\n\t\t r, state, &res_est, &err_est, xmid, sigma_l, sigma_r);\n\n /* We have now used up some calls for the estimation */\n\n calls -= estimate_calls;\n\n /* Now find direction with the smallest total \"variance\" */\n\n {\n double best_var = GSL_DBL_MAX;\n double beta = 2.0 / (1.0 + state->alpha);\n found_best = 0;\n i_bisect = 0;\n weight_l = weight_r = 1.0;\n\n for (i = 0; i < dim; i++)\n {\n\tif (sigma_l[i] >= 0 && sigma_r[i] >= 0)\n\t {\n\t /* estimates are okay */\n\t double var = pow (sigma_l[i], beta) + pow (sigma_r[i], beta);\n\n\t if (var <= best_var)\n\t {\n\t\tfound_best = 1;\n\t\tbest_var = var;\n\t\ti_bisect = i;\n\t\tweight_l = pow (sigma_l[i], beta);\n\t\tweight_r = pow (sigma_r[i], beta);\n\t }\n\t }\n\telse\n\t {\n\t if (sigma_l[i] < 0)\n\t {\n\t\tGSL_ERROR (\"no points in left-half space!\", GSL_ESANITY);\n\t }\n\t if (sigma_r[i] < 0)\n\t {\n\t\tGSL_ERROR (\"no points in right-half space!\", GSL_ESANITY);\n\t }\n\t }\n }\n }\n\n if (!found_best)\n {\n /* All estimates were the same, so chose a direction at random */\n\n i_bisect = gsl_rng_uniform_int (r, dim);\n }\n\n xbi_l = xl[i_bisect];\n xbi_m = xmid[i_bisect];\n xbi_r = xu[i_bisect];\n\n /* Get the actual fractional sizes of the two \"halves\", and\n distribute the remaining calls among them */\n\n {\n double fraction_l = fabs ((xbi_m - xbi_l) / (xbi_r - xbi_l));\n double fraction_r = 1 - fraction_l;\n\n double a = fraction_l * weight_l;\n double b = fraction_r * weight_r;\n\n calls_l = min_calls + (calls - 2 * min_calls) * a / (a + b);\n calls_r = min_calls + (calls - 2 * min_calls) * b / (a + b);\n }\n\n /* Compute the integral for the left hand side of the bisection */\n\n /* Due to the recursive nature of the algorithm we must allocate\n some new memory for each recursive call */\n\n {\n int status;\n\n double *xu_tmp = (double *) malloc (dim * sizeof (double));\n\n if (xu_tmp == 0)\n {\n\tGSL_ERROR_VAL (\"out of memory for left workspace\", GSL_ENOMEM, 0);\n }\n\n for (i = 0; i < dim; i++)\n {\n\txu_tmp[i] = xu[i];\n }\n\n xu_tmp[i_bisect] = xbi_m;\n\n status = gsl_monte_miser_integrate (f, xl, xu_tmp,\n\t\t\t\t\tdim, calls_l, r, state,\n\t\t\t\t\t&res_l, &err_l);\n free (xu_tmp);\n\n if (status != GSL_SUCCESS)\n {\n\treturn status;\n }\n }\n\n /* Compute the integral for the right hand side of the bisection */\n\n {\n int status;\n\n double *xl_tmp = (double *) malloc (dim * sizeof (double));\n\n if (xl_tmp == 0)\n {\n\tGSL_ERROR_VAL (\"out of memory for right workspace\", GSL_ENOMEM, 0);\n }\n\n for (i = 0; i < dim; i++)\n {\n\txl_tmp[i] = xl[i];\n }\n\n xl_tmp[i_bisect] = xbi_m;\n\n status = gsl_monte_miser_integrate (f, xl_tmp, xu,\n\t\t\t\t\tdim, calls_r, r, state,\n\t\t\t\t\t&res_r, &err_r);\n free (xl_tmp);\n\n if (status != GSL_SUCCESS)\n {\n\treturn status;\n }\n }\n\n *result = res_l + res_r;\n *abserr = sqrt (err_l * err_l + err_r * err_r);\n\n return GSL_SUCCESS;\n}\n\ngsl_monte_miser_state *\ngsl_monte_miser_alloc (size_t dim)\n{\n gsl_monte_miser_state *s =\n (gsl_monte_miser_state *) malloc (sizeof (gsl_monte_miser_state));\n\n if (s == 0)\n {\n GSL_ERROR_VAL (\"failed to allocate space for miser state struct\",\n\t\t GSL_ENOMEM, 0);\n }\n\n s->x = (double *) malloc (dim * sizeof (double));\n\n if (s->x == 0)\n {\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for x\", GSL_ENOMEM, 0);\n }\n\n s->xmid = (double *) malloc (dim * sizeof (double));\n\n if (s->xmid == 0)\n {\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for xmid\", GSL_ENOMEM, 0);\n }\n\n s->sigma_l = (double *) malloc (dim * sizeof (double));\n\n if (s->sigma_l == 0)\n {\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for sigma_l\", GSL_ENOMEM, 0);\n }\n\n s->sigma_r = (double *) malloc (dim * sizeof (double));\n\n if (s->sigma_r == 0)\n {\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for sigma_r\", GSL_ENOMEM, 0);\n }\n\n s->fmax_l = (double *) malloc (dim * sizeof (double));\n\n if (s->fmax_l == 0)\n {\n free (s->sigma_r);\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for fmax_l\", GSL_ENOMEM, 0);\n }\n\n s->fmax_r = (double *) malloc (dim * sizeof (double));\n\n if (s->fmax_r == 0)\n {\n free (s->fmax_l);\n free (s->sigma_r);\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for fmax_r\", GSL_ENOMEM, 0);\n }\n\n s->fmin_l = (double *) malloc (dim * sizeof (double));\n\n if (s->fmin_l == 0)\n {\n free (s->fmax_r);\n free (s->fmax_l);\n free (s->sigma_r);\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for fmin_l\", GSL_ENOMEM, 0);\n }\n\n s->fmin_r = (double *) malloc (dim * sizeof (double));\n\n if (s->fmin_r == 0)\n {\n free (s->fmin_l);\n free (s->fmax_r);\n free (s->fmax_l);\n free (s->sigma_r);\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for fmin_r\", GSL_ENOMEM, 0);\n }\n\n s->fsum_l = (double *) malloc (dim * sizeof (double));\n\n if (s->fsum_l == 0)\n {\n free (s->fmin_r);\n free (s->fmin_l);\n free (s->fmax_r);\n free (s->fmax_l);\n free (s->sigma_r);\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for fsum_l\", GSL_ENOMEM, 0);\n }\n\n s->fsum_r = (double *) malloc (dim * sizeof (double));\n\n if (s->fsum_r == 0)\n {\n free (s->fsum_l);\n free (s->fmin_r);\n free (s->fmin_l);\n free (s->fmax_r);\n free (s->fmax_l);\n free (s->sigma_r);\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for fsum_r\", GSL_ENOMEM, 0);\n }\n\n s->fsum2_l = (double *) malloc (dim * sizeof (double));\n\n if (s->fsum2_l == 0)\n {\n free (s->fsum_r);\n free (s->fsum_l);\n free (s->fmin_r);\n free (s->fmin_l);\n free (s->fmax_r);\n free (s->fmax_l);\n free (s->sigma_r);\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for fsum2_l\", GSL_ENOMEM, 0);\n }\n\n s->fsum2_r = (double *) malloc (dim * sizeof (double));\n\n if (s->fsum2_r == 0)\n {\n free (s->fsum2_l);\n free (s->fsum_r);\n free (s->fsum_l);\n free (s->fmin_r);\n free (s->fmin_l);\n free (s->fmax_r);\n free (s->fmax_l);\n free (s->sigma_r);\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for fsum2_r\", GSL_ENOMEM, 0);\n }\n\n\n s->hits_r = (size_t *) malloc (dim * sizeof (size_t));\n\n if (s->hits_r == 0)\n {\n free (s->fsum2_r);\n free (s->fsum2_l);\n free (s->fsum_r);\n free (s->fsum_l);\n free (s->fmin_r);\n free (s->fmin_l);\n free (s->fmax_r);\n free (s->fmax_l);\n free (s->sigma_r);\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for fsum2_r\", GSL_ENOMEM, 0);\n }\n\n s->hits_l = (size_t *) malloc (dim * sizeof (size_t));\n\n if (s->hits_l == 0)\n {\n free (s->hits_r);\n free (s->fsum2_r);\n free (s->fsum2_l);\n free (s->fsum_r);\n free (s->fsum_l);\n free (s->fmin_r);\n free (s->fmin_l);\n free (s->fmax_r);\n free (s->fmax_l);\n free (s->sigma_r);\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for fsum2_r\", GSL_ENOMEM, 0);\n }\n\n s->dim = dim;\n\n gsl_monte_miser_init (s);\n\n return s;\n}\n\nint\ngsl_monte_miser_init (gsl_monte_miser_state * s)\n{\n /* We use 8 points in each halfspace to estimate the variance. There are\n 2*dim halfspaces. A variance estimate requires a minimum of 2 points. */\n s->min_calls = 16 * s->dim;\n s->min_calls_per_bisection = 32 * s->min_calls;\n s->estimate_frac = 0.1;\n s->alpha = 2.0;\n s->dither = 0.0;\n\n return GSL_SUCCESS;\n}\n\nvoid\ngsl_monte_miser_free (gsl_monte_miser_state * s)\n{\n free (s->hits_r);\n free (s->hits_l);\n free (s->fsum2_r);\n free (s->fsum2_l);\n free (s->fsum_r);\n free (s->fsum_l);\n free (s->fmin_r);\n free (s->fmin_l);\n free (s->fmax_r);\n free (s->fmax_l);\n free (s->sigma_r);\n free (s->sigma_l);\n free (s->xmid);\n free (s->x);\n free (s);\n}\n\nstatic int\nestimate_corrmc (gsl_monte_function * f,\n\t\t const double xl[], const double xu[],\n\t\t size_t dim, size_t calls,\n\t\t gsl_rng * r,\n\t\t gsl_monte_miser_state * state,\n\t\t double *result, double *abserr,\n\t\t const double xmid[], double sigma_l[], double sigma_r[])\n{\n size_t i, n;\n \n double *x = state->x;\n double *fsum_l = state->fsum_l;\n double *fsum_r = state->fsum_r;\n double *fsum2_l = state->fsum2_l;\n double *fsum2_r = state->fsum2_r;\n size_t *hits_l = state->hits_l;\n size_t *hits_r = state->hits_r;\n\n double m = 0.0, q = 0.0; \n double vol = 1.0;\n\n for (i = 0; i < dim; i++)\n {\n vol *= xu[i] - xl[i];\n hits_l[i] = hits_r[i] = 0;\n fsum_l[i] = fsum_r[i] = 0.0;\n fsum2_l[i] = fsum2_r[i] = 0.0;\n sigma_l[i] = sigma_r[i] = -1;\n }\n\n for (n = 0; n < calls; n++)\n {\n double fval;\n \n unsigned int j = (n/2) % dim;\n unsigned int side = (n % 2);\n\n for (i = 0; i < dim; i++)\n\t{\n double z = gsl_rng_uniform_pos (r) ;\n\n if (i != j) \n {\n x[i] = xl[i] + z * (xu[i] - xl[i]);\n }\n else\n {\n if (side == 0) \n {\n x[i] = xmid[i] + z * (xu[i] - xmid[i]);\n }\n else\n {\n x[i] = xl[i] + z * (xmid[i] - xl[i]);\n }\n }\n\t}\n\n fval = GSL_MONTE_FN_EVAL (f, x);\n\n /* recurrence for mean and variance */\n {\n\tdouble d = fval - m;\n\tm += d / (n + 1.0);\n\tq += d * d * (n / (n + 1.0));\n }\n\n /* compute the variances on each side of the bisection */\n for (i = 0; i < dim; i++)\n\t{\n\t if (x[i] <= xmid[i])\n\t {\n\t fsum_l[i] += fval;\n\t fsum2_l[i] += fval * fval;\n\t hits_l[i]++;\n\t }\n\t else\n\t {\n\t fsum_r[i] += fval;\n\t fsum2_r[i] += fval * fval;\n\t hits_r[i]++;\n\t }\n\t}\n }\n\n for (i = 0; i < dim; i++)\n {\n double fraction_l = (xmid[i] - xl[i]) / (xu[i] - xl[i]);\n\n if (hits_l[i] > 0)\n\t{\n\t fsum_l[i] /= hits_l[i];\n\t sigma_l[i] = sqrt (fsum2_l[i] - fsum_l[i] * fsum_l[i] / hits_l[i]);\n\t sigma_l[i] *= fraction_l * vol / hits_l[i];\n\t}\n\n if (hits_r[i] > 0)\n\t{\n\t fsum_r[i] /= hits_r[i];\n\t sigma_r[i] = sqrt (fsum2_r[i] - fsum_r[i] * fsum_r[i] / hits_r[i]);\n\t sigma_r[i] *= (1 - fraction_l) * vol / hits_r[i];\n\t}\n }\n\n *result = vol * m;\n\n if (calls < 2)\n {\n *abserr = GSL_POSINF;\n }\n else\n {\n *abserr = vol * sqrt (q / (calls * (calls - 1.0)));\n }\n\n return GSL_SUCCESS;\n}\n\n", "meta": {"hexsha": "4e5932aa1d58da2b8fa0045867a0b9a04d8aa5e8", "size": 15550, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/monte/miser.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/monte/miser.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/monte/miser.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 22.8005865103, "max_line_length": 79, "alphanum_fraction": 0.551511254, "num_tokens": 5100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.4443568304005992}} {"text": "/* specfunc/bessel_Y1.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n#include \"bessel.h\"\n#include \"bessel_amp_phase.h\"\n#include \"cheb_eval.c\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n/* based on SLATEC besy1, 1977 version, w. fullerton */\n\n/* chebyshev expansions\n\n series for by1 on the interval 0. to 1.60000d+01\n with weighted error 1.87e-18\n log weighted error 17.73\n significant figures required 17.83\n decimal places required 18.30\n*/\n\nstatic double by1_data[14] = {\n 0.03208047100611908629,\n 1.262707897433500450,\n 0.00649996189992317500,\n -0.08936164528860504117,\n 0.01325088122175709545,\n -0.00089790591196483523,\n 0.00003647361487958306,\n -0.00000100137438166600,\n 0.00000001994539657390,\n -0.00000000030230656018,\n 0.00000000000360987815,\n -0.00000000000003487488,\n 0.00000000000000027838,\n -0.00000000000000000186\n};\nstatic cheb_series by1_cs = {\n by1_data,\n 13,\n -1, 1,\n 10\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_bessel_Y1_e(const double x, gsl_sf_result * result)\n{\n const double two_over_pi = 2.0/M_PI;\n const double xmin = 1.571*GSL_DBL_MIN; /*exp ( amax1(alog(r1mach(1)), -alog(r1mach(2)))+.01) */\n const double x_small = 2.0 * GSL_SQRT_DBL_EPSILON;\n const double xmax = 1.0/GSL_DBL_EPSILON;\n\n /* CHECK_POINTER(result) */\n\n if(x <= 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x < xmin) {\n OVERFLOW_ERROR(result);\n }\n else if(x < x_small) {\n const double lnterm = log(0.5*x);\n gsl_sf_result J1;\n gsl_sf_result c;\n int status = gsl_sf_bessel_J1_e(x, &J1);\n cheb_eval_e(&by1_cs, -1.0, &c);\n result->val = two_over_pi * lnterm * J1.val + (0.5 + c.val)/x;\n result->err = fabs(lnterm) * (fabs(GSL_DBL_EPSILON * J1.val) + J1.err) + c.err/x;\n return status;\n }\n else if(x < 4.0) {\n const double lnterm = log(0.5*x);\n int status;\n gsl_sf_result J1;\n gsl_sf_result c;\n cheb_eval_e(&by1_cs, 0.125*x*x-1.0, &c);\n status = gsl_sf_bessel_J1_e(x, &J1);\n result->val = two_over_pi * lnterm * J1.val + (0.5 + c.val)/x;\n result->err = fabs(lnterm) * (fabs(GSL_DBL_EPSILON * J1.val) + J1.err) + c.err/x;\n return status;\n }\n else if(x < xmax) {\n const double z = 32.0/(x*x) - 1.0;\n gsl_sf_result ca;\n gsl_sf_result ct;\n gsl_sf_result cp;\n const int stat_ca = cheb_eval_e(&_gsl_sf_bessel_amp_phase_bm1_cs, z, &ca);\n const int stat_ct = cheb_eval_e(&_gsl_sf_bessel_amp_phase_bth1_cs, z, &ct);\n const int stat_cp = gsl_sf_bessel_cos_pi4_e(x, ct.val/x, &cp);\n const double sqrtx = sqrt(x);\n const double ampl = (0.75 + ca.val) / sqrtx;\n result->val = -ampl * cp.val;\n result->err = fabs(cp.val) * ca.err/sqrtx + fabs(ampl) * cp.err;\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_ERROR_SELECT_3(stat_ca, stat_ct, stat_cp);\n }\n else {\n UNDERFLOW_ERROR(result);\n }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_Y1(const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_Y1_e(x, &result));\n}\n", "meta": {"hexsha": "205eed30533ac1bdef92c631c8b8a25acf826510", "size": 4177, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_Y1.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_Y1.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_Y1.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 30.268115942, "max_line_length": 97, "alphanum_fraction": 0.6380177161, "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.731058578630005, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.44423737322383716}} {"text": "#ifndef BLAS_WRAPPER_H\n#define BLAS_WRAPPER_H\n\n#include \n#include \n#include \n#include \n\n// Useful dense kernels from BLAS, with readable, overloaded, cross-platform names and some simplified calling\n// dot (dot-product of vectors)\n// nrm2 (2-norm of a vector)\n// asum (1-norm of a vector)\n// amax (index of maximum absolute value in a vector)\n// swap (exchanging values in two vectors)\n// copy (copying values from one vector to another)\n// axpy (adding a scalar times a vector to another vector)\n// scal (multiplying a vector by a scalar)\n// gemv (multiplying a matrix times a vector, scaling, and adding result to another vector))\n// gemm (multiplying two matrices, scaling, and adding result to another matrix)\n// In addition:\n// set_zero (zero out all entries in a vector)\n// abs_max (return the infinity norm of a vector, i.e. the magnitude of its largest element)\n// There are also version using std::vector for convenience.\n\n// Matrices are always assumed to be in column-major format.\n\n// You can #define one of:\n// USE_FORTRAN_BLAS (if your BLAS calls should look like dgemm_ with FORTRAN calling conventions, as in GOTO BLAS)\n// USE_AMD_BLAS (if using the AMD Math Library)\n// USE_CBLAS (if instead you have calls like cblas_dgemm, and have a file \"cblas.h\" available)\n// or, if you're on the Mac, it will default to the vecLib CBLAS if none of these are specified.\n\nnamespace BLAS{\n \n template\n inline void set_zero(int n, T *x)\n { std::memset(x, 0, n*sizeof(T)); }\n \n}\n\n//============================================================================\n#ifdef USE_FORTRAN_BLAS\n\nextern \"C\" {\n double dsdot_(const int*, const float*, const int*, const float*, const int*);\n double sdot_(const int*, const float*, const int*, const float*, const int*);\n double ddot_(const int*, const double*, const int*, const double*, const int*);\n float snrm2_(const int*, const float*, const int*);\n double dnrm2_(const int*, const double*, const int*);\n float sasum_(const int*, const float*, const int*);\n double dasum_(const int*, const double*, const int*);\n int isamax_(const int*, const float*, const int*);\n int idamax_(const int*, const double*, const int*);\n void sswap_(const int*, float*, const int*, float*, const int*);\n void dswap_(const int*, double*, const int*, double*, const int*);\n void scopy_(const int*, const float*, const int*, float*, const int*);\n void dcopy_(const int*, const double*, const int*, double*, const int*);\n void saxpy_(const int*, const float*, const float*, const int*, float*, const int*);\n void daxpy_(const int*, const double*, const double*, const int*, double*, const int*);\n void sscal_(const int*, const float*, float*, const int*);\n void dscal_(const int*, const double*, double*, const int*);\n void sgemv_(const char*, const int*, const int*, const float*, const float*, const int*, const float*, const int*, const float*, float*, const int*);\n void dgemv_(const char*, const int*, const int*, const double*, const double*, const int*, const double*, const int*, const double*, double*, const int*);\n void sgemm_(const char*, const char*, const int*, const int*, const int*, const float*, const float*, const int*, const float*, const int*, const float*, float*, const int*);\n void dgemm_(const char*, const char*, const int*, const int*, const int*, const double*, const double*, const int*, const double*, const int*, const double*, double*, const int*);\n}\n\nnamespace BLAS{\n \n enum Transpose {NoTrans='N', Trans='T'};\n enum UpperLower {Upper='U', Lower='L'};\n enum UnitDiag {NonUnit='N', Unit='U'};\n enum Side {Left='L', Right='R'};\n \n // dot products\n \n inline double dot(int n, const float *x, int incx, const float *y, int incy=1)\n { return dsdot_(&n, x, &incx, y, &incy); }\n \n inline double dot(int n, const float *x, const float *y, int incy=1)\n { const int one=1; return dsdot_(&n, x, &one, y, &incy); }\n \n inline float dotf(int n, const float *x, int incx, const float *y, int incy=1)\n { return (float)sdot_(&n, x, &incx, y, &incy); }\n \n inline float dotf(int n, const float *x, const float *y, int incy=1)\n { const int one=1; return (float)sdot_(&n, x, &one, y, &incy); }\n \n inline double dot(int n, const double *x, int incx, const double *y, int incy=1)\n { return ddot_(&n, x, &incx, y, &incy); }\n \n inline double dot(int n, const double *x, const double *y, int incy=1)\n { const int one=1; return ddot_(&n, x, &one, y, &incy); }\n \n // 2-norm \n \n inline float norm2(int n, const float *x, int incx=1)\n { return snrm2_(&n, x, &incx); }\n \n inline double norm2(int n, const double *x, int incx=1)\n { return dnrm2_(&n, x, &incx); }\n \n // 1-norm (sum of absolute values)\n \n inline float abs_sum(int n, const float *x, int incx=1)\n { return sasum_(&n, x, &incx); }\n \n inline double abs_sum(int n, const double *x, int incx=1)\n { return dasum_(&n, x, &incx); }\n \n // inf-norm (maximum absolute value: index of max returned)\n \n inline int index_abs_max(int n, const float *x, int incx=1)\n { return isamax_(&n, x, &incx)-1; }\n \n inline int index_abs_max(int n, const double *x, int incx=1)\n { return idamax_(&n, x, &incx)-1; }\n \n inline float abs_max(int n, const float *x, int incx=1)\n { return std::fabs(x[isamax_(&n, x, &incx)-1]); }\n \n inline double abs_max(int n, const double *x, int incx=1)\n { return std::fabs(x[idamax_(&n, x, &incx)-1]); }\n \n // swap (actual data exchanged, not just pointers)\n \n inline void swap(int n, float *x, int incx, float *y, int incy=1)\n { sswap_(&n, x, &incx, y, &incy); }\n \n inline void swap(int n, float *x, float *y, int incy=1)\n { const int one=1; sswap_(&n, x, &one, y, &incy); }\n \n inline void swap(int n, double *x, int incx, double *y, int incy=1)\n { dswap_(&n, x, &incx, y, &incy); }\n \n inline void swap(int n, double *x, double *y, int incy=1)\n { const int one=1; dswap_(&n, x, &one, y, &incy); }\n \n // copy (y=x)\n \n inline void copy(int n, const float *x, int incx, float *y, int incy=1)\n { scopy_(&n, x, &incx, y, &incy); }\n \n inline void copy(int n, const float *x, float *y, int incy=1)\n { const int one=1; scopy_(&n, x, &one, y, &incy); }\n \n inline void copy(int n, const double *x, int incx, double *y, int incy=1)\n { dcopy_(&n, x, &incx, y, &incy); }\n \n inline void copy(int n, const double *x, double *y, int incy=1)\n { const int one=1; dcopy_(&n, x, &one, y, &incy); }\n \n // saxpy (y=alpha*x+y)\n \n inline void add_scaled(int n, float alpha, const float *x, int incx, float *y, int incy=1)\n { saxpy_(&n, &alpha, x, &incx, y, &incy); }\n \n inline void add_scaled(int n, float alpha, const float *x, float *y, int incy=1)\n { const int one=1; saxpy_(&n, &alpha, x, &one, y, &incy); }\n \n inline void add_scaled(int n, double alpha, const double *x, int incx, double *y, int incy=1)\n { daxpy_(&n, &alpha, x, &incx, y, &incy); }\n \n inline void add_scaled(int n, double alpha, const double *x, double *y, int incy=1)\n { const int one=1; daxpy_(&n, &alpha, x, &one, y, &incy); }\n \n // scale (x=alpha*x)\n \n inline void scale(int n, float alpha, float *x, int incx=1)\n { sscal_(&n, &alpha, x, &incx); }\n \n inline void scale(int n, double alpha, double *x, int incx=1)\n { dscal_(&n, &alpha, x, &incx); }\n \n // gemv (y=alpha*A*x+beta*y, or using A^T)\n // The matrix is always m*n; the size of x and y depend on if A is transposed.\n \n inline void multiply_matrix_vector(Transpose transpose,\n int m, int n, float alpha, const float *A, int lda,\n const float *x, int incx, float beta, float *y, int incy=1)\n { sgemv_((const char*)&transpose, &m, &n, &alpha, A, &lda, x, &incx, &beta, y, &incy); }\n \n inline void multiply_matrix_vector(int m, int n, const float *A, const float *x, float *y, int incy=1) // y=A*x\n { const int onei=1; const float zero=0, onef=1; sgemv_(\"N\", &m, &n, &onef, A, &m, x, &onei, &zero, y, &incy); }\n \n inline void multiply_matrix_vector(Transpose transpose,\n int m, int n, double alpha, const double *A, int lda,\n const double *x, int incx, double beta, double *y, int incy=1)\n { dgemv_((const char*)&transpose, &m, &n, &alpha, A, &lda, x, &incx, &beta, y, &incy); }\n \n inline void multiply_matrix_vector(int m, int n, const double *A, const double *x, double *y, int incy=1) // y=A*x\n { const int onei=1; const double zero=0, onef=1; dgemv_(\"N\", &m, &n, &onef, A, &m, x, &onei, &zero, y, &incy); }\n \n // gemm (C=alpha*A*B+beta*C)\n \n inline void multiply_matrix_matrix(Transpose transA, Transpose transB,\n int m, int n, int k, float alpha, const float *A, int lda,\n const float *B, int ldb, float beta, float *C, int ldc)\n { sgemm_((const char*)&transA, (const char*)&transB, &m, &n, &k, &alpha, A, &lda, B, &ldb, &beta, C, &ldc); }\n \n inline void multiply_matrix_matrix(int m, int n, int k, const float *A, const float *B, float *C) \n { const float zero=0, one=1; sgemm_(\"N\", \"N\", &m, &n, &k, &one, A, &m, B, &k, &zero, C, &m); } // C=A*B\n \n inline void multiply_matrix_matrix(Transpose transA, Transpose transB,\n int m, int n, int k, double alpha, const double *A, int lda,\n const double *B, int ldb, double beta, double *C, int ldc)\n { dgemm_((const char*)&transA, (const char*)&transB, &m, &n, &k, &alpha, A, &lda, B, &ldb, &beta, C, &ldc); }\n \n inline void multiply_matrix_matrix(int m, int n, int k, const double *A, const double *B, double *C) \n { const double zero=0, one=1; dgemm_(\"N\", \"N\", &m, &n, &k, &one, A, &m, B, &k, &zero, C, &m); } // C=A*B\n \n};\n\n//============================================================================\n#elif defined USE_AMD_BLAS\n\n#include \n\nnamespace BLAS{\n \n enum Transpose {NoTrans='N', Trans='T'};\n enum UpperLower {Upper='U', Lower='L'};\n enum UnitDiag {NonUnit='N', Unit='U'};\n enum Side {Left='L', Right='R'};\n \n // dot products\n \n inline double dot(int n, const float *x, int incx, const float *y, int incy=1)\n { return dsdot(n, (float*)x, incx, (float*)y, incy); }\n \n inline double dot(int n, const float *x, const float *y, int incy=1)\n { return dsdot(n, (float*)x, 1, (float*)y, incy); }\n \n inline float dotf(int n, const float *x, int incx, const float *y, int incy=1)\n { return sdot(n, (float*)x, incx, (float*)y, incy); }\n \n inline float dotf(int n, const float *x, const float *y, int incy=1)\n { return sdot(n, (float*)x, 1, (float*)y, incy); }\n \n inline double dot(int n, const double *x, int incx, const double *y, int incy=1)\n { return ddot(n, (double *)x, incx, (double *)y, incy); }\n \n inline double dot(int n, const double *x, const double *y, int incy=1)\n { return ddot(n, (double *)x, 1, (double *)y, incy); }\n \n // 2-norm \n \n inline float norm2(int n, const float *x, int incx=1)\n { return snrm2(n, (float*)x, incx); }\n \n inline double norm2(int n, const double *x, int incx=1)\n { return dnrm2(n, (double*)x, incx); }\n \n // 1-norm (sum of absolute values)\n \n inline float abs_sum(int n, const float *x, int incx=1)\n { return sasum(n, (float*)x, incx); }\n \n inline double abs_sum(int n, const double *x, int incx=1)\n { return dasum(n, (double*)x, incx); }\n \n // inf-norm (maximum absolute value: index of max returned)\n \n inline int index_abs_max(int n, const float *x, int incx=1)\n { return isamax(n, (float*)x, incx)-1; }\n \n inline int index_abs_max(int n, const double *x, int incx=1)\n { return idamax(n, (double*)x, incx)-1; }\n \n inline float abs_max(int n, const float *x, int incx=1)\n { return std::fabs(x[isamax(n, (float*)x, incx)]-1); }\n \n inline double abs_max(int n, const double *x, int incx=1)\n { return std::fabs(x[idamax(n, (double*)x, incx)]-1); }\n \n // swap (actual data exchanged, not just pointers)\n \n inline void swap(int n, float *x, int incx, float *y, int incy=1)\n { sswap(n, x, incx, y, incy); }\n \n inline void swap(int n, float *x, float *y, int incy=1)\n { sswap(n, x, 1, y, incy); }\n \n inline void swap(int n, double *x, int incx, double *y, int incy=1)\n { dswap(n, x, incx, y, incy); }\n \n inline void swap(int n, double *x, double *y, int incy=1)\n { dswap(n, x, 1, y, incy); }\n \n // copy (y=x)\n \n inline void copy(int n, const float *x, int incx, float *y, int incy=1)\n { scopy(n, (float*)x, incx, y, incy); }\n \n inline void copy(int n, const float *x, float *y, int incy=1)\n { scopy(n, (float*)x, 1, y, incy); }\n \n inline void copy(int n, const double *x, int incx, double *y, int incy=1)\n { dcopy(n, (double *)x, incx, y, incy); }\n \n inline void copy(int n, const double *x, double *y, int incy=1)\n { dcopy(n, (double *)x, 1, y, incy); }\n \n // saxpy (y=alpha*x+y)\n \n inline void add_scaled(int n, float alpha, const float *x, int incx, float *y, int incy=1)\n { saxpy(n, alpha, (float*)x, incx, y, incy); }\n \n inline void add_scaled(int n, float alpha, const float *x, float *y, int incy=1)\n { saxpy(n, alpha, (float*)x, 1, y, incy); }\n \n inline void add_scaled(int n, double alpha, const double *x, int incx, double *y, int incy=1)\n { daxpy(n, alpha, (double*)x, incx, y, incy); }\n \n inline void add_scaled(int n, double alpha, const double *x, double *y, int incy=1)\n { daxpy(n, alpha, (double*)x, 1, y, incy); }\n \n // scale (x=alpha*x)\n \n inline void scale(int n, float alpha, float *x, int incx=1)\n { sscal(n, alpha, x, incx); }\n \n inline void scale(int n, double alpha, double *x, int incx=1)\n { dscal(n, alpha, x, incx); }\n \n // gemv (y=alpha*A*x+beta*y, or using A^T)\n // The matrix is always m*n; the size of x and y depend on if A is transposed.\n \n inline void multiply_matrix_vector(Transpose transpose,\n int m, int n, float alpha, const float *A, int lda,\n const float *x, int incx, float beta, float *y, int incy=1)\n { sgemv(transpose, m, n, alpha, (float*)A, lda, (float*)x, incx, beta, y, incy); }\n \n inline void multiply_matrix_vector(int m, int n, const float *A, const float *x, float *y, int incy=1) // y=A*x\n { sgemv(NoTrans, m, n, 1.f, (float*)A, m, (float*)x, 1, 0.f, y, incy); }\n \n inline void multiply_matrix_vector(Transpose transpose,\n int m, int n, double alpha, const double *A, int lda,\n const double *x, int incx, double beta, double *y, int incy=1)\n { dgemv(transpose, m, n, alpha, (double*)A, lda, (double*)x, incx, beta, y, incy); }\n \n inline void multiply_matrix_vector(int m, int n, const double *A, const double *x, double *y, int incy=1) // y=A*x\n { dgemv(NoTrans, m, n, 1., (double*)A, m, (double*)x, 1, 0., y, incy); }\n \n // gemm (C=alpha*A*B+beta*C)\n \n inline void multiply_matrix_matrix(Transpose transA, Transpose transB,\n int m, int n, int k, float alpha, const float *A, int lda,\n const float *B, int ldb, float beta, float *C, int ldc)\n { sgemm(transA, transB, m, n, k, alpha, (float*)A, lda, (float*)B, ldb, beta, C, ldc); }\n \n inline void multiply_matrix_matrix(int m, int n, int k, const float *A, const float *B, float *C) \n { sgemm(NoTrans, NoTrans, m, n, k, 1.f, (float*)A, m, (float*)B, k, 0.f, C, m); } // C=A*B\n \n inline void multiply_matrix_matrix(Transpose transA, Transpose transB,\n int m, int n, int k, double alpha, const double *A, int lda,\n const double *B, int ldb, double beta, double *C, int ldc)\n { dgemm(transA, transB, m, n, k, alpha, (double*)A, lda, (double*)B, ldb, beta, C, ldc); }\n \n inline void multiply_matrix_matrix(int m, int n, int k, const double *A, const double *B, double *C) \n { dgemm(NoTrans, NoTrans, m, n, k, 1., (double*)A, m, (double*)B, k, 0., C, m); } // C=A*B\n \n};\n\n//============================================================================\n#elif defined USE_CBLAS || defined __APPLE__\n\n#ifdef USE_CBLAS\n#include \n#elif defined __APPLE__\n#include \n#endif\n\nnamespace BLAS{\n \n enum Transpose {NoTrans=CblasNoTrans, Trans=CblasTrans};\n enum UpperLower {Upper=CblasUpper, Lower=CblasLower};\n enum UnitDiag {NonUnit=CblasNonUnit, Unit=CblasUnit};\n enum Side {Left=CblasLeft, Right=CblasRight};\n \n // dot products\n \n inline float dotf(int n, const float *x, int incx, const float *y, int incy=1)\n { return cblas_sdot(n, x, incx, y, incy); }\n \n inline float dotf(int n, const float *x, const float *y, int incy=1)\n { return cblas_sdot(n, x, 1, y, incy); }\n \n inline double dot(int n, const float *x, int incx, const float *y, int incy=1)\n { return cblas_dsdot(n, x, incx, y, incy); }\n \n inline double dot(int n, const float *x, const float *y, int incy=1)\n { return cblas_dsdot(n, x, 1, y, incy); }\n \n inline double dot(int n, const double *x, int incx, const double *y, int incy=1)\n { return cblas_ddot(n, x, incx, y, incy); }\n \n inline double dot(int n, const double *x, const double *y, int incy=1)\n { return cblas_ddot(n, x, 1, y, incy); }\n \n // 2-norm\n \n inline float norm2(int n, const float *x, int incx=1)\n { return cblas_snrm2(n, x, incx); }\n \n inline double norm2(int n, const double *x, int incx=1)\n { return cblas_dnrm2(n, x, incx); }\n \n // 1-norm (sum of absolute values)\n \n inline float abs_sum(int n, const float *x, int incx=1)\n { return cblas_sasum(n, x, incx); }\n \n inline double abs_sum(int n, const double *x, int incx=1)\n { return cblas_dasum(n, x, incx); }\n \n // inf-norm (maximum absolute value)\n \n inline int index_abs_max(int n, const float *x, int incx=1)\n { return cblas_isamax(n, x, incx); }\n \n inline int index_abs_max(int n, const double *x, int incx=1)\n { return cblas_idamax(n, x, incx); }\n \n inline float abs_max(int n, const float *x, int incx=1)\n { return std::fabs(x[cblas_isamax(n, x, incx)]); }\n \n inline double abs_max(int n, const double *x, int incx=1)\n { return std::fabs(x[cblas_idamax(n, x, incx)]); }\n \n // swap (actual data exchanged, not just pointers)\n \n inline void swap(int n, float *x, int incx, float *y, int incy=1)\n { cblas_sswap(n, x, incx, y, incy); }\n \n inline void swap(int n, float *x, float *y, int incy=1)\n { cblas_sswap(n, x, 1, y, incy); }\n \n inline void swap(int n, double *x, int incx, double *y, int incy=1)\n { cblas_dswap(n, x, incx, y, incy); }\n \n inline void swap(int n, double *x, double *y, int incy=1)\n { cblas_dswap(n, x, 1, y, incy); }\n \n // copy (y=x)\n \n inline void copy(int n, const float *x, int incx, float *y, int incy=1)\n { cblas_scopy(n, x, incx, y, incy); }\n \n inline void copy(int n, const float *x, float *y, int incy=1)\n { cblas_scopy(n, x, 1, y, incy); }\n \n inline void copy(int n, const double *x, int incx, double *y, int incy=1)\n { cblas_dcopy(n, x, incx, y, incy); }\n \n inline void copy(int n, const double *x, double *y, int incy=1)\n { cblas_dcopy(n, x, 1, y, incy); }\n \n // saxpy (y=alpha*x+y)\n \n inline void add_scaled(int n, float alpha, const float *x, int incx, float *y, int incy=1)\n { cblas_saxpy(n, alpha, x, incx, y, incy); }\n \n inline void add_scaled(int n, float alpha, const float *x, float *y, int incy=1)\n { cblas_saxpy(n, alpha, x, 1, y, incy); }\n \n inline void add_scaled(int n, double alpha, const double *x, int incx, double *y, int incy=1)\n { cblas_daxpy(n, alpha, x, incx, y, incy); }\n \n inline void add_scaled(int n, double alpha, const double *x, double *y, int incy=1)\n { cblas_daxpy(n, alpha, x, 1, y, incy); }\n \n // scale (x=alpha*x)\n \n inline void scale(int n, float alpha, float *x, int incx=1)\n { cblas_sscal(n, alpha, x, incx); }\n \n inline void scale(int n, double alpha, double *x, int incx=1)\n { cblas_dscal(n, alpha, x, incx); }\n \n // gemv (y=alpha*A*x+beta*y, or using A^T)\n // The matrix is always m*n; the size of x and y depend on if A is transposed.\n \n inline void multiply_matrix_vector(Transpose transpose,\n int m, int n, float alpha, const float *A, int lda,\n const float *x, int incx,\n float beta, float *y, int incy=1)\n { cblas_sgemv(CblasColMajor, (CBLAS_TRANSPOSE)transpose, m, n, alpha, A, lda, x, incx, beta, y, incy); }\n \n inline void multiply_matrix_vector(int m, int n, const float *A, const float *x, float *y, int incy=1) // y=A*x\n { cblas_sgemv(CblasColMajor, CblasNoTrans, m, n, 1.f, A, m, x, 1, 0.f, y, incy); }\n \n inline void multiply_matrix_vector(Transpose transpose,\n int m, int n, double alpha, const double *A, int lda,\n const double *x, int incx, double beta, double *y, int incy=1)\n { cblas_dgemv(CblasColMajor, (CBLAS_TRANSPOSE)transpose, m, n, alpha, A, lda, x, incx, beta, y, incy); }\n \n inline void multiply_matrix_vector(int m, int n, const double *A, const double *x, double *y, int incy=1) // y=A*x\n { cblas_dgemv(CblasColMajor, CblasNoTrans, m, n, 1., A, m, x, 1, 0., y, incy); }\n \n // gemm (C=alpha*A*B+beta*C)\n \n inline void multiply_matrix_matrix(Transpose transA, Transpose transB,\n int m, int n, int k, float alpha, const float *A, int lda,\n const float *B, int ldb, float beta, float *C, int ldc)\n { cblas_sgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); }\n \n inline void multiply_matrix_matrix(int m, int n, int k, const float *A, const float *B, float *C) \n { cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.f, A, m, B, k, 0.f, C, m); } // C=A*B\n \n inline void multiply_matrix_matrix(Transpose transA, Transpose transB,\n int m, int n, int k, double alpha, const double *A, int lda,\n const double *B, int ldb, double beta, double *C, int ldc)\n { cblas_dgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); }\n \n inline void multiply_matrix_matrix(int m, int n, int k, const double *A, const double *B, double *C) \n { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1., A, m, B, k, 0., C, m); } // C=A*B\n \n inline void rank_one_update( int m, int n, double alpha, const double* x, const double* y, double* A )\n {\n cblas_dger( CblasColMajor, m, n, alpha, x, 1, y, 1, A, m );\n }\n \n} // namespace BLAS\n\n\n#endif\n\n// std::vector calls =========================================================\nnamespace BLAS{\n \n template\n inline void set_zero(std::vector &x)\n { set_zero((int)x.size(), &x[0]); }\n \n inline float dotf(const std::vector &x, const std::vector &y)\n { assert(x.size()==y.size()); return dotf((int)x.size(), &x[0], &y[0]); }\n \n inline double dot(const std::vector &x, const std::vector &y)\n { assert(x.size()==y.size()); return dot((int)x.size(), &x[0], &y[0]); }\n \n inline double dot(const std::vector &x, const std::vector &y)\n { assert(x.size()==y.size()); return dot((int)x.size(), &x[0], &y[0]); }\n \n inline float norm2(const std::vector &x)\n { return norm2((int)x.size(), &x[0]); }\n \n inline double norm2(const std::vector &x)\n { return norm2((int)x.size(), &x[0]); }\n \n inline float abs_sum(const std::vector &x)\n { return abs_sum((int)x.size(), &x[0]); }\n \n inline double abs_sum(const std::vector &x)\n { return abs_sum((int)x.size(), &x[0]); }\n \n inline int index_abs_max(const std::vector &x)\n { return index_abs_max((int)x.size(), &x[0]); }\n \n inline int index_abs_max(const std::vector &x)\n { return index_abs_max((int)x.size(), &x[0]); }\n \n inline float abs_max(const std::vector &x)\n { return abs_max((int)x.size(), &x[0]); }\n \n inline double abs_max(const std::vector &x)\n { return abs_max((int)x.size(), &x[0]); }\n \n inline void swap(std::vector &x, std::vector &y)\n { assert(x.size()==y.size()); swap((int)x.size(), &x[0], &y[0]); }\n \n inline void swap(std::vector &x, std::vector &y)\n { assert(x.size()==y.size()); swap((int)x.size(), &x[0], &y[0]); }\n \n inline void copy(const std::vector &x, std::vector &y)\n { assert(x.size()==y.size()); copy((int)x.size(), &x[0], &y[0]); }\n \n inline void copy(const std::vector &x, std::vector &y)\n { assert(x.size()==y.size()); copy((int)x.size(), &x[0], &y[0]); }\n \n inline void add_scaled(float alpha, const std::vector &x, std::vector &y)\n { assert(x.size()==y.size()); add_scaled((int)x.size(), alpha, &x[0], &y[0]); }\n \n inline void add_scaled(double alpha, const std::vector &x, std::vector &y)\n { assert(x.size()==y.size()); add_scaled((int)x.size(), alpha, &x[0], &y[0]); }\n \n inline void scale(float alpha, std::vector &x)\n { scale((int)x.size(), alpha, &x[0]); }\n \n inline void scale(float alpha, std::vector &x)\n { scale((int)x.size(), alpha, &x[0]); }\n \n // I'm not sure if it makes sense to include level 2 or level 3 std::vector versions,\n // since there isn't an STL matrix type...\n \n} // namespace BLAS\n\n#endif\n", "meta": {"hexsha": "e6d13d7f1651d29a225cd21a3b700d126f1a4f57", "size": 26532, "ext": "h", "lang": "C", "max_stars_repo_path": "common/blas_wrapper.h", "max_stars_repo_name": "q349wang/eltopo", "max_stars_repo_head_hexsha": "a63a43d2a890c53f8e0c51034c46ce01ead86564", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2015-01-18T14:44:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T14:59:39.000Z", "max_issues_repo_path": "common/blas_wrapper.h", "max_issues_repo_name": "q349wang/eltopo", "max_issues_repo_head_hexsha": "a63a43d2a890c53f8e0c51034c46ce01ead86564", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-11-04T07:35:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T12:13:17.000Z", "max_forks_repo_path": "common/blas_wrapper.h", "max_forks_repo_name": "q349wang/eltopo", "max_forks_repo_head_hexsha": "a63a43d2a890c53f8e0c51034c46ce01ead86564", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-01-05T18:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T14:59:40.000Z", "avg_line_length": 44.2938230384, "max_line_length": 183, "alphanum_fraction": 0.5823533846, "num_tokens": 8422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.444237373223837}} {"text": "// Copyright (c) 2013-2017 Anton Kozhevnikov, Thomas Schulthess\n// All rights reserved.\n// \n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that \n// the following conditions are met:\n// \n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the \n// following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions \n// and the following disclaimer in the documentation and/or other materials provided with the distribution.\n// \n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED \n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A \n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR \n// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \n// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n/** \\file sbessel.h\n * \n * \\brief Contains implementation of sirius::Spherical_Bessel_functions and sirius::sbessel_approx classes.\n */\n\n#ifndef __SBESSEL_PW_H__\n#define __SBESSEL_PW_H__\n\n#include \n#include \"eigenproblem.h\"\n#include \"Unit_cell/unit_cell.h\"\n\nnamespace sirius\n{\n\n/// Spherical Bessel functions \\f$ j_{\\ell}(q x) \\f$ up to lmax.\nclass Spherical_Bessel_functions\n{\n private:\n int lmax_{-1};\n double q_{0};\n Radial_grid const* rgrid_{nullptr};\n\n std::vector> sbessel_;\n\n public:\n\n Spherical_Bessel_functions()\n {\n }\n\n Spherical_Bessel_functions(int lmax__, Radial_grid const& rgrid__, double q__)\n : lmax_(lmax__)\n , q_(q__)\n , rgrid_(&rgrid__)\n {\n assert(q_ >= 0);\n\n sbessel_ = std::vector>(lmax__ + 2);\n for (int l = 0; l <= lmax__ + 1; l++) {\n sbessel_[l] = Spline(rgrid__);\n }\n\n std::vector jl(lmax__ + 2);\n for (int ir = 0; ir < rgrid__.num_points(); ir++) {\n double t = rgrid__[ir] * q__;\n gsl_sf_bessel_jl_array(lmax__ + 1, t, &jl[0]);\n for (int l = 0; l <= lmax__ + 1; l++) {\n sbessel_[l](ir) = jl[l];\n }\n }\n \n for (int l = 0; l <= lmax__ + 1; l++) {\n sbessel_[l].interpolate();\n }\n }\n\n static void sbessel(int lmax__, double t__, double* jl__)\n {\n gsl_sf_bessel_jl_array(lmax__, t__, jl__);\n }\n\n static void sbessel_deriv_q(int lmax__, double q__, double x__, double* jl_dq__)\n {\n std::vector jl(lmax__ + 2);\n sbessel(lmax__ + 1, x__ * q__, &jl[0]);\n\n for (int l = 0; l <= lmax__; l++) {\n if (q__ != 0) {\n jl_dq__[l] = (l / q__) * jl[l] - x__ * jl[l + 1];\n } else {\n if (l == 1) {\n jl_dq__[l] = x__ / 3;\n } else {\n jl_dq__[l] = 0;\n }\n }\n }\n }\n\n Spline const& operator[](int l__) const\n {\n assert(l__ <= lmax_);\n return sbessel_[l__];\n }\n \n /// Derivative of Bessel function with respect to q.\n /** \\f[\n * \\frac{\\partial j_{\\ell}(q x)}{\\partial q} = \\frac{\\ell}{q} j_{\\ell}(q x) - x j_{\\ell+1}(q x)\n * \\f]\n */\n Spline deriv_q(int l__)\n {\n assert(l__ <= lmax_);\n assert(q_ >= 0);\n Spline s(*rgrid_);\n if (q_ != 0) {\n for (int ir = 0; ir < rgrid_->num_points(); ir++) {\n s(ir) = (l__ / q_) * sbessel_[l__](ir) - (*rgrid_)[ir] * sbessel_[l__ + 1](ir);\n }\n } else {\n if (l__ == 1) {\n for (int ir = 0; ir < rgrid_->num_points(); ir++) {\n s(ir) = (*rgrid_)[ir] / 3;\n }\n }\n }\n s.interpolate();\n return std::move(s);\n }\n};\n\nclass sbessel_approx\n{\n private:\n\n Unit_cell const& unit_cell_;\n\n int lmax_;\n\n mdarray, 2> qnu_;\n mdarray coeffs_; \n\n int nqnu_max_;\n\n static double sbessel_l2norm(double nu, int l, double R)\n {\n if (std::abs(nu) < 1e-10) TERMINATE_NOT_IMPLEMENTED;\n\n if (l == 0)\n {\n return (nu * R * 2 - std::sin(nu * R * 2)) / 4 / std::pow(nu, 3);\n }\n else\n {\n double jl[l + 2];\n gsl_sf_bessel_jl_array(l + 1, R * nu, &jl[0]);\n return std::pow(R, 3) * (jl[l] * jl[l] - jl[l + 1] * jl[l - 1]) / 2;\n }\n }\n\n public:\n\n sbessel_approx(Unit_cell const& unit_cell__,\n int lmax__,\n double const qmin__,\n double const qmax__,\n double const eps__)\n : unit_cell_(unit_cell__),\n lmax_(lmax__)\n {\n PROFILE(\"sirius::sbessel_approx\");\n\n qnu_ = mdarray, 2>(lmax_ + 1, unit_cell_.num_atom_types());\n\n for (int l = 0; l <= lmax_; l++) {\n for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) {\n qnu_(l, iat) = build_approx_freq(qmin__, qmax__, l, unit_cell_.atom_type(iat).mt_radius(), eps__);\n }\n }\n\n nqnu_max_ = 0;\n for (int l = 0; l <= lmax_; l++) {\n for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) {\n nqnu_max_ = std::max(nqnu_max_, static_cast(qnu_(l, iat).size()));\n }\n }\n }\n\n void approximate(std::vector const& q__)\n {\n PROFILE(\"sirius::sbessel_approx::approximate\");\n\n coeffs_ = mdarray(nqnu_max_, q__.size(), lmax_ + 1, unit_cell_.num_atom_types());\n \n #pragma omp parallel for\n for (int l = 0; l <= lmax_; l++)\n {\n for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++)\n {\n int n = nqnu(l, iat);\n\n mdarray A(n, n);\n for (int iq = 0; iq < n; iq++)\n { \n for (int jq = 0; jq <= iq; jq++)\n {\n A(jq, iq) = A(iq, jq) = overlap(qnu_(l, iat)[jq], qnu_(l, iat)[iq], l,\n unit_cell_.atom_type(iat).mt_radius());\n }\n\n for (int j = 0; j < (int)q__.size(); j++)\n {\n if (std::abs(q__[j]) < 1e-12)\n {\n coeffs_(iq, j, l, iat) = 0;\n }\n else\n {\n coeffs_(iq, j, l, iat) = overlap(qnu_(l, iat)[iq], q__[j], l, \n unit_cell_.atom_type(iat).mt_radius());\n }\n }\n }\n linalg::gesv(n, (int)q__.size(), A.at(), A.ld(), &coeffs_(0, 0, l, iat), coeffs_.ld());\n }\n }\n }\n\n inline double qnu(int const iq, int const l, int const iat)\n {\n return qnu_(l, iat)[iq];\n }\n\n inline int nqnu(int const l, int const iat)\n {\n return static_cast(qnu_(l, iat).size());\n }\n\n inline int nqnu_max()\n {\n return nqnu_max_;\n }\n\n inline double coeff(int const iq, int const j, int const l, int const iat)\n {\n return coeffs_(iq, j, l, iat);\n }\n \n // \\int_0^{R} j(nu1 * r) * j(nu2 * r) * r^2 dr\n // this integral can be computed analytically\n static double overlap(double nu1__, double nu2__, int l__, double R__)\n {\n if (std::abs(nu1__) < 1e-10 || std::abs(nu2__) < 1e-10) TERMINATE_NOT_IMPLEMENTED;\n\n if (std::abs(nu1__ - nu2__) < 1e-12)\n {\n if (l__ == 0)\n {\n return (nu2__ * R__ * 2 - std::sin(nu2__ * R__ * 2)) / 4 / std::pow(nu2__, 3);\n }\n else\n {\n double jl[l__ + 2];\n gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &jl[0]);\n return std::pow(R__, 3) * (jl[l__] * jl[l__] - jl[l__ + 1] * jl[l__ - 1]) / 2;\n }\n }\n else\n {\n if (l__ == 0)\n {\n return (nu2__ * std::cos(nu2__ * R__) * std::sin(nu1__ * R__) - nu1__ * std::cos(nu1__ * R__) * std::sin(nu2__ * R__)) /\n (std::pow(nu1__, 3) * nu2__ - nu1__ * std::pow(nu2__, 3));\n }\n else\n {\n double j1[l__ + 2];\n gsl_sf_bessel_jl_array(l__ + 1, R__ * nu1__, &j1[0]);\n\n double j2[l__ + 2];\n gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &j2[0]);\n\n return std::pow(R__, 2) * (nu2__ * j2[l__ - 1] * j1[l__] - nu1__ * j1[l__ - 1] * j2[l__]) / (std::pow(nu1__, 2) - std::pow(nu2__, 2));\n }\n }\n }\n\n std::vector build_approx_freq(double const qmin__,\n double const qmax__,\n int const l__,\n double const R__,\n double const eps__)\n {\n std::vector qnu;\n\n double min_val;\n int n = 2;\n\n do\n {\n n++;\n qnu.resize(n);\n for (int i = 0; i < n; i++) qnu[i] = qmin__ + (qmax__ - qmin__) * i / (n - 1);\n \n dmatrix ovlp(n, n);\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j <= i; j++)\n {\n double o = overlap(qnu[j], qnu[i], l__, R__);\n ovlp(j, i) = o / sbessel_l2norm(qnu[i], l__, R__) / sbessel_l2norm(qnu[j], l__, R__);\n }\n }\n \n std::vector eval(n);\n dmatrix z(n, n);\n\n Eigensolver_lapack solver;\n solver.solve(n, ovlp, &eval[0], z);\n min_val = eval[0];\n\n } while (min_val > eps__);\n\n return qnu;\n }\n};\n\nclass Spherical_Bessel_approximant\n{\n private:\n\n int lmax_;\n\n double R_;\n \n /// List of Bessel function scaling factors for each angular momentum.\n std::vector< std::vector > qnu_;\n\n\n //mdarray coeffs_; \n\n int nqnu_max_;\n\n static double sbessel_l2norm(double nu, int l, double R)\n {\n if (std::abs(nu) < 1e-10)\n {\n if (l == 0) return std::pow(R, 3) / 3.0;\n return 0;\n }\n\n if (l == 0)\n {\n return (nu * R * 2 - std::sin(nu * R * 2)) / 4 / std::pow(nu, 3);\n }\n else\n {\n double jl[l + 2];\n gsl_sf_bessel_jl_array(l + 1, R * nu, &jl[0]);\n return std::pow(R, 3) * (jl[l] * jl[l] - jl[l + 1] * jl[l - 1]) / 2;\n }\n }\n\n public:\n\n Spherical_Bessel_approximant(int lmax__,\n double R__,\n double const qmin__,\n double const qmax__,\n double const eps__)\n : lmax_(lmax__),\n R_(R__)\n {\n PROFILE(\"sirius::Spherical_Bessel_approximant\");\n\n qnu_ = std::vector< std::vector >(lmax_ + 1);\n\n #pragma omp parallel for\n for (int l = 0; l <= lmax_; l++)\n qnu_[l] = build_approx_freq(qmin__, qmax__, l, R_, eps__);\n\n nqnu_max_ = 0;\n for (int l = 0; l <= lmax_; l++)\n nqnu_max_ = std::max(nqnu_max_, nqnu(l));\n }\n\n std::vector approximate(int l__, double nu__)\n {\n int n = nqnu(l__);\n std::vector x(n);\n matrix A(n, n);\n\n for (int iq = 0; iq < n; iq++)\n { \n for (int jq = 0; jq <= iq; jq++)\n {\n A(jq, iq) = A(iq, jq) = overlap(qnu(jq, l__), qnu(iq, l__), l__, R_);\n }\n x[iq] = overlap(qnu(iq, l__), nu__, l__, R_);\n }\n linalg::gesv(n, 1, A.at(), A.ld(), &x[0], n);\n return x;\n }\n\n void approximate(std::vector const& q__)\n {\n //runtime::Timer t(\"sirius::sbessel_approx::approximate\");\n\n //coeffs_ = mdarray(nqnu_max_, q__.size(), lmax_ + 1, unit_cell_.num_atom_types());\n //\n //#pragma omp parallel for\n //for (int l = 0; l <= lmax_; l++)\n //{\n // for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++)\n // {\n // int n = nqnu(l, iat);\n\n // mdarray A(n, n);\n // for (int iq = 0; iq < n; iq++)\n // { \n // for (int jq = 0; jq <= iq; jq++)\n // {\n // A(jq, iq) = A(iq, jq) = overlap(qnu_(l, iat)[jq], qnu_(l, iat)[iq], l,\n // unit_cell_.atom_type(iat).mt_radius());\n // }\n\n // for (int j = 0; j < (int)q__.size(); j++)\n // {\n // if (std::abs(q__[j]) < 1e-12)\n // {\n // coeffs_(iq, j, l, iat) = 0;\n // }\n // else\n // {\n // coeffs_(iq, j, l, iat) = overlap(qnu_(l, iat)[iq], q__[j], l, \n // unit_cell_.atom_type(iat).mt_radius());\n // }\n // }\n // }\n // linalg::gesv(n, (int)q__.size(), A.at(), A.ld(), &coeffs_(0, 0, l, iat), coeffs_.ld());\n // }\n //}\n }\n\n inline double qnu(int const iq, int const l) const\n {\n return qnu_[l][iq];\n }\n\n inline int nqnu(int const l) const\n {\n return static_cast(qnu_[l].size());\n }\n\n inline int nqnu_max() const\n {\n return nqnu_max_;\n }\n\n //inline double coeff(int const iq, int const j, int const l, int const iat)\n //{\n // return coeffs_(iq, j, l, iat);\n //}\n //\n\n // \\int_0^{R} j(nu1 * r) * j(nu2 * r) * r^2 dr\n // this integral can be computed analytically\n static double overlap(double nu1__, double nu2__, int l__, double R__)\n {\n if (std::abs(nu1__) < 1e-10 && std::abs(nu2__) < 1e-10 && l__ == 0) return std::pow(R__, 3) / 3.0;\n\n if ((std::abs(nu1__) < 1e-10 || std::abs(nu2__) < 1e-10) && l__ > 0) return 0;\n\n if ((std::abs(nu1__) < 1e-10 || std::abs(nu2__) < 1e-10) && l__ == 0)\n {\n double nu = std::max(nu1__, nu2__);\n double nuR = nu * R__;\n return (std::sin(nuR) - nuR * std::cos(nuR)) / std::pow(nu, 3);\n }\n\n if (std::abs(nu1__ - nu2__) < 1e-12)\n {\n if (l__ == 0)\n {\n return (nu2__ * R__ * 2 - std::sin(nu2__ * R__ * 2)) / 4 / std::pow(nu2__, 3);\n }\n else\n {\n double jl[l__ + 2];\n gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &jl[0]);\n return std::pow(R__, 3) * (jl[l__] * jl[l__] - jl[l__ + 1] * jl[l__ - 1]) / 2;\n }\n }\n else\n {\n if (l__ == 0)\n {\n return (nu2__ * std::cos(nu2__ * R__) * std::sin(nu1__ * R__) - nu1__ * std::cos(nu1__ * R__) * std::sin(nu2__ * R__)) /\n (std::pow(nu1__, 3) * nu2__ - nu1__ * std::pow(nu2__, 3));\n }\n else\n {\n double j1[l__ + 2];\n gsl_sf_bessel_jl_array(l__ + 1, R__ * nu1__, &j1[0]);\n\n double j2[l__ + 2];\n gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &j2[0]);\n\n return std::pow(R__, 2) * (nu2__ * j2[l__ - 1] * j1[l__] - nu1__ * j1[l__ - 1] * j2[l__]) / (std::pow(nu1__, 2) - std::pow(nu2__, 2));\n }\n }\n TERMINATE(\"this is wrong\");\n return -1;\n }\n\n std::vector build_approx_freq(double const qmin__,\n double const qmax__,\n int const l__,\n double const R__,\n double const eps__)\n {\n std::vector qnu;\n\n double min_val;\n int n = 2;\n\n do\n {\n n++;\n qnu.resize(n);\n for (int i = 0; i < n; i++) qnu[i] = qmin__ + (qmax__ - qmin__) * i / (n - 1);\n \n dmatrix ovlp(n, n);\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j <= i; j++)\n {\n double o = overlap(qnu[j], qnu[i], l__, R__);\n ovlp(j, i) = o / sbessel_l2norm(qnu[i], l__, R__) / sbessel_l2norm(qnu[j], l__, R__);\n }\n }\n \n std::vector eval(n);\n dmatrix z(n, n);\n\n Eigensolver_lapack solver;\n solver.solve(n, ovlp, &eval[0], z);\n min_val = eval[0];\n\n } while (min_val > eps__);\n\n return qnu;\n }\n};\n\nclass Spherical_Bessel_approximant2\n{\n private:\n\n int lmax_;\n\n double R_;\n \n /// List of Bessel function scaling factors for each angular momentum.\n std::vector qnu_;\n\n static double sbessel_l2norm(double nu, int l, double R)\n {\n if (std::abs(nu) < 1e-10)\n {\n if (l == 0) return std::pow(R, 3) / 3.0;\n return 0;\n }\n\n if (l == 0)\n {\n return (nu * R * 2 - std::sin(nu * R * 2)) / 4 / std::pow(nu, 3);\n }\n else\n {\n double jl[l + 2];\n gsl_sf_bessel_jl_array(l + 1, R * nu, &jl[0]);\n return std::pow(R, 3) * (jl[l] * jl[l] - jl[l + 1] * jl[l - 1]) / 2;\n }\n }\n\n public:\n\n Spherical_Bessel_approximant2(int lmax__,\n double R__,\n double const qmin__,\n double const qmax__,\n int nq__)\n : lmax_(lmax__),\n R_(R__)\n {\n PROFILE(\"sirius::Spherical_Bessel_approximant\");\n\n int nq = nfreq(qmin__, qmax__, 0, R__, 1e-12);\n qnu_.resize(nq);\n for (int i = 0; i < nq; i++) qnu_[i] = qmin__ + (qmax__ - qmin__) * i / (nq - 1);\n\n }\n\n std::vector approximate(int l__, double nu__)\n {\n int n = nqnu();\n std::vector x(n);\n matrix A(n, n);\n\n for (int iq = 0; iq < n; iq++)\n { \n for (int jq = 0; jq <= iq; jq++)\n {\n A(jq, iq) = A(iq, jq) = overlap(qnu(jq), qnu(iq), l__, R_);\n }\n x[iq] = overlap(qnu(iq), nu__, l__, R_);\n }\n linalg::gesv(n, 1, A.at(), A.ld(), &x[0], n);\n return x;\n }\n\n inline double qnu(int const iq) const\n {\n return qnu_[iq];\n }\n\n inline int nqnu() const\n {\n return static_cast(qnu_.size());\n }\n\n // \\int_0^{R} j(nu1 * r) * j(nu2 * r) * r^2 dr\n // this integral can be computed analytically\n static double overlap(double nu1__, double nu2__, int l__, double R__)\n {\n if (std::abs(nu1__) < 1e-10 && std::abs(nu2__) < 1e-10 && l__ == 0) return std::pow(R__, 3) / 3.0;\n\n if ((std::abs(nu1__) < 1e-10 || std::abs(nu2__) < 1e-10) && l__ > 0) return 0;\n\n if ((std::abs(nu1__) < 1e-10 || std::abs(nu2__) < 1e-10) && l__ == 0)\n {\n double nu = std::max(nu1__, nu2__);\n double nuR = nu * R__;\n return (std::sin(nuR) - nuR * std::cos(nuR)) / std::pow(nu, 3);\n }\n\n if (std::abs(nu1__ - nu2__) < 1e-12)\n {\n if (l__ == 0)\n {\n return (nu2__ * R__ * 2 - std::sin(nu2__ * R__ * 2)) / 4 / std::pow(nu2__, 3);\n }\n else\n {\n std::vector jl(l__ + 2);\n gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &jl[0]);\n return std::pow(R__, 3) * (jl[l__] * jl[l__] - jl[l__ + 1] * jl[l__ - 1]) / 2;\n }\n }\n else\n {\n if (l__ == 0)\n {\n return (nu2__ * std::cos(nu2__ * R__) * std::sin(nu1__ * R__) - nu1__ * std::cos(nu1__ * R__) * std::sin(nu2__ * R__)) /\n (std::pow(nu1__, 3) * nu2__ - nu1__ * std::pow(nu2__, 3));\n }\n else\n {\n std::vector j1(l__ + 2);\n gsl_sf_bessel_jl_array(l__ + 1, R__ * nu1__, &j1[0]);\n\n std::vector j2(l__ + 2);\n gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &j2[0]);\n\n return std::pow(R__, 2) * (nu2__ * j2[l__ - 1] * j1[l__] - nu1__ * j1[l__ - 1] * j2[l__]) / (std::pow(nu1__, 2) - std::pow(nu2__, 2));\n }\n }\n TERMINATE(\"this is wrong\");\n return -1;\n }\n\n int nfreq(double const qmin__,\n double const qmax__,\n int const l__,\n double const R__,\n double const eps__)\n {\n std::vector qnu;\n\n double min_val;\n int n = 2;\n\n do\n {\n n++;\n qnu.resize(n);\n for (int i = 0; i < n; i++) qnu[i] = qmin__ + (qmax__ - qmin__) * i / (n - 1);\n \n dmatrix ovlp(n, n);\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j <= i; j++)\n {\n double o = overlap(qnu[j], qnu[i], l__, R__);\n ovlp(j, i) = o / sbessel_l2norm(qnu[i], l__, R__) / sbessel_l2norm(qnu[j], l__, R__);\n }\n }\n \n std::vector eval(n);\n dmatrix z(n, n);\n\n Eigensolver_lapack solver;\n solver.solve(n, ovlp, &eval[0], z);\n min_val = eval[0];\n\n if (n > 100) return 100;\n\n } while (min_val > eps__);\n\n return n;\n }\n};\n\n\n};\n\n#endif\n", "meta": {"hexsha": "ad93b931937434fdf4572ed28f2c3e02fc353a59", "size": 24922, "ext": "h", "lang": "C", "max_stars_repo_path": "src/sbessel.h", "max_stars_repo_name": "ckae95/SIRIUS", "max_stars_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sbessel.h", "max_issues_repo_name": "ckae95/SIRIUS", "max_issues_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sbessel.h", "max_forks_repo_name": "ckae95/SIRIUS", "max_forks_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1865569273, "max_line_length": 154, "alphanum_fraction": 0.4068694326, "num_tokens": 6715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.44395896502611676}} {"text": "#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"ccl.h\"\n\ntypedef struct{\n double l;\n ccl_cosmology *cosmo;\n ccl_cl_tracer_collection_t *trc1;\n ccl_cl_tracer_collection_t *trc2;\n ccl_f2d_t *psp;\n int *status;\n} integ_cl_par;\n\n\ntypedef struct{\n int chipow;\n double l1;\n double l2;\n ccl_cosmology *cosmo;\n ccl_cl_tracer_collection_t *trc1;\n ccl_cl_tracer_collection_t *trc2;\n ccl_cl_tracer_collection_t *trc3;\n ccl_cl_tracer_collection_t *trc4;\n ccl_f3d_t *tsp;\n ccl_f1d_t *ker_extra;\n ccl_a_finder *finda;\n int *status;\n} integ_cov_par;\n\nstatic void update_chi_limits(ccl_cl_tracer_collection_t *trc,\n double *chimin, double *chimax,\n int is_union)\n{\n int itr;\n double chimin_h=1E15;\n double chimax_h=-1E15;\n for(itr=0; itr < trc->n_tracers; itr++) {\n if (trc->ts[itr]->chi_min < chimin_h)\n chimin_h = trc->ts[itr]->chi_min;\n if (trc->ts[itr]->chi_max > chimax_h)\n chimax_h = trc->ts[itr]->chi_max;\n }\n\n if(is_union) {\n if(chimin_h < *chimin)\n *chimin = chimin_h;\n if(chimax_h > *chimax)\n *chimax = chimax_h;\n }\n else {\n if(chimin_h > *chimin)\n *chimin = chimin_h;\n if(chimax_h < *chimax)\n *chimax = chimax_h;\n }\n}\n\nstatic void get_k_interval(ccl_cosmology *cosmo,\n ccl_cl_tracer_collection_t *trc1,\n ccl_cl_tracer_collection_t *trc2,\n double l, double *lkmin, double *lkmax) {\n int itr;\n\n // Loop through all tracers and find distance bounds\n double chi_min1 = 1E15;\n double chi_max1 = -1E15;\n for (itr=0; itr < trc1->n_tracers; itr++) {\n if (trc1->ts[itr]->chi_min < chi_min1)\n chi_min1 = trc1->ts[itr]->chi_min;\n if (trc1->ts[itr]->chi_max > chi_max1)\n chi_max1 = trc1->ts[itr]->chi_max;\n }\n\n double chi_min2 = 1E15;\n double chi_max2 = -1E15;\n for (itr=0; itr < trc2->n_tracers; itr++) {\n if (trc2->ts[itr]->chi_min < chi_min2)\n chi_min2 = trc2->ts[itr]->chi_min;\n if (trc2->ts[itr]->chi_max > chi_max2)\n chi_max2 = trc2->ts[itr]->chi_max;\n }\n\n // Find maximum of minima and minimum of maxima\n // (i.e. edges where the product of both kernels will have support).\n double chi_min = fmax(chi_min1, chi_min2);\n double chi_max = fmin(chi_max1, chi_max2);\n\n if (chi_min <= 0)\n chi_min = 0.5*(l+0.5)/cosmo->spline_params.K_MAX;\n\n // Don't go beyond kmax\n *lkmax = log(fmin(cosmo->spline_params.K_MAX, 2*(l+0.5)/chi_min));\n *lkmin = log(fmax(cosmo->spline_params.K_MIN, (l+0.5)/chi_max));\n}\n\nstatic double transfer_limber_single(ccl_cl_tracer_t *tr, double l, double lk,\n double k, double chi_l, double a_l,\n ccl_cosmology *cosmo, ccl_f2d_t *psp,\n int ignore_jbes_deriv,\n int *status) {\n double dd = 0;\n\n // Kernel and transfer evaluated at chi_l\n double w = ccl_cl_tracer_t_get_kernel(tr, chi_l, status);\n double t = ccl_cl_tracer_t_get_transfer(tr, lk,a_l, status);\n double fl = ccl_cl_tracer_t_get_f_ell(tr, l, status);\n\n if (tr->der_bessel < 1) { //We don't need l+1\n dd = w*t;\n if (tr->der_bessel == -1) { //If we divide by (chi*k)^2\n double lp1h = l+0.5;\n dd /= (lp1h*lp1h);\n }\n }\n else { // We will need l+1\n if(ignore_jbes_deriv)\n dd = 0;\n else {\n // Compute chi_{l+1} and a_{l+1}\n double lp1h = l+0.5;\n double lp3h = l+1.5;\n double chi_lp = lp3h/k;\n double a_lp = ccl_scale_factor_of_chi(cosmo, chi_lp, status);\n\n // Compute power spectrum ratio there\n double pk_ratio = fabs(ccl_f2d_t_eval(psp, lk, a_lp, cosmo, status) /\n ccl_f2d_t_eval(psp, lk, a_l, cosmo, status));\n\n // Compute kernel and trasfer at chi_{l+1}\n double w_p = ccl_cl_tracer_t_get_kernel(tr, chi_lp, status);\n double t_p = ccl_cl_tracer_t_get_transfer(tr, lk,a_lp, status);\n\n // sqrt(2l+1/2l+3)\n double sqell = sqrt(lp1h*pk_ratio/lp3h);\n if (tr->der_bessel == 1)\n dd = l*w*t/lp1h-sqell*w_p*t_p;\n else //we assume der_bessel=2 here to avoid extra if clause\n dd = sqell*2*w_p*t_p/lp3h - (0.25+2*l)*w*t/(lp1h*lp1h);\n }\n }\n return dd*fl;\n}\n\nstatic double transfer_limber_wrap(double l,double lk, double k, double chi,\n double a, ccl_cl_tracer_collection_t *trc,\n ccl_cosmology *cosmo,ccl_f2d_t *psp,\n int ignore_jbes_deriv, int *status) {\n int itr;\n double transfer = 0;\n\n for (itr=0; itr < trc->n_tracers; itr++) {\n transfer += transfer_limber_single(\n trc->ts[itr], l, lk, k, chi, a, cosmo, psp, ignore_jbes_deriv, status);\n if (*status != 0)\n return -1;\n }\n return transfer;\n}\n \nstatic double cl_integrand(double lk, void *params) {\n double d1, d2;\n integ_cl_par *p = (integ_cl_par *)params;\n double k = exp(lk);\n double chi = (p->l+0.5)/k;\n double a = ccl_scale_factor_of_chi(p->cosmo, chi, p->status);\n\n d1 = transfer_limber_wrap(p->l, lk, k, chi, a, p->trc1,\n p->cosmo, p->psp, 0, p->status);\n if (d1 == 0)\n return 0;\n\n d2 = transfer_limber_wrap(p->l, lk, k, chi, a, p->trc2,\n p->cosmo, p->psp, 0, p->status);\n\n if (d2 == 0)\n return 0;\n\n double pk = ccl_f2d_t_eval(p->psp, lk, a, p->cosmo, p->status);\n\n return k*pk*d1*d2;\n}\n\nstatic void integ_cls_limber_spline(ccl_cosmology *cosmo,\n\t\t\t\t integ_cl_par *ipar,\n\t\t\t\t double lkmin, double lkmax,\n\t\t\t\t double *result, int *status) {\n int ik;\n int nk = (int)(fmax((lkmax - lkmin) / cosmo->spline_params.DLOGK_INTEGRATION + 0.5,\n\t\t 1))+1;\n double *fk_arr = NULL;\n double *lk_arr = NULL;\n lk_arr = ccl_linear_spacing(lkmin, lkmax, nk);\n if(lk_arr == NULL)\n *status = CCL_ERROR_LOGSPACE;\n\n if(*status == 0) {\n fk_arr = malloc(nk * sizeof(double));\n if(fk_arr == NULL)\n *status = CCL_ERROR_MEMORY;\n }\n\n if(*status == 0) {\n for(ik=0; ikstatus)) {\n\t*status = *(ipar->status);\n\tbreak;\n }\n }\n }\n\n if(*status == 0) {\n ccl_integ_spline(1, nk, lk_arr, &fk_arr,\n 1, -1, result, gsl_interp_akima,\n status);\n }\n free(fk_arr);\n free(lk_arr);\n}\n\nstatic void integ_cls_limber_qag_quad(ccl_cosmology *cosmo,\n\t\t\t\t gsl_function *F,\n\t\t\t\t double lkmin, double lkmax,\n\t\t\t\t gsl_integration_workspace *w,\n\t\t\t\t double *result, double *eresult,\n\t\t\t\t int *status) {\n int gslstatus;\n size_t nevals;\n gsl_integration_cquad_workspace *w_cquad = NULL;\n // Integrate\n gslstatus = gsl_integration_qag(F, lkmin, lkmax, 0,\n\t\t\t\t cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL,\n\t\t\t\t cosmo->gsl_params.N_ITERATION,\n\t\t\t\t cosmo->gsl_params.INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS,\n\t\t\t\t w, result, eresult);\n\n // Test if a round-off error occured in the evaluation of the integral\n // If so, try another integration function, more robust but potentially slower\n if (gslstatus == GSL_EROUND) {\n ccl_raise_gsl_warning(gslstatus,\n\t\t\t \"ccl_cls.c: integ_cls_limber_qag_quad(): \"\n\t\t\t \"Default GSL integration failure, attempting backup method.\");\n w_cquad = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n if (w_cquad == NULL)\n *status = CCL_ERROR_MEMORY;\n\n if (*status == 0) {\n nevals = 0;\n gslstatus = gsl_integration_cquad(F, lkmin, lkmax, 0,\n\t\t\t\t\tcosmo->gsl_params.INTEGRATION_LIMBER_EPSREL,\n\t\t\t\t\tw_cquad, result, eresult, &nevals);\n }\n }\n gsl_integration_cquad_workspace_free(w_cquad);\n if(*status == 0)\n *status = gslstatus;\n}\n\nvoid ccl_angular_cls_limber(ccl_cosmology *cosmo,\n\t\t\t ccl_cl_tracer_collection_t *trc1,\n\t\t\t ccl_cl_tracer_collection_t *trc2,\n\t\t\t ccl_f2d_t *psp,\n\t\t\t int nl_out, double *l_out, double *cl_out,\n\t\t\t ccl_integration_t integration_method,\n\t\t\t int *status) {\n\n // make sure to init core things for safety\n if (!cosmo->computed_distances) {\n *status = CCL_ERROR_DISTANCES_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_cls.c: ccl_angular_cls_limber(): distance splines have not been precomputed!\");\n return;\n }\n\n #pragma omp parallel shared(cosmo, trc1, trc2, l_out, cl_out, \\\n nl_out, status, psp, integration_method) \\\n default(none)\n {\n int clastatus, lind;\n integ_cl_par ipar;\n gsl_integration_workspace *w = NULL;\n int local_status = *status;\n gsl_function F;\n double lkmin, lkmax, l, result, eresult;\n\n if (local_status == 0) {\n // Set up integrating function parameters\n ipar.cosmo = cosmo;\n ipar.trc1 = trc1;\n ipar.trc2 = trc2;\n ipar.psp = psp;\n ipar.status = &clastatus;\n }\n\n if(integration_method == ccl_integration_qag_quad) {\n if (local_status == 0) {\n\tw = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n\tif (w == NULL) {\n\t local_status = CCL_ERROR_MEMORY;\n\t}\n }\n\n if (local_status == 0) {\n\t// Set up integrating function\n\tF.function = &cl_integrand;\n\tF.params = &ipar;\n }\n }\n\n #pragma omp for schedule(dynamic)\n for (lind=0; lind < nl_out; ++lind) {\n if (local_status == 0) {\n l = l_out[lind];\n clastatus = 0;\n ipar.l = l;\n\n // Get integration limits\n get_k_interval(cosmo, trc1, trc2, l, &lkmin, &lkmax);\n\n\t// Integrate\n\tif(integration_method == ccl_integration_qag_quad) {\n\t integ_cls_limber_qag_quad(cosmo, &F, lkmin, lkmax, w,\n\t\t\t\t &result, &eresult, &local_status);\n\t}\n\telse if(integration_method == ccl_integration_spline) {\n\t integ_cls_limber_spline(cosmo, &ipar, lkmin, lkmax,\n\t\t\t\t &result, &local_status);\n\t}\n\telse\n\t local_status = CCL_ERROR_NOT_IMPLEMENTED;\n\n if ((*ipar.status == 0) && (local_status == 0)) {\n cl_out[lind] = result / (l+0.5);\n }\n else {\n ccl_raise_gsl_warning(local_status, \"ccl_cls.c: ccl_angular_cls_limber():\");\n cl_out[lind] = NAN;\n local_status = CCL_ERROR_INTEG;\n }\n }\n }\n\n gsl_integration_workspace_free(w);\n\n if (local_status) {\n #pragma omp atomic write\n *status = local_status;\n }\n }\n\n if (*status) {\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_cls.c: ccl_angular_cls_limber(); integration error\\n\");\n }\n}\n\nvoid ccl_angular_cls_nonlimber(ccl_cosmology *cosmo,\n ccl_cl_tracer_collection_t *trc1,\n ccl_cl_tracer_collection_t *trc2,\n ccl_f2d_t *psp,\n int nl_out, int *l_out, double *cl_out,\n int *status) {\n *status = CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_cls.c: ccl_angular_cls_nonlimber(); non-Limber integrator not implemented yet\\n\");\n}\n\nstatic double cov_integrand(double chi, void *params)\n{\n double d1, d2, d3, d4, tkk, ker=1;\n integ_cov_par *p = (integ_cov_par *)params;\n double k1=(p->l1+0.5)/chi;\n double k2=(p->l2+0.5)/chi;\n double lk1=log(k1);\n double lk2=log(k2);\n double a = ccl_scale_factor_of_chi(p->cosmo, chi, p->status);\n\n d1 = transfer_limber_wrap(p->l1, lk1, k1, chi, a, p->trc1,\n p->cosmo, NULL, 1, p->status);\n if (d1 == 0)\n return 0;\n d2 = transfer_limber_wrap(p->l1, lk1, k1, chi, a, p->trc2,\n p->cosmo, NULL, 1, p->status);\n if (d2 == 0)\n return 0;\n d3 = transfer_limber_wrap(p->l2, lk2, k2, chi, a, p->trc3,\n p->cosmo, NULL, 1, p->status);\n if (d3 == 0)\n return 0;\n d4 = transfer_limber_wrap(p->l2, lk2, k2, chi, a, p->trc4,\n p->cosmo, NULL, 1, p->status);\n if (d4 == 0)\n return 0;\n\n tkk = ccl_f3d_t_eval(p->tsp, lk1, lk2, a,\n p->finda, p->cosmo, p->status);\n if(p->ker_extra!=NULL)\n ker = ccl_f1d_t_eval(p->ker_extra, chi);\n\n return d1*d2*d3*d4*tkk*ker/pow(chi, p->chipow);\n}\n\nstatic void integ_cov_limber_spline(ccl_cosmology *cosmo,\n\t\t\t\t integ_cov_par *ipar,\n\t\t\t\t double chimin, double chimax,\n\t\t\t\t double *result, int *status)\n{\n int ichi;\n int nchi = (int)(fmax((chimax - chimin) / cosmo->spline_params.DCHI_INTEGRATION + 0.5,\n\t\t 1))+1;\n double *fchi_arr = NULL;\n double *chi_arr = NULL;\n chi_arr = ccl_linear_spacing(chimin, chimax, nchi);\n if(chi_arr == NULL)\n *status = CCL_ERROR_LOGSPACE;\n\n if(*status == 0) {\n fchi_arr = malloc(nchi * sizeof(double));\n if(fchi_arr == NULL)\n *status = CCL_ERROR_MEMORY;\n }\n\n if(*status == 0) {\n for(ichi=0; ichistatus)) {\n\t*status = *(ipar->status);\n\tbreak;\n }\n }\n }\n\n if(*status == 0) {\n ccl_integ_spline(1, nchi, chi_arr, &fchi_arr,\n 1, -1, result, gsl_interp_akima,\n status);\n }\n\n free(fchi_arr);\n free(chi_arr);\n}\n\nstatic void integ_cov_limber_qag_quad(ccl_cosmology *cosmo,\n\t\t\t\t gsl_function *F,\n\t\t\t\t double chimin, double chimax,\n\t\t\t\t gsl_integration_workspace *w,\n\t\t\t\t double *result, double *eresult,\n\t\t\t\t int *status) {\n int gslstatus;\n size_t nevals;\n gsl_integration_cquad_workspace *w_cquad = NULL;\n // Integrate\n gslstatus = gsl_integration_qag(F, chimin, chimax, 0,\n\t\t\t\t cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL,\n\t\t\t\t cosmo->gsl_params.N_ITERATION,\n\t\t\t\t cosmo->gsl_params.INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS,\n\t\t\t\t w, result, eresult);\n\n // Test if a round-off error occured in the evaluation of the integral\n // If so, try another integration function, more robust but potentially slower\n if (gslstatus == GSL_EROUND) {\n ccl_raise_gsl_warning(gslstatus,\n\t\t\t \"ccl_cls.c: ccl_angular_cov_limber(): \"\n\t\t\t \"Default GSL integration failure, attempting backup method.\");\n w_cquad = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n if (w_cquad == NULL)\n *status = CCL_ERROR_MEMORY;\n\n if (*status == 0) {\n nevals = 0;\n gslstatus = gsl_integration_cquad(F, chimin, chimax, 0,\n\t\t\t\t\tcosmo->gsl_params.INTEGRATION_LIMBER_EPSREL,\n\t\t\t\t\tw_cquad, result, eresult, &nevals);\n }\n }\n gsl_integration_cquad_workspace_free(w_cquad);\n if(*status == 0)\n *status = gslstatus;\n}\n\nvoid ccl_angular_cl_covariance(ccl_cosmology *cosmo,\n ccl_cl_tracer_collection_t *trc1,\n ccl_cl_tracer_collection_t *trc2,\n ccl_cl_tracer_collection_t *trc3,\n ccl_cl_tracer_collection_t *trc4,\n ccl_f3d_t *tsp,\n int nl1_out, double *l1_out,\n int nl2_out, double *l2_out,\n double *cov_out,\n ccl_integration_t integration_method,\n int chi_exponent, ccl_f1d_t *kernel_extra,\n double prefactor_extra, int *status)\n{\n if(!cosmo->computed_distances) {\n *status = CCL_ERROR_DISTANCES_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_cls.c: ccl_angular_cl_limber(): distance splines have not been precomputed!\");\n return;\n }\n\n #pragma omp parallel shared(cosmo, trc1, trc2, trc3, trc4, tsp, \\\n nl1_out, l1_out, nl2_out, l2_out, cov_out, \\\n integration_method, chi_exponent, \\\n kernel_extra, prefactor_extra, status) \\\n default(none)\n {\n int clastatus, lind1,lind2;\n integ_cov_par ipar;\n gsl_integration_workspace *w = NULL;\n int local_status = *status;\n gsl_function F;\n double chimin, chimax;\n double l1, l2, result, eresult;\n ccl_a_finder *finda = ccl_a_finder_new_from_f3d(tsp);\n \n // Find integration limits\n chimin = 1E15;\n chimax = -1E15;\n update_chi_limits(trc1, &chimin, &chimax, 1);\n update_chi_limits(trc2, &chimin, &chimax, 0);\n update_chi_limits(trc3, &chimin, &chimax, 0);\n update_chi_limits(trc4, &chimin, &chimax, 0);\n \n if (local_status == 0) {\n // Set up integrating function parameters\n ipar.cosmo = cosmo;\n ipar.trc1 = trc1;\n ipar.trc2 = trc2;\n ipar.trc3 = trc3;\n ipar.trc4 = trc4;\n ipar.tsp = tsp;\n ipar.ker_extra = kernel_extra;\n ipar.finda = finda;\n ipar.status = &clastatus;\n ipar.chipow = chi_exponent;\n }\n\n if(integration_method == ccl_integration_qag_quad) {\n if (local_status == 0) {\n\tw = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n\tif (w == NULL) {\n\t local_status = CCL_ERROR_MEMORY;\n\t}\n }\n\n if (local_status == 0) {\n\t// Set up integrating function\n\tF.function = &cov_integrand;\n\tF.params = &ipar;\n }\n }\n\n #pragma omp for schedule(dynamic)\n for (lind1=0; lind1 < nl1_out; ++lind1) {\n l1 = l1_out[lind1];\n ipar.l1 = l1;\n\n for (lind2=0; lind2 < nl2_out; ++lind2) {\n if (local_status == 0) {\n l2 = l2_out[lind2];\n clastatus = 0;\n ipar.l2 = l2;\n\n // Integrate\n if(integration_method == ccl_integration_qag_quad) {\n integ_cov_limber_qag_quad(cosmo, &F, chimin, chimax, w,\n &result, &eresult, &local_status);\n }\n else if(integration_method == ccl_integration_spline) {\n integ_cov_limber_spline(cosmo, &ipar, chimin, chimax,\n &result, &local_status);\n }\n else\n local_status = CCL_ERROR_NOT_IMPLEMENTED;\n\n if ((*ipar.status == 0) && (local_status == 0)) {\n cov_out[lind1+nl1_out*lind2] = result * prefactor_extra;\n }\n else {\n ccl_raise_gsl_warning(local_status, \"ccl_cls.c: ccl_angular_cov_limber():\");\n cov_out[lind1+nl1_out*lind2] = NAN;\n local_status = CCL_ERROR_INTEG;\n }\n }\n }\n }\n\n gsl_integration_workspace_free(w);\n \n if (local_status) {\n #pragma omp atomic write\n *status = local_status;\n }\n ccl_a_finder_free(finda);\n }\n\n if (*status) {\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_cls.c: ccl_angular_cov_limber(); integration error\\n\");\n }\n}\n", "meta": {"hexsha": "a92fe2a457d9a824f37f19ceb29831cd31f8a7c5", "size": 18582, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_cls.c", "max_stars_repo_name": "carlosggarcia/CCL", "max_stars_repo_head_hexsha": "f3fe6383e2cbb804a03ad07e4627de6f226780d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_cls.c", "max_issues_repo_name": "carlosggarcia/CCL", "max_issues_repo_head_hexsha": "f3fe6383e2cbb804a03ad07e4627de6f226780d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccl_cls.c", "max_forks_repo_name": "carlosggarcia/CCL", "max_forks_repo_head_hexsha": "f3fe6383e2cbb804a03ad07e4627de6f226780d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3132137031, "max_line_length": 91, "alphanum_fraction": 0.5998277903, "num_tokens": 5714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4436258745194945}} {"text": "// for license information, see the accompanying LICENSE file\n\n#include \n\n#include \n\n#include \n\n#include \n\n// CBLAS, LAPACKE are f2c translated Netlib F77 reference routines.\n// 'cblas.h' is widely supported, and is the f2c translated Netlib F77 refernce version. \n// There are known issues with name mangling schemes regarding wrapped code and inter-language operability between Fortran and C. \n// \n// Netlib CBLAS / LAPACKE target\n// #define LISE_LA_REF\n// #include \n// #include \n//\n// IBM ESSL target\n// #define LISE_LA_ESSL\n// #include \n//\n// Intel MKL target\n// #define LISE_LA_MKL\n// #include \n\n#ifdef LISE_LA_MKL\n#include \ndouble ddot(const int *, const double *, const int *, const double *, const int *);\nvoid daxpy(const int *, const double *, const double *, const int *, double *, const int *);\nvoid dgemv(const char *, const int *, const int *, const double *, const double *, const int *, const double *, const int *, const double *, double *, const int *);\nvoid dcopy(const int *, const double *, const int *, double *, const int *);\nvoid dgemm(const char *, const char *, const int *, const int *, const int *, const double *, const double *, const int *, const double *, const int *, const double *, double *, const int *);\nvoid dgesdd(const char *, const int *, const int *, double *, const int *, double *, double *, const int *, double *, const int *, double *, const int *, int *, int *);\nvoid dger(const int *, const int *, const double *, const double *, const int *, const double *, const int *, double *, const int *);\n#endif\n\n#ifdef LISE_LA_ESSL\n#include \ndouble ddot(int, const double *, int, const double *,int);\nvoid daxpy(int, double, double *, int, double *, int);\nvoid dgemv(const char *, int, int, double, const void *, int, const double *, int, double, double *, int);\nvoid dcopy(int, double *, int, double *, int);\nvoid dgemm(const char *, const char *, int, int, int, double, const void *, int, const void *, int, double, void *, int);\nvoid dgesdd(const char *, int, int, void *, int, double *, void *, int, void *, int, double *, int, int *, int *);\nvoid dger(int, int, double, const double *, int, const double *, int, void *, int);\n// void dger1(int, int, double, const double *, int, const double *, int, void *, int);\n#endif\n\n#ifdef LISE_LA_REF\n#include \n#include \ndouble cblas_ddot(const int N, const double *X, const int incX, const double *Y, const int incY);\nvoid cblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY);\nvoid cblas_dgemv(CBLAS_LAYOUT layout, CBLAS_TRANSPOSE TransA, const int M, const int N, const double alpha, const double *A, const int lda, const double *X, const int incX, const double beta, double *Y, const int incY);\nvoid cblas_dcopy(const int N, const double *X, const int incX, double *Y, const int incY);\nvoid cblas_dgemm(CBLAS_LAYOUT layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc);\nvoid cblas_dger(CBLAS_LAYOUT layout, const int M, const int N, const double alpha, const double *X, const int incX, const double *Y, const int incY, double *A, const int lda);\nlapack_int LAPACKE_dgesdd( int matrix_layout, char jobz, lapack_int m, lapack_int n, double* a, lapack_int lda, double* s, double* u, lapack_int ldu, double* vt, lapack_int ldvt );\n#endif\n\ndouble ddotII( int * , double * , int * , double * , int * ) ;\nvoid daxpyII( int * , double * , double * , int * , double * , int * ) ;\nint broyden_minB( double * v_in , double * v_in_old , double * f_old , double * b , double * v_out , const int n , int * it_out , const double alpha ) ;\nint broyden_min( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * b_ket , double * d , double * v_out , const int n , int * it_out , const double alpha ) ;\nint broydenMod_min( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * b_ket , double * d , double * v_out , const int n , int * it_out , const double alpha ) ;\n\nvoid broyden_min_( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * b_ket , double * d , double * v_out , int * n , int * it_out , double * alpha ) \n\n{\n broydenMod_min( v_in , v_in_old , f_old , b_bra , b_ket , d , v_out , * n , it_out , * alpha ) ;\n}\n\nvoid broyden_minb_( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * v_out , int * n , int * it_out , double * alpha ) \n\n{\n\n broyden_minB( v_in , v_in_old , f_old , b_bra , v_out , * n , it_out , * alpha ) ;\n\n}\n\nint broyden_min( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * b_ket , double * d , double * v_out , const int n , int * it_out , const double alpha )\n\n{\n\n double * f , * dv , * df ;\n\n int i , ii , it1 ;\n\n int ione = 1 ;\n\n double norm , norm1 , norm2 ;\n\n int n1 , ishift ;\n\n int it ;\n\n it = * it_out ;\n\n n1 = n ;\n\n if( it == 0 )\n\n {\n\n * it_out = 1 ;\n\n for( i = 0 ; i < n ; ++i ) {\n\n\tv_in_old[ i ] = v_in[ i ] ;\n\n\tf_old[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;\n\n\tv_in[ i ] -= f_old[ i ] ;\n\n\tv_out[ i ] = v_in[ i ] ;\n\n }\n\n return( 0 ) ;\n\n }\n\n assert( f = malloc( n * sizeof( double ) ) ) ;\n\n assert( df = malloc( n * sizeof( double ) ) ) ;\n\n assert( dv = malloc( n * sizeof( double ) ) ) ;\n\n it1 = it - 1 ;\n\n ishift = it1 * n ;\n\n norm = 0. ; /* || F || */\n\n norm1 = 0. ; /* || F_old || */\n\n for( i = 0 ; i < n ; i++ )\n\n {\n\n f[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;\n\n norm += f[ i ] * f[ i ] ;\n\n norm1 += f_old[ i ] * f_old[ i ] ;\n\n dv[ i ] = v_in[ i ] - v_in_old[ i ] ;\n\n df[ i ] = f[ i ] - f_old[ i ] ;\n\n b_ket[ ishift + i ] = df[ i ] ;\n\n b_bra[ ishift + i ] = dv[ i ] ;\n\n }\n\n for( ii = 0 ; ii < it1 ; ++ii )\n\n {\n\n#ifdef LISE_LA_MKL\n norm = d[ ii ] * ddot( &n1 , df , &ione , b_bra + ii * n , &ione ) ;\n daxpy( &n1 , &norm , b_ket + ii * n , &ione , b_ket + ishift , &ione ) ;\n norm = d[ ii ] * ddot( &n1 , dv , &ione , b_ket + ii * n , &ione ) ;\n daxpy( &n1 , &norm , b_bra + ii * n , &ione , b_bra + ishift ,&ione ) ;\n#endif\n#ifdef LISE_LA_ESSL\n norm = d[ ii ] * ddot( n1 , df , ione , b_bra + ii * n , ione ) ;\n daxpy( n1 , norm , b_ket + ii * n , ione , b_ket + ishift , ione ) ;\n norm = d[ ii ] * ddot( n1 , dv , ione , b_ket + ii * n , ione ) ;\n daxpy( n1 , norm , b_bra + ii * n , ione , b_bra + ishift ,ione ) ;\n#endif\n#ifdef LISE_LA_REF\n//double cblas_ddot(const int N, const double *X, const int incX, const double *Y, const int incY);\n//void cblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY);\n norm = d[ ii ] * cblas_ddot( n1 , df , ione , b_bra + ii * n , ione ) ;\n cblas_daxpy( n1 , norm , b_ket + ii * n , ione , b_ket + ishift , ione ) ;\n norm = d[ ii ] * cblas_ddot( n1 , dv , ione , b_ket + ii * n , ione ) ;\n cblas_daxpy( n1 , norm , b_bra + ii * n , ione , b_bra + ishift ,ione ) ;\n#endif\n\n }\n\n#ifdef LISE_LA_MKL\n norm = ddot( &n1 , dv , &ione , b_ket + ishift , &ione ) ;\n#endif\n#ifdef LISE_LA_ESSL\n norm = ddot( n1 , dv , ione , b_ket + ishift , ione ) ;\n#endif\n#ifdef LISE_LA_REF\n norm = cblas_ddot( n1 , dv , ione , b_ket + ishift , ione ) ;\n#endif\n\n printf( \" =%12.6e\\n\", norm ) ;\n\n if( fabs( norm ) < 1.e-15 ) return( 0 ) ;\n\n for( i = 0 ; i < n ; ++i )\n\n b_ket[ ishift + i ] = ( dv[ i ] - b_ket[ ishift + i ] ) / norm ;\n\n#ifdef LISE_LA_MKL\n norm1 = sqrt( ddot( &n1 , b_ket + ishift , &ione , b_ket + ishift , &ione ) ) ;\n norm2 = sqrt( ddot( &n1 , b_bra + ishift , &ione , b_bra + ishift , &ione ) ) ;\n#endif\n#ifdef LISE_LA_ESSL\n norm1 = sqrt( ddot( n1 , b_ket + ishift , ione , b_ket + ishift , ione ) ) ;\n norm2 = sqrt( ddot( n1 , b_bra + ishift , ione , b_bra + ishift , ione ) ) ;\n#endif\n#ifdef LISE_LA_REF\n norm1 = sqrt( cblas_ddot( n1 , b_ket + ishift , ione , b_ket + ishift , ione ) ) ;\n norm2 = sqrt( cblas_ddot( n1 , b_bra + ishift , ione , b_bra + ishift , ione ) ) ;\n#endif\n\n for( i = 0 ; i < n ; i++ )\n\n {\n\n b_ket[ ishift + i ] = b_ket[ ishift + i ] / norm1 ;\n\n b_bra[ ishift + i ] = b_bra[ ishift + i ] / norm2 ;\n\n }\n\n d[ it1 ] = norm1 * norm2 ;\n\n for( i = 0 ; i < n ; i++)\n {\n\n v_in_old[ i ] = v_in[ i ] ;\n\n v_in[ i ] -= f[ i ] ;\n\n }\n\n for( ii = 0 ; ii < it ; ii++ )\n\n {\n\n#ifdef LISE_LA_MKL\n norm = - d[ ii ] * ddot( &n1 , b_bra + ii * n , &ione , f , &ione ) ;\n daxpy( &n1 , &norm , b_ket + ii * n , &ione , v_in , &ione ) ;\n#endif\n#ifdef LISE_LA_ESSL\n norm = - d[ ii ] * ddot( n1 , b_bra + ii * n , ione , f , ione ) ;\n daxpy( n1 , norm , b_ket + ii * n , ione , v_in , ione ) ;\n#endif\n#ifdef LISE_LA_REF\n norm = - d[ ii ] * cblas_ddot( n1 , b_bra + ii * n , ione , f , ione ) ;\n cblas_daxpy( n1 , norm , b_ket + ii * n , ione , v_in , ione ) ;\n#endif\n\n }\n\n for( i = 0 ; i < n ; i++ )\n\n {\n\n f_old[ i ] = f[ i ] ;\n\n v_out[ i ] = v_in[ i ] ;\n\n }\n\n ( * it_out ) ++ ;\n\n free( f ) ; free( dv ) ; free( df ) ;\n\n return( 0 ) ;\n\n}\n\nint broyden_minB( double * v_in , double * v_in_old , double * f_old , double * b , double * v_out , const int n , int * it_out , const double alpha )\n\n{\n\n double * f , * dv , * df , * bdf , * bdv ;\n\n int i , ii , it1 ;\n\n int ione = 1 ;\n\n double norm , norm1 , norm2 ;\n\n int n1 , ishift ;\n\n int it , j ;\n\n double * u , * vt , * s , * work , wk_[ 2 ] ;\n\n int lwork = -1 , info , * iwork ;\n\n it = * it_out ;\n\n printf( \"Starting Broyden %d \\n\\n\" , it ) ;\n\n n1 = n ;\n\n if( it == 0 )\n\n {\n\n * it_out = 1 ;\n\n for( i = 0 ; i < n ; ++i ) {\n\n\tv_in_old[ i ] = v_in[ i ] ;\n\n\tf_old[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;\n\n\tv_in[ i ] -= f_old[ i ] ;\n\n\tv_out[ i ] = v_in[ i ] ;\n\n\tfor( j = 0 ; j < n ; j++ )\n\n\t b[ i + n * j ] = 0. ;\n\n\tb[ i + n * i ] = 1. ;\n\n }\n\n return( 0 ) ;\n\n }\n\n assert( f = malloc( n * sizeof( double ) ) ) ;\n\n assert( df = malloc( n * sizeof( double ) ) ) ;\n\n assert( dv = malloc( n * sizeof( double ) ) ) ;\n\n assert( bdv = malloc( n * sizeof( double ) ) ) ;\n\n assert( bdf = malloc( n * sizeof( double ) ) ) ;\n\n it1 = it - 1 ;\n\n ishift = it1 * n ;\n\n for( i = 0 ; i < n ; i++ )\n\n {\n\n f[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;\n\n dv[ i ] = v_in[ i ] - v_in_old[ i ] ;\n\n df[ i ] = f[ i ] - f_old[ i ] ;\n\n }\n\n norm = 0. ;\n\n for( i = 0 ; i < n ; i ++ ) {\n\n bdv[ i ] = 0. ;\n\n bdf[ i ] = dv[ i ] ;\n\n for( j = 0 ; j < n ; j++ ){\n\n bdv[ i ] += b[ j + n * i ] * dv[ j ] ;\n\n bdf[ i ] -= b[ i + n * j ] * df[ j ] ;\n\n }\n\n norm += df[ i ] * bdv[ i ] ;\n\n }\n\n printf( \" =%12.6e\\n\", norm ) ;\n\n norm = 1./norm ;\n\n#ifdef LISE_LA_REF\n cblas_dger( CBLASColMajor, n1 , n1 , norm , bdf , ione , bdv , ione , b , n1 ) ;\n#endif\n#ifdef LISE_LA_ESSL\n dger( n1 , n1 , norm , bdf , ione , bdv , ione , b , n1 ) ;\n#endif\n#ifdef LISE_LA_MKL\n// void dger(const int *, const int *, const double *, const double *, const int *, const double *, const int *, void *, const int *);\n dger( &n1 , &n1 , &norm , bdf , &ione , bdv , &ione , b , &n1 ) ;\n#endif\n\n if( it > 5 ){\n\n /* add a SVD decomposition of matrix B */\n\n assert( s = malloc( n * sizeof( double ) ) ) ;\n\n assert( u = malloc( n * n * sizeof( double ) ) ) ;\n\n assert( vt = malloc( n * n * sizeof( double ) ) ) ;\n\n assert( iwork = malloc( 8 * n * sizeof( double ) ) ) ;\n\n#ifdef LISE_LA_MKL\n dgesdd( \"A\", &n1 , &n1 , b , &n1 , s , u , &n1 , vt , &n1 , wk_ , &lwork , iwork , &info ) ;\n#endif\n#ifdef LISE_LA_ESSL\n dgesdd( \"A\", n1 , n1 , b , n1 , s , u , n1 , vt , n1 , wk_ , lwork , iwork , &info ) ;\n#endif\n#ifdef LISE_LA_REF\n info = LAPACKE_dgesdd(LAPACK_COL_MAJOR, 'A', n1 , n1 , b , n1 , s , u , n1 , vt , n1 ) ; \n#endif\n\n lwork = ( int ) wk_[ 0 ] ;\n\n assert( work = malloc( lwork * sizeof( double ) ) ) ;\n\n#ifdef LISE_LA_ESSL\n dgesdd( \"A\" , n1 , n1 , b , n1 , s , u , n1 , vt , n1 , work , lwork , iwork , &info ) ;\n#endif\n#ifdef LISE_LA_REF\n info = LAPACKE_dgesdd(LAPACK_COL_MAJOR, 'A', n1 , n1 , b , n1 , s , u , n1 , vt , n1 ) ; \n#endif\n#ifdef LISE_LA_MKL\n dgesdd( \"A\", &n1 , &n1 , b , &n1 , s , u , &n1 , vt , &n1 , work , &lwork , iwork , &info ) ;\n#endif\n\n free( work ) ; free( iwork ) ;\n\n for( i = 0 ; i < n ; i++ ){\n\n if( s[ i ] < 1.e-6 ) {\n\n\tprintf( \" s[ %d ] = %g \\n\" , i , s[ i ] ) ;\n\n\ts[ i ] = 0. ;\n\n }\n\n for( j = 0 ; j < n ; j++ )\n\n\tvt[ i + j * n ] *= s[ i ] ;\n\n }\n\n free( s ) ;\n\n norm = 0. ;\n\n norm1 = 1. ;\n \n#ifdef LISE_LA_ESSL\n dgemm( \"N\" , \"N\" , n1 , n1 , n1 , norm1 , u , n1 , vt , n1 , norm , b , n1 ) ;\n#endif\n#ifdef LISE_LA_MKL\n// void dgemm(const char *, const char *, const int *, const int *, const int *, const double *, const double *, const int *, const double *, const int *, const double *, double *, const int *);\n dgemm( \"N\" , \"N\" , &n1 , &n1 , &n1 , &norm1 , u , &n1 , vt , &n1 , &norm , b , &n1 ) ;\n#endif\n#ifdef LISE_LA_REF\n cblas_dgemm(CBLAS_COL_MAJOR,\"N\" , \"N\" , n1 , n1 , n1 , norm1 , u , n1 , vt , n1 , norm , b , n1);\n#endif\n\n free( u ) ; free( vt ) ;\n\n }\n\n#ifdef LISE_LA_ESSL\n dcopy( n1 , v_in , ione , v_in_old , ione ) ;\n#endif\n#ifdef LISE_LA_MKL\n//void dcopy(const int *, const double *, const int *, double *, const int *);\n dcopy( &n1 , v_in , &ione , v_in_old , &ione ) ;\n#endif\n#ifdef LISE_LA_REF\n cblas_dcopy( n1 , v_in , ione , v_in_old , ione ) ;\n#endif\n\n norm1 = -1. ;\n\n norm = 1. ;\n\n#ifdef LISE_LA_MKL\n//void dgemv(const char *, const int *, const int *, const double *, const double *, const int *, const double *, const int *, const double *, double *, const int *);\n dgemv( \"N\" , &n1 , &n1 , &norm1 , b , &n1 , f , &ione , &norm , v_in , &ione ) ;\n#endif\n#ifdef LISE_LA_ESSL\n dgemv( \"N\" , n1 , n1 , norm1 , b , n1 , f , ione , norm , v_in , ione ) ;\n#endif\n#ifdef LISE_LA_REF\n cblas_dgemv(CBLAS_COL_MAJOR, \"N\" , n1 , n1 , norm1 , b , n1 , f , ione , norm , v_in , ione ) ; \n#endif\n\n for( i = 0 ; i < n ; i++ )\n\n {\n\n f_old[ i ] = f[ i ] ;\n\n v_out[ i ] = v_in[ i ] ;\n\n }\n\n ( * it_out ) ++ ;\n\n free( f ) ; free( dv ) ; free( df ) ; free( bdf ) ; free( bdv ) ;\n\n printf( \"Done with Broyden \\n\\n\" ) ;\n\n return( 0 ) ;\n\n}\n\nint broydenMod_min( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * b_ket , double * d , double * v_out , const int n , int * it_out , const double alpha )\n/*\n\nChange in the formula. Use Eq. (10) in J.Chem.Phys. 134 (2011) 134109\n\n */\n\n{\n\n double * f , * dv , * df ;\n\n int i , ii , it1 ;\n\n int ione = 1 ;\n\n double norm , norm1 , norm2 ;\n\n int n1 , ishift ;\n\n int it ;\n\n it = * it_out ;\n\n printf( \"Starting Broyden %d \\n\\n\" , it ) ;\n\n n1 = n ;\n\n if( it == 0 )\n\n {\n\n * it_out = 1 ;\n\n for( i = 0 ; i < n ; ++i ) {\n\n\tv_in_old[ i ] = v_in[ i ] ;\n\n\tf_old[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;\n\n\tv_in[ i ] -= f_old[ i ] ;\n\n\tv_out[ i ] = v_in[ i ] ;\n\n }\n\n return( 0 ) ;\n\n }\n\n assert( f = malloc( n * sizeof( double ) ) ) ;\n\n assert( df = malloc( n * sizeof( double ) ) ) ;\n\n assert( dv = malloc( n * sizeof( double ) ) ) ;\n\n it1 = it - 1 ;\n\n ishift = it1 * n ;\n\n norm = 0. ; /* || F || */\n\n norm1 = 0. ; /* || F_old || */\n\n for( i = 0 ; i < n ; i++ )\n\n {\n\n f[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;\n\n norm += f[ i ] * f[ i ] ;\n\n norm1 += f_old[ i ] * f_old[ i ] ;\n\n dv[ i ] = v_in[ i ] - v_in_old[ i ] ;\n\n df[ i ] = f[ i ] - f_old[ i ] ;\n\n b_ket[ ishift + i ] = df[ i ] ;\n\n b_bra[ ishift + i ] = df[ i ] ;\n\n }\n\n for( ii = 0 ; ii < it1 ; ++ii )\n\n {\n\n#ifdef LISE_LA_MKL\n norm = d[ ii ] * ddot( &n1 , df , &ione , b_bra + ii * n , &ione ) ;\n daxpy( &n1 , &norm , b_ket + ii * n , &ione , b_ket + ishift , &ione ) ;\n#endif\n#ifdef LISE_LA_ESSL \n norm = d[ ii ] * ddot( n1 , df , ione , b_bra + ii * n , ione ) ;\n daxpy( n1 , norm , b_ket + ii * n , ione , b_ket + ishift , ione ) ;\n#endif\n#ifdef LISE_LA_REF\n norm = d[ ii ] * cblas_ddot( n1 , df , ione , b_bra + ii * n , ione ) ;\n cblas_daxpy( n1 , norm , b_ket + ii * n , ione , b_ket + ishift , ione ) ;\n#endif\n\n }\n\n#ifdef LISE_LA_MKL\n norm = ddot( &n1 , df , &ione , df , &ione ) ;\n#endif\n#ifdef LISE_LA_ESSL \n norm = ddot( n1 , df , ione , df , ione ) ;\n#endif\n#ifdef LISE_LA_REF\n norm = cblas_ddot( n1 , df , ione , df , ione ) ;\n#endif\n\n printf( \" =%12.6e\\n\", norm ) ;\n\n for( i = 0 ; i < n ; ++i )\n\n b_ket[ ishift + i ] = ( dv[ i ] - b_ket[ ishift + i ] ) / norm ;\n\n#ifdef LISE_LA_MKL\n norm1 = sqrt( ddot( &n1 , b_ket + ishift , &ione , b_ket + ishift , &ione ) ) ;\n norm2 = sqrt( ddot( &n1 , b_bra + ishift , &ione , b_bra + ishift ,&ione ) ) ;\n#endif\n#ifdef LISE_LA_ESSL\n norm1 = sqrt( ddot( n1 , b_ket + ishift , ione , b_ket + ishift , ione ) ) ;\n norm2 = sqrt( ddot( n1 , b_bra + ishift , ione , b_bra + ishift ,ione ) ) ;\n#endif\n#ifdef LISE_LA_REF\n norm1 = sqrt( cblas_ddot( n1 , b_ket + ishift , ione , b_ket + ishift , ione ) ) ;\n norm2 = sqrt( cblas_ddot( n1 , b_bra + ishift , ione , b_bra + ishift ,ione ) ) ;\n#endif\n\n\n for( i = 0 ; i < n ; i++ )\n\n {\n\n b_ket[ ishift + i ] = b_ket[ ishift + i ] / norm1 ;\n\n b_bra[ ishift + i ] = b_bra[ ishift + i ] / norm2 ;\n\n }\n\n d[ it1 ] = norm1 * norm2 ;\n\n for( i = 0 ; i < n ; i++)\n {\n\n v_in_old[ i ] = v_in[ i ] ;\n\n v_in[ i ] -= f[ i ] ;\n\n }\n\n for( ii = 0 ; ii < it ; ii++ )\n\n {\n\n#ifdef LISE_LA_MKL\n norm = - d[ ii ] * ddot( &n1 , b_bra + ii * n , &ione , f , &ione ) ;\n daxpy( &n1 , &norm , b_ket + ii * n , &ione , v_in , &ione ) ;\n#endif\n#ifdef LISE_LA_ESSL\n norm = - d[ ii ] * ddot( n1 , b_bra + ii * n , ione , f , ione ) ;\n daxpy( n1 , norm , b_ket + ii * n , ione , v_in , ione ) ;\n#endif\n#ifdef LISE_LA_REF\n norm = - d[ ii ] * cblas_ddot( n1 , b_bra + ii * n , ione , f , ione ) ;\n cblas_daxpy( n1 , norm , b_ket + ii * n , ione , v_in , ione ) ;\n#endif\n\n }\n\n for( i = 0 ; i < n ; i++ )\n\n {\n\n f_old[ i ] = f[ i ] ;\n\n v_out[ i ] = v_in[ i ] ;\n\n }\n\n ( * it_out ) ++ ;\n\n free( f ) ; free( dv ) ; free( df ) ;\n\n printf( \"Done with Broyden \\n\\n\" ) ;\n\n return( 0 ) ;\n\n}\n\ndouble ddotII( int * n , double *v1 , int * i1 , double * v2 , int * i2 )\n\n{\n\n double sum = 0. ;\n\n int i ;\n\n for( i = 0 ; i < * n ; i++ )\n\n sum += v1[ i ] * v2[ i ] ;\n\n return( sum ) ;\n\n}\n\nvoid daxpyII( int * n , double * alpha , double * x , int * i1 , double * y , int * i2 ) \n\n{\n\n int i ;\n\n for( i = 0 ; i < * n ; i++ )\n\n y[ i ] += *alpha * x[ i ] ;\n\n}\n", "meta": {"hexsha": "76bcb0ad284fd7d66a31c80fbb71304aafba79ea", "size": 18755, "ext": "c", "lang": "C", "max_stars_repo_path": "LISE-SLDAsolver/broyden_min.c", "max_stars_repo_name": "dmageeLANL/LISE", "max_stars_repo_head_hexsha": "89dfb2ab8456179ad6b97fb6669571799b2bd4f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-07-21T14:58:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T19:14:29.000Z", "max_issues_repo_path": "LISE-SLDAsolver/broyden_min.c", "max_issues_repo_name": "dmageeLANL/LISE", "max_issues_repo_head_hexsha": "89dfb2ab8456179ad6b97fb6669571799b2bd4f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LISE-SLDAsolver/broyden_min.c", "max_forks_repo_name": "dmageeLANL/LISE", "max_forks_repo_head_hexsha": "89dfb2ab8456179ad6b97fb6669571799b2bd4f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-12-24T00:28:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T16:02:10.000Z", "avg_line_length": 25.6917808219, "max_line_length": 254, "alphanum_fraction": 0.5303652359, "num_tokens": 6950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146849, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.443587022304413}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \"parmt_postProcess.h\"\n#include \"beachball.h\"\n#ifdef PARMT_USE_INTEL\n#include \n#else\n#include \n#endif\n#include \"compearth.h\"\n\nstatic void argsort3(const double *__restrict__ x, int *__restrict__ iperm);\nstatic void sortUL(const double *__restrict__ lam,\n const double *__restrict__ U,\n double *__restrict__ lamSort,\n double *__restrict__ Usort);\nstatic void eigenvector2PrincipalAxis(const double eig,\n const double *__restrict__ ev, \n double *__restrict__ paxis);\nstatic void vecstrd(const double str, const double dip, double r[3]);\nstatic double dot3(const double *__restrict__ x,\n const double *__restrict__ y);\nstatic void gemv3(const double *__restrict__ A, const double *__restrict__ x,\n double *__restrict__ y);\nstatic void crossp(const double *__restrict__ u,\n const double *__restrict__ v,\n double *__restrict__ n);\nstatic void strdvec(double r[3], double *str, double *dip);\n\nint postprocess_tnp2beachballPolarity(const int nxp,\n const double xc, const double yc,\n const double rad,\n const double *__restrict__ pAxis,\n const double *__restrict__ nAxis,\n const double *__restrict__ tAxis,\n double *__restrict__ xw1,\n double *__restrict__ yw1,\n int8_t *__restrict__ pn1)\n{\n double ax1[3] __attribute__ ((aligned(64)));\n double ax2[3] __attribute__ ((aligned(64)));\n double ax3[3] __attribute__ ((aligned(64)));\n double rm[9] __attribute__ ((aligned(64)));\n double rmt[9] __attribute__ ((aligned(64)));\n double tm[9] __attribute__ ((aligned(64)));\n double pt[3] __attribute__ ((aligned(64)));\n double ptnew[3] __attribute__ ((aligned(64)));\n double ampMax, az, baz, baz1, bdp, bdp1, bev, bevI, dp,\n dx, dxc, dy, dyc, evI,\n fclvd, fIso, paz, paz1, pdp, pdp1, pev, pevI, plusMin,\n rad2, rpt, rpt2,\n taz, taz1, tdp, tdp1, tev, tevI, theta, x, x0, y, y0;\n int ix, iy, k, nx, ny;\n const double degradi = 180.0/M_PI;\n const double third = 1.0/3.0;\n const double sqrt2 = 1.4142135623730951;\n const double sqrt2i = 1.0/sqrt2;\n taz1 = tAxis[0];\n tdp1 = tAxis[1];\n tevI = tAxis[2];\n baz1 = nAxis[0];\n bdp1 = nAxis[1];\n bevI = nAxis[2];\n paz1 = pAxis[0];\n pdp1 = pAxis[1];\n pevI = pAxis[2];\n // Avoid overwriting memory\n taz = taz1;\n tdp = tdp1;\n baz = baz1;\n bdp = bdp1;\n paz = paz1;\n pdp = pdp1;\n // Step 1: set up axes:\n // - D axis ('dominant' 1-axis - with largest absolute eigenvalue)\n // - M axis ('minor' 3-axis)\n // - B axis ( 2-axis)\n evI = (tevI + bevI + pevI)*third;\n tev = tevI - evI;\n bev = bevI - evI;\n pev = pevI - evI;\n vecstrd(paz, pdp, ax1);\n vecstrd(taz, tdp, ax3);\n fclvd = fabs(bev/pev);\n fIso = evI/pev;\n if (fabs(tev) > fabs(pev))\n {\n vecstrd(taz, tdp, ax1);\n vecstrd(paz, pdp, ax3);\n fclvd = fabs(bev/tev);\n fIso = evI/tev;\n }\n //if (fabs(evI) > .03) \n //{\n // write(6,901) evI\n //}\n crossp(ax1, ax3, ax2);\n strdvec(ax2, &baz, &bdp);\n cliffsNodes_mtensor(taz, tdp, paz, pdp, tevI, bevI, pevI,\n tm, rm, rmt, &Max);\n nx = nxp;\n ny = nxp;\n memset(xw1, 0, (size_t) (nx*ny)*sizeof(double));\n memset(yw1, 0, (size_t) (nx*ny)*sizeof(double));\n memset(pn1, 0, (size_t) (nx*ny)*sizeof(int8_t));\n dx = 2.0*rad/(double) (nx - 1);\n dy = 2.0*rad/(double) (ny - 1);\n x0 = xc - rad;\n y0 = yc - rad;\n rad2 = rad*rad; // saves a sqrt computation when comparing distance\n // loop on pixel grid\n for (iy=0; iy 100.0*DBL_EPSILON*ampMax){pn1[k] = 1;}\n } // end check on location\n } // loop on x\n } // loop on y\n return 0;\n}\n/*!\n * @brief Converts a Tape and Tape 2015 tensor to tension, null, and\n * plunge eigenvectors in USE coordinates for plotting with\n * cliffsnodes\n * @param[in] beta colatitude (radians)\n * @param[in] gamma longitude (radians)\n * @param[in] kappa strike angle (radians)\n * @param[in] sigma slip angle (radians)\n * @param[in] theta dip angle (radians)\n *\n * @param[out] pAxis (azimuth, plunge, eigenvalue) of pressure axis [3]\n * @param[out] nAxis (azimuth, plunge, eigenvalue) of null axis [3]\n * @param[out] tAxis (azimuth, plunge, eigenvalue) of tension axis [3]\n *\n * @result 0 indicate success\n *\n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n */\nint postprocess_tt2tnp(const double beta, const double gamma,\n const double kappa, const double sigma,\n const double theta,\n double *__restrict__ pAxis,\n double *__restrict__ nAxis,\n double *__restrict__ tAxis)\n{\n const double R[9] = {\n 0.7071067811865476, 0.0, -0.7071067811865476,\n -0.4082482904638631, 0.8164965809277261, -0.4082482904638631, \n 0.5773502691896258, 0.5773502691896258, 0.5773502691896258};\n const double Yrot[9] = {\n 0.7071067811865475, 0.0, 0.7071067811865475,\n 0.0, 1.0, 0.0,\n -0.7071067811865475, 0.0, 0.7071067811865475};\n // Convert NWU to USE\n const double Rot[9] = {0, -1, 0, 0, 0, -1, 1, 0, 0};\n //const double RotInv[9] = {0, 0, 1, -1, 0, 0, 0, -1, 0};\n double Zsigma[9], Xtheta[9], Zkappa[9], ZX[9], V[9],\n U[9], Uuse[9], Usort[9], Uw[9],\n lambda[3], v3[3], lamSort[3],\n cosb, cosg, sinb, sing, nKappaDeg, sigmaDeg, thetaDeg;\n const double toDeg = 180.0/M_PI;\n // Compute the eigenvalues from Eqn 7\n sinb = sin(beta);\n sing = sin(gamma);\n cosb = cos(beta);\n cosg = cos(gamma);\n v3[0] = sinb*cosg;\n v3[1] = sinb*sing;\n v3[2] = cosb;\n // Compute R*lam \n lambda[0] = R[0]*v3[0] + R[3]*v3[1] + R[6]*v3[2];\n lambda[1] = R[1]*v3[0] + R[4]*v3[1] + R[7]*v3[2];\n lambda[2] = R[2]*v3[0] + R[5]*v3[1] + R[8]*v3[2];\n // Eqn 9-10\n sigmaDeg = sigma*toDeg;\n thetaDeg = theta*toDeg;\n nKappaDeg =-kappa*toDeg;\n compearth_eulerUtil_rotmat(1, &sigmaDeg, 3, Zsigma);\n compearth_eulerUtil_rotmat(1, &thetaDeg, 1, Xtheta);\n compearth_eulerUtil_rotmat(1, &nKappaDeg, 3, Zkappa);\n //compearth_eulerUtil_rotmatGen(1,-45.0, 2, Yrot);\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n 3, 3, 3, 1.0, Zkappa, 3, Xtheta, 3, 0.0, ZX, 3); \n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n 3, 3, 3, 1.0, ZX, 3, Zsigma, 3, 0.0, V, 3); \n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n 3, 3, 3, 1.0, V, 3, Yrot, 3, 0.0, U, 3);\n // M could be computed by computing M = U*Lambda*inv(U) hence\n // U corresponds to the eigenvectors and lambda the scaling.\n // However, the current basis is NWU which must be converted to USE.\n // If performing a proper rotation of M to M_{use} we would compute:\n // R M inv(R) = R U Lambda inv(U) inv(R) \n // thus what we must be do is transform the eigenvectors into the\n // apropriate frame. Intuitively it is the rotation of each \n // eigenvector (column) of the U matrix which is indeed the matrix\n // matrix multiplication of R*U.\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n 3, 3, 3, 1.0, Rot, 3, U, 3, 0.0, Uuse, 3);\n // If I want to finish this I could compute:\n // R U Lambda inv(U) inv(R) = R U Lambda U^T R^T\n/*\n double lamMat[9], Temp[9], M[9], UtRt[9];\n memset(lamMat, 0, 9*sizeof(double));\n lamMat[0] = lambda[0]; lamMat[4] = lambda[1]; lamMat[8] = lambda[2];\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n 3, 3, 3, 1.0, Uuse, 3, lamMat, 3, 0.0, Temp, 3);\n cblas_dgemm(CblasColMajor, CblasTrans, CblasTrans,\n 3, 3, 3, 1.0, U, 3, Rot, 3, 0.0, UtRt, 3); \n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n 3, 3, 3, 1.0, Temp, 3, UtRt, 3, 0.0, M, 3);\n for (int i=0; i<3; i++)\n {\n for (int j=0; j<3; j++)\n {\n printf(\"%f \", M[3*j+i]);\n }\n printf(\"\\n\");\n }\n*/\n sortUL(lambda, Uuse, lamSort, Usort);\n//printf(\"%f %f %f\\n\", lamSort[0], lamSort[1], lamSort[2]);\n // Compute pressure, null, and tension axes\n eigenvector2PrincipalAxis(lamSort[0], &Usort[0], pAxis);\n eigenvector2PrincipalAxis(lamSort[1], &Usort[3], nAxis);\n eigenvector2PrincipalAxis(lamSort[2], &Usort[6], tAxis);\n // Explosion - simplification (all positive eigenvalues)\n if (lamSort[0] > 0.0)\n {\n pAxis[2] = 1.0;\n nAxis[2] = 1.0;\n tAxis[2] = 1.0;\n }\n // Implosion - simplification (all negative eigenvalues)\n if (lamSort[2] < 0.0)\n {\n pAxis[0] =-1.0;\n nAxis[1] =-1.0;\n tAxis[2] =-1.0;\n }\n //printf(\"%f %f %f\\n\", pAxis[0], pAxis[1], pAxis[2]);\n //printf(\"%f %f %f\\n\", nAxis[0], nAxis[1], nAxis[2]);\n //printf(\"%f %f %f\\n\", tAxis[0], tAxis[1], tAxis[2]);\n return 0;\n}\n\n/*!\n * @brief Convert pressure, null, and tension principal axes to azimuth,\n * plunge, and length.\n */\nstatic void eigenvector2PrincipalAxis(const double eig,\n const double *__restrict__ ev,\n double *__restrict__ paxis)\n{\n const char *fcnm = \"cmopad_Eigenvector2PrincipalAxis\\0\";\n double v[3], az, plunge;\n double twopi = 2.0*M_PI;\n double pi180i = 180.0/M_PI;\n int ierr;\n //------------------------------------------------------------------------// //\n // Compute azimuth and plunge angles where ev is USE coordinates\n plunge = asin(-ev[0]); //arcsin(-z/r)\n az = atan2(ev[2],-ev[1]); //atan(x/y)\n if (plunge <= 0.0)\n { \n plunge =-plunge;\n az = az + M_PI;\n }\n if (az < 0.0){az = az + twopi;} //Shift to [0,360]\n if (az > twopi){az = az - twopi;} //Shift to [0,360]\n // Convert to degrees\n plunge = plunge*pi180i;\n az = az*pi180i;\n // Copy back result\n paxis[0] = az; //First value is azimuth (degrees)\n paxis[1] = plunge; //Second value is plunge (degrees)\n paxis[2] = eig; //Final value is eigenvalue (distance)\n return;\n}\n//===========================================================================//\nstatic void sortUL(const double *__restrict__ lam,\n const double *__restrict__ U,\n double *__restrict__ lamSort,\n double *__restrict__ Usort)\n{\n int perm[3], j;\n argsort3(lam, perm);\n lamSort[0] = lam[perm[0]];\n lamSort[1] = lam[perm[1]];\n lamSort[2] = lam[perm[2]];\n for (j=0; j<3; j++)\n {\n Usort[3*j+0] = U[3*perm[j]+0];\n Usort[3*j+1] = U[3*perm[j]+1];\n Usort[3*j+2] = U[3*perm[j]+2];\n }\n return;\n}\n\n//============================================================================//\n/*!\n * @brief Permutation to sort length 3 array into ascending order\n */\nstatic void argsort3(const double *__restrict__ x, int *__restrict__ iperm)\n{\n const char *fcnm = \"__cmopad_argsort3\\0\";\n int i, temp;\n const int a = 0; \n const int b = 1; \n const int c = 2; \n // Copy\n iperm[a] = a; \n iperm[b] = b; \n iperm[c] = c; \n if (x[iperm[a]] > x[iperm[c]])\n { \n temp = iperm[c];\n iperm[c] = iperm[a];\n iperm[a] = temp;\n } \n if (x[iperm[a]] > x[iperm[b]])\n { \n temp = iperm[b];\n iperm[b] = iperm[a];\n iperm[a] = temp;\n } \n //Now the smallest element is the first one. Just check the 2-nd and 3-rd\n if (x[iperm[b]] > x[iperm[c]])\n { \n temp = iperm[c];\n iperm[c] = iperm[b];\n iperm[b] = temp;\n }\n return;\n}\n//============================================================================//\n/*!\n * @brief Find components of downward pointing unit vector pole from the \n * strike and dip angles. This is based on Cliff Frolich's vecstrd.\n *\n * @param[in] str strike angle of pole (degrees)\n * @param[in] dip dip angle of pole (degrees)\n *\n * @param[out] r corresponding unit vector pole (3)\n *\n * @author Ben Baker\n *\n * @copyright BSD\n * \n */\nstatic void vecstrd(const double str, const double dip, double r[3])\n{\n double cosdip, cosstr, diprad, sindip, sinstr, strrad;\n const double degrad = M_PI/180.0;\n // convert to radians\n strrad = str*degrad;\n diprad = dip*degrad;\n // compute cosines and sines\n sinstr = sin(strrad);\n cosstr = cos(strrad);\n cosdip = cos(diprad);\n sindip = sin(diprad);\n // compute (x,y,z) from strike and dip for unit radius \n r[0] = sinstr*cosdip;\n r[1] = cosstr*cosdip;\n r[2] =-sindip;\n return;\n}\n/*!\n * @brief Utility function for computing dot product of length 3 vector\n */\nstatic double dot3(const double *__restrict__ x,\n const double *__restrict__ y)\n{\n double dot;\n dot = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n return dot;\n}\n/*!\n * @brief Utility function for computing y = Ax for 3 x 3 matrix.\n */\nstatic void gemv3(const double *__restrict__ A, const double *__restrict__ x,\n double *__restrict__ y)\n{\n y[0] = A[0]*x[0] + A[3]*x[1] + A[6]*x[2];\n y[1] = A[1]*x[0] + A[4]*x[1] + A[7]*x[2];\n y[2] = A[2]*x[0] + A[5]*x[1] + A[8]*x[2];\n return;\n}\n/*!\n * @brief Cross product of 2 length 3 vectors u and v. Returns normal vector n.\n * \n * @param[in] u first vector in cross product u x v [3]\n * @param[in] v second vector in cross product u x v [3]\n * \n * @param[out] n normal vector n = u x v [3]\n *\n * @author Ben Baker\n *\n * @copyright BSD\n *\n */\nstatic void crossp(const double *__restrict__ u,\n const double *__restrict__ v,\n double *__restrict__ n)\n{\n n[0] = u[1]*v[2] - u[2]*v[1];\n n[1] = u[2]*v[0] - u[0]*v[2];\n n[2] = u[0]*v[1] - u[1]*v[0];\n return;\n}\n/*!\n * @brief Finds the strike and dip of downward pointing unit vector. This\n * is based on Cliff Frolich's strdvec.\n *\n * @param[in,out] r on input contains the downward pointing unit\n * vector.\n * if r[2] is > 0 then the unit vector is pointing\n * updward. in this case then on output r3 will\n * be negated.\n *\n * @param[out] str strike angle (degrees) \\f$ s.t. \\phi \\in [0,360] \\f$.\n * @param[out] dip dip angle (degrees) \n *\n * @author Ben Baker\n *\n * @copyright BSD\n *\n */\nstatic void strdvec(double r[3], double *str, double *dip)\n{\n double rs;\n const double degradi = 180.0/M_PI;\n if (r[2] > 0.0)\n { \n r[0] =-r[0];\n r[1] =-r[1];\n r[2] =-r[2];\n } \n *str = atan2(r[0], r[1])*degradi;\n if (*str < 0.){*str = *str + 360.;}\n rs = sqrt(r[0]*r[0] + r[1]*r[1]); \n *dip=atan2(-r[2], rs)*degradi;\n return;\n}\n", "meta": {"hexsha": "04a27309bdf28e0da68278f73b4df4974f34c73c", "size": 16380, "ext": "c", "lang": "C", "max_stars_repo_path": "postprocess/tt2beachball.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "postprocess/tt2beachball.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "postprocess/tt2beachball.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4117647059, "max_line_length": 86, "alphanum_fraction": 0.5316239316, "num_tokens": 5400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4432597505880549}} {"text": "/*\n * SPDX-License-Identifier: BSD-3-Clause\n * \n * example_10-StructOfArrays-CellLinkedList-OuterLoop-SymmetricalLoadBalancing.c : \n * Example of SPH Density Calculation using \n * fast neighbor search the main density loop via\n * Cell Linked List method, Struct of Arrays (SoA) \n * data layout, OpenMP parallelization at the \n * cell-pair level, SIMD directives in the kernel\n * and in the inner-most loop. It also implements \n * symmetrical load balancing by moving the parallelism \n * from iterating over cells to iterate over \n * unique pairs of cell (i.e. i\n *\n * Command Line Options: \n * -runs : Set the number of repetitions (runs) for\n * calculating the density. The value of\n * the density is based on the last \n * iteration.\n * Default value: 1\n * -run_seed : Flag to set an alternative seed use for\n * for the PRNG. Instead of feeding seed\n * to the PRNG directly, it feeds \n * seed + iteration, as to generate different\n * configurations for each iteration. \n * Default value: 0 - (possible 0/1)\n * -seed : Set the seed to use for the SPH particles \n * uniform position generation in the box\n * Default value: 123123123\n *\n * -N : Set the number of SPH particles to be used\n * Default value: 1e5 = 100,000\n * -h : Set the value of the smoothing kernel \n * parameter h, which corresponds to half\n * of the support of the kernel. \n * Default value: 0.05\n *\n * -Nx : Set the number of Cells in the X direction\n * Default value: 10\n * -Ny : Set the number of Cells in the Y direction\n * Default value: 10\n * -Nz : Set the number of Cells in the Z direction\n * Default value: 10\n * \n * -Xmin : Set the lower bound in the X direction for \n * the Cell Linked List box \n * Default value: 0.0\n * -Ymin : Set the lower bound in the Y direction for \n * the Cell Linked List box \n * Default value: 0.0\n * -Ymin : Set the lower bound in the Z direction for \n * the Cell Linked List box \n * Default value: 0.0\n * \n * -Xmax : Set the lower bound in the X direction for \n * the Cell Linked List box \n * Default value: 1.0\n * -Ymax : Set the lower bound in the Y direction for \n * the Cell Linked List box \n * Default value: 1.0\n * -Zmax : Set the lower bound in the Z direction for \n * the Cell Linked List box \n * Default value: 1.0\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"sph_data_types.h\"\n#include \"sph_linked_list.h\"\n#include \"sph_utils.h\"\n\n#ifndef M_PI\n#define M_PI (3.14159265358979323846)\n#endif\n\n#define COMPUTE_BLOCKS 5\n\n#define dbg false\n\nint main_loop(int run, bool run_seed, int64_t N, double h, long int seed, \n void *swap_arr,int64_t *temp_hash, linkedListBox *box, SPHparticle *lsph, double *times);\n\nint compute_density_3d_symmetrical_load_ballance(int N, double h, SPHparticle *lsph, linkedListBox *box);\n\nint compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end,\n int64_t nb_begin, int64_t nb_end,double h,\n double* restrict x, double* restrict y,\n double* restrict z, double* restrict nu,\n double* restrict rhoi, double* restrict rhoj);\n\n//void quickSort_int64_t2(int64_t *arr, int64_t low, int64_t high);\n\nvoid quickSort_int64_t_2(int64_t *arr, int64_t low, int64_t high);\n\nvoid mergeSort(int64_t arr[], int64_t l, int64_t r);\n\ndouble w_bspline_3d_constant(double h);\n\n#pragma omp declare simd\ndouble w_bspline_3d_simd(double q);\n\n#define ip_swap(a,b) (b)^=((a)^=((b)^=(a)))\n\nKHASH_MAP_INIT_INT64(2, int64_t)\n\nvoid counting_sort(int64_t N, linkedListBox *box, SPHparticle *lsph,void *swap_arr,int64_t *temp_hash);\n\nint main(int argc, char **argv){\n bool run_seed = false; // By default the behavior is is to use the same seed\n int runs = 1,err; // it only runs once\n long int seed = 123123123; // The default seed is 123123123\n int64_t N = 100000; // The default number of particles is N = 1e5 = 100,000\n double h=0.05; // The default kernel smoothing length is h = 0.05\n linkedListBox *box; // Uninitialized Box containing the cells for the cell linked list method\n SPHparticle *lsph; // Uninitialized array of SPH particles\n\n box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); // Create a box representing the entire 3d domain\n\n // allow for command line customization of the run\n arg_parse(argc,argv,&N,&h,&seed,&runs,&run_seed,box); // Parse the command line options\n // line arguments and override default values\n\n err = SPHparticle_SoA_malloc(N,&lsph);\n if(err)\n fprintf(stderr,\"error in SPHparticle_SoA_malloc\\n\");\n\n void *swap_arr = malloc(N*sizeof(double));\n int64_t *temp_hash = (int64_t*)malloc(2*N*sizeof(int64_t));\n double times[runs*COMPUTE_BLOCKS];\n\n for(int run=0;run : index (or value) or the present iteration\n * run_seed : boolean defining whether to use run index for seed or not\n * N : Number of SPH particles to be used in the run\n * h : Smoothing Length for the Smoothing Kernel w_bspline\n * seed : seed for GSL PRNG generator to generate particle positions\n * box : Box of linked list cells, encapsulating the 3d domain\n * lsph : Array (pointer) of SPH particles to be updated\n * times : Array to store the computation timings to be updated\n * Returns:\n * 0 : error code returned\n * lsph : SPH particle array is updated in the rho field by reference\n * times : Times is updated by reference\n */\n\nint main_loop(int run, bool run_seed, int64_t N, double h, long int seed, \n void *swap_arr, int64_t *temp_hash, linkedListBox *box, SPHparticle *lsph, double *times)\n{\n int err;\n \n if(run_seed)\n err = gen_unif_rdn_pos_box(N,seed+run,box,lsph);\n else\n err = gen_unif_rdn_pos_box(N,seed,box,lsph);\n\n if(err)\n fprintf(stderr,\"error in gen_unif_rdn_pos\\n\");\n\n // ------------------------------------------------------ //\n\n double t0,t1,t2,t3,t4,t5;\n\n t0 = omp_get_wtime();\n\n err = compute_hash_MC3D(N,lsph,box); // Compute Morton Z 3D hash based on the \n if(err) // cell index for each of the X, Y and Z \n fprintf(stderr,\"error in compute_hash_MC3D\\n\"); // directions, in which a given particle reside\n\n t1 = omp_get_wtime();\n \n counting_sort(N,box,lsph,swap_arr,temp_hash);\n\n t2 = omp_get_wtime();\n\n t3 = omp_get_wtime();\n\n t4 = omp_get_wtime();\n\n err = compute_density_3d_symmetrical_load_ballance(N,h,lsph,box); // Compute the density of the particles based\n if(err) // on the cell linked list method for fast \n fprintf(stderr,\"error in compute_density_3d_load_ballanced\\n\"); // neighbor search\n\n // --------------------------------------------------------------- //\n\n t5 = omp_get_wtime();\n\n kh_clear(0, box->hbegin);\n kh_clear(1, box->hend);\n\n times[COMPUTE_BLOCKS*run+0] = t1-t0; // Time for compute morton Z 3d hash\n times[COMPUTE_BLOCKS*run+1] = t2-t1; // Time for sorting the particles' hashes\n times[COMPUTE_BLOCKS*run+2] = t3-t2; // Time for reordering all other arrays accordingly\n times[COMPUTE_BLOCKS*run+3] = t4-t3; // Time for setting up the interval hash tables\n times[COMPUTE_BLOCKS*run+4] = t5-t4; // Time for computing the SPH particle densities\n\n return 0;\n}\n\n/*\n * Function compute_density_3d_symmetrical_load_ballance:\n * Computes the SPH density from the particles using cell linked list with\n * vectorization at the compute_density_3d_chunk level, but the parallelization\n * done at the level of the outer-most loop of the compute_density_3d_cll_outerOmp\n * function, not at the chunk level. \n *\n * The parallelization is done at the level of unique cell pair instead of cells, \n * with the indexes for the cell pairs pre-computed before parallelization. \n * \n * Arguments:\n * N : Number of SPH particles to be used in the run\n * h : Smoothing Length for the Smoothing Kernel w_bspline\n * lsph : Array (pointer) of SPH particles to be updated\n * Returns:\n * 0 : error code returned\n * lsph : SPH particle array is updated in the rho field by reference\n */\nint compute_density_3d_symmetrical_load_ballance(int N, double h, SPHparticle *lsph, linkedListBox *box){\n int64_t *node_begin,*node_end,*nb_begin,*nb_end; // Define the arrays for cell boundaries \n int64_t max_cell_pair_count = 0; // and the number of cell pairs\n const double kernel_constant = w_bspline_3d_constant(h); \n\n max_cell_pair_count = count_box_pairs(box); // compute the maximum number of cell pairs\n \n node_begin = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for node_begin\n node_end = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for node_end\n nb_begin = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for nb_begin\n nb_end = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for nb_end\n\n max_cell_pair_count = setup_unique_box_pairs(box, // set the values for cell pairs\n node_begin,node_end,\n nb_begin,nb_end); \n \n memset(lsph->rho,(int)0,N*sizeof(double)); // Pre-initialize the density to zero\n\n // Parallelism was moved \n // to the level of unique pairs\n #pragma omp parallel for schedule(dynamic,5) proc_bind(master) // Execute in parallel \n for(size_t i=0;ix,lsph->y,lsph->z, // for both node and nb partial density\n lsph->nu,local_rhoi, \n local_rhoj);\n\n // merging the results can result in race conditions, therefore needs to be serialized\n #pragma omp critical // this serializes this code section\n {\n\n for(size_t ii=node_begin[i];iirho[ii] += kernel_constant*local_rhoi[ii-node_begin[i]]; // add the partial density contribution\n }\n \n if(node_begin[i] != nb_begin[i]) // if sender and receiver are different\n for(size_t ii=nb_begin[i];iirho[ii] += kernel_constant*local_rhoj[ii-nb_begin[i]]; // add the partial density contribution\n }\n }\n }\n\n free(node_begin); \n free(node_end);\n free(nb_begin);\n free(nb_end);\n \n return 0;\n}\n\n/*\n * Function compute_density_3d_chunk_symmetrical:\n * Computes the SPH density contribution to both the node_ cell and the nb_ cell. \n * Vectorization in the inner-most loop, but no parallelization. \n * The density contribution is symmetrical. \n * \n * Arguments:\n * N : Number of SPH particles to be used in the run\n * h : Smoothing Length for the Smoothing Kernel w_bspline\n * x : Array of particles' X positions\n * y : Array of particles' Y positions\n * z : Array of particles' Z positions\n * nu : Array of particles' density weights (i.e. masses)\n * Returns:\n * 0 : error code returned\n * rho : Array of particles' densities\n */\nint compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end,\n int64_t nb_begin, int64_t nb_end,double h,\n double* restrict x, double* restrict y,\n double* restrict z, double* restrict nu,\n double* restrict rhoi, double* restrict rhoj){\n const double inv_h = 1./h;\n\n for(int64_t ii=node_begin;ii : Smoothing Length for the Smoothing Kernel w_bspline\n * Returns:\n * 3d bspline normalization density \n */\ndouble w_bspline_3d_constant(double h){ \n return 3./(2.*M_PI*h*h*h); // 3d normalization value for the b-spline kernel\n}\n\n/*\n * Function w_bspline_3d_simd:\n * Returns the un-normalized value of the cubic b-spline SPH smoothing kernel\n * \n * Arguments:\n * q : Distance between particles normalized by the smoothing length h\n * Returns:\n * wq : Unnormalized value of the kernel\n * \n * Observation: \n * Why not else if(q<2.)? \n * Because if you use \"else if\", the compiler refuses to vectorize, \n * This results in a large slowdown, as of 2.5x slower for example_04\n */\n#pragma omp declare simd\ndouble w_bspline_3d_simd(double q){\n double wq=0;\n double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q); // The first polynomial of the spline\n double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); // The second polynomial of the spline\n\n if(q<2.) // If the distance is below 2\n wq = wq2; // Use the 2nd polynomial for the spline \n \n if(q<1.) // If the distance is below 1\n wq = wq1; // Use the 1st polynomial for the spline\n\n return wq; // return which ever value corresponds to the distance\n}\n\nint cmp_int64_t(const void *p,const void *q){\n int64_t *data1,*data2;\n data1 = (int64_t*)p;\n data2 = (int64_t*)q;\n\n if(*data1 < *data2) // data[0] is the hash value, \n return -1; \n else if(*data1 == *data2) // in the unsorted array\n return 0;\n else\n return 1;\n}\n\n#define swap_loop(N,lsph,temp_swap,member,type) for(int64_t i=0;i<(N);i+=1) \\\n (temp_swap)[i] = (lsph)->member[(lsph)->hash[2*i+1]];\\\n memcpy((lsph)->member,temp_swap,(N)*sizeof(type))\n\n/*\n * Function counting_sort:\n * \n * \n * Arguments:\n * N : \n * box :\n * lsph :\n * swap_arr :\n * temp_hash :\n * Returns: \n * box :\n * \n * Observation: \n * Why not else if(q<2.)? \n * Because if you use \"else if\", the compiler refuses to vectorize, \n * This results in a large slowdown, as of 2.5x slower for example_04\n */\nvoid counting_sort(int64_t N, linkedListBox *box, SPHparticle *lsph,void *swap_arr,int64_t *temp_hash){\n\n double t0,t1,t2,t3,t4,t5,t6;\n double t31,t32,t33,t34;\n\n t0 = omp_get_wtime();\n \n for(int64_t i=0;ihbegin, lsph->hash[2*i+0], &ret);\n if(ret==1)\n kh_value(box->hbegin, k) = 1;\n else if(ret==0){\n int64_t val = kh_value(box->hbegin, k);\n kh_value(box->hbegin, k) = val + 1;\n }\n else{\n printf(\"error counting_sort init\");\n return;\n }\n }\n\n t1 = omp_get_wtime();\n\n unsigned int dict_size = kh_size(box->hbegin);\n int64_t hash[dict_size];\n int64_t prefix[dict_size];\n int idx = 0;\n\n for (khiter_t k = kh_begin(box->hbegin); k != kh_end(box->hbegin); ++k){\n if (kh_exist(box->hbegin, k)){\n hash[idx] = kh_key(box->hbegin,k);\n idx+=1;\n }\n }\n\n t2 = omp_get_wtime();\n\n qsort(hash,dict_size,sizeof(int64_t),cmp_int64_t);\n\n t3 = omp_get_wtime();\n\n prefix[0] = 0;\n for(int i=1;ihbegin, hash[i-1]);\n prefix[i] += kh_value(box->hbegin, k);\n }\n\n t31 = omp_get_wtime();\n\n for(int i = 0; i< dict_size;i+=1){\n khiter_t kp = kh_get(0, box->hbegin, hash[i]);\n kh_value(box->hbegin, kp) = prefix[i];\n }\n\n t32 = omp_get_wtime();\n\n for (khiter_t k = kh_begin(box->hbegin); k != kh_end(box->hbegin); ++k){\n if (kh_exist(box->hbegin, k)){\n int ret;\n int64_t hash = kh_key(box->hbegin,k);\n khiter_t ke = kh_put(1, box->hend, hash, &ret);\n kh_value(box->hend, ke) = kh_value(box->hbegin, k);\n }\n }\n\n t33 = omp_get_wtime();\n\n for(int64_t i=0;ihend, lsph->hash[2*i]);\n if (kh_exist(box->hend, kp)){\n lsph->hash[2*i+1] = kh_value(box->hend, kp);\n kh_value(box->hend, kp) += 1;\n }\n else{\n printf(\"there is an issue\\n\");\n }\n }\n\n t34 = omp_get_wtime();\n\n t4 = omp_get_wtime();\n\n for(int64_t i=0;ihash[2*i+1];\n temp_hash[2*idx+0] = lsph->hash[2*i+0];\n temp_hash[2*idx+1] = i;\n }\n\n for(int64_t i=0;ihash[2*i+0] = temp_hash[2*i+0];\n lsph->hash[2*i+1] = temp_hash[2*i+1];\n }\n\n t4 = omp_get_wtime();\n\n int64_t *int64_temp_swap = (int64_t *)swap_arr;\n swap_loop(N,lsph,int64_temp_swap,id ,int64_t);\n double *double_temp_swap = (double *)swap_arr;\n swap_loop(N,lsph,double_temp_swap,nu ,double);\n swap_loop(N,lsph,double_temp_swap,rho,double);\n swap_loop(N,lsph,double_temp_swap,x ,double);\n swap_loop(N,lsph,double_temp_swap,y ,double);\n swap_loop(N,lsph,double_temp_swap,z ,double);\n swap_loop(N,lsph,double_temp_swap,ux ,double);\n swap_loop(N,lsph,double_temp_swap,uy ,double);\n swap_loop(N,lsph,double_temp_swap,uz ,double);\n swap_loop(N,lsph,double_temp_swap,Fx ,double);\n swap_loop(N,lsph,double_temp_swap,Fy ,double);\n swap_loop(N,lsph,double_temp_swap,Fz ,double);\n\n t5 = omp_get_wtime();\n \n for(int64_t i=0;ihash[i] = lsph->hash[2*i];\n\n t6 = omp_get_wtime();\n\n if(dbg){\n printf(\"1: %lf \\n\",t1-t0);\n printf(\"2: %lf \\n\",t2-t1);\n printf(\"3: %lf \\n\",t3-t2);\n printf(\"4: %lf \\n\",t4-t3);\n printf(\" 31: %lf\\n\",t31-t3);\n printf(\" 32: %lf\\n\",t32-t31);\n printf(\" 33: %lf\\n\",t33-t32);\n printf(\" 34: %lf\\n\",t34-t33);\n printf(\" 35: %lf\\n\",t4-t34);\n printf(\"5: %lf \\n\",t5-t4);\n printf(\"6: %lf \\n\",t6-t5);\n }\n\n return;\n}", "meta": {"hexsha": "6ffea1e10a40fd8f8425a9a326156e2728e5d61f", "size": 23489, "ext": "c", "lang": "C", "max_stars_repo_path": "SoA/exec/example_11-StructOfArrays-CellLinkedList-OuterLoop-SymmLB-quickerSort.c", "max_stars_repo_name": "jhelsas/sphalerite", "max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SoA/exec/example_11-StructOfArrays-CellLinkedList-OuterLoop-SymmLB-quickerSort.c", "max_issues_repo_name": "jhelsas/sphalerite", "max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SoA/exec/example_11-StructOfArrays-CellLinkedList-OuterLoop-SymmLB-quickerSort.c", "max_forks_repo_name": "jhelsas/sphalerite", "max_forks_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5682210708, "max_line_length": 121, "alphanum_fraction": 0.5788667036, "num_tokens": 6133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.44317261983126344}} {"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef math_870b373b_c3fb_4c7a_abc7_bc4bd4095aef_h\r\n#define math_870b373b_c3fb_4c7a_abc7_bc4bd4095aef_h\r\n\r\n#include \r\n#include \r\n\r\n#ifndef PI\r\n#define PI (3.14159265358979323846f)\r\n#endif\r\n\r\n__gslib_begin__\r\n\r\nstruct _vec2 { float x, y; };\r\nstruct _vec3 { float x, y, z; };\r\nstruct _vec4 { float x, y, z, w; };\r\nstruct _mat2\r\n{\r\n union\r\n {\r\n struct\r\n {\r\n float _11, _12, \r\n _21, _22;\r\n };\r\n float m[2][2];\r\n };\r\n};\r\nstruct _mat3\r\n{\r\n union\r\n {\r\n struct\r\n {\r\n float _11, _12, _13, \r\n _21, _22, _23, \r\n _31, _32, _33;\r\n };\r\n float m[3][3];\r\n };\r\n};\r\nstruct _mat4\r\n{\r\n union\r\n {\r\n struct \r\n {\r\n float _11, _12, _13, _14, \r\n _21, _22, _23, _24, \r\n _31, _32, _33, _34, \r\n _41, _42, _43, _44;\r\n };\r\n float m[4][4];\r\n };\r\n};\r\nstruct _quat\r\n{\r\n union\r\n {\r\n struct { float x, y, z, w; };\r\n float q[4];\r\n };\r\n};\r\nstruct _plane { float a, b, c, d; };\r\n\r\nstruct viewport\r\n{\r\n int left;\r\n int top;\r\n uint width;\r\n uint height;\r\n float min_depth;\r\n float max_depth;\r\n};\r\n\r\nclass vec2;\r\nclass vec3;\r\nclass vec4;\r\nclass mat3;\r\nclass mat4;\r\nclass quat;\r\nclass plane;\r\n\r\ntypedef vec2 point2;\r\ntypedef vec3 point3;\r\ntypedef mat4 matrix;\r\ntypedef mat3 matrix3;\r\ntypedef _mat2 matrix2;\r\n\r\n/* inline */\r\nfloat vec2length(const vec2* p);\r\nfloat vec2lengthsq(const vec2* p);\r\nfloat vec2dot(const vec2* p1, const vec2* p2);\r\nfloat vec2ccw(const vec2* p1, const vec2* p2);\r\nvec2* vec2add(vec2* out, const vec2* p1, const vec2* p2);\r\nvec2* vec2sub(vec2* out, const vec2* p1, const vec2* p2);\r\nvec2* vec2min(vec2* out, const vec2* p1, const vec2* p2);\r\nvec2* vec2max(vec2* out, const vec2* p1, const vec2* p2);\r\nvec2* vec2scale(vec2* out, const vec2* p, float s);\r\nvec2* vec2lerp(vec2* out, const vec2* p1, const vec2* p2, float s);\r\nfloat vec2lerp_x(const vec2* p1, const vec2* p2, float y);\r\nfloat vec2lerp_y(const vec2* p1, const vec2* p2, float x);\r\nvec2* vec2multiply(vec2* out, const vec2* p, const matrix2* m);\r\nvec2* vec2transformcoord(vec2* out, const vec2* p, const mat3* m);\r\nvec2* vec2transformnormal(vec2* out, const vec2* p, const mat3* m);\r\nfloat vec3length(const vec3* v);\r\nfloat vec3lengthsq(const vec3* v);\r\nfloat vec3dot(const vec3* v1, const vec3* v2);\r\nvec3* vec3cross(vec3* out, const vec3* v1, const vec3* v2);\r\nvec3* vec3add(vec3* out, const vec3* v1, const vec3* v2);\r\nvec3* vec3sub(vec3* out, const vec3* v1, const vec3* v2);\r\nvec3* vec3min(vec3* out, const vec3* v1, const vec3* v2);\r\nvec3* vec3max(vec3* out, const vec3* v1, const vec3* v2);\r\nvec3* vec3scale(vec3* out, const vec3* v, float s);\r\nvec3* vec3lerp(vec3* out, const vec3* v1, const vec3* v2, float s);\r\nvec3* vec3multiply(vec3* out, const vec3* v, const mat3* m);\r\nvec3* vec3project(vec3* out, const vec3* v, const viewport* vp, const matrix* prj, const matrix* view, const matrix* world);\r\nvec3* vec3unproject(vec3* out, const vec3* v, const viewport* vp, const matrix* prj, const matrix* view, const matrix* world);\r\nvec3* vec3projectarray(vec3* out, uint ostride, const vec3* v, uint vstride, const viewport* vp, const matrix* prj, const matrix* view, const matrix* world, uint n);\r\nvec3* vec3unprojectarray(vec3* out, uint ostride, const vec3* v, uint vstride, const viewport* vp, const matrix* prj, const matrix* view, const matrix* world, uint n);\r\nfloat vec4length(const vec4* v);\r\nfloat vec4lengthsq(const vec4* v);\r\nfloat vec4dot(const vec4* v1, const vec4* v2);\r\nvec4* vec4add(vec4* out, const vec4* v1, const vec4* v2);\r\nvec4* vec4sub(vec4* out, const vec4* v1, const vec4* v2);\r\nvec4* vec4min(vec4* out, const vec4* v1, const vec4* v2);\r\nvec4* vec4max(vec4* out, const vec4* v1, const vec4* v2);\r\nvec4* vec4scale(vec4* out, const vec4* v, float s);\r\nvec4* vec4lerp(vec4* out, const vec4* v1, const vec4* v2, float s);\r\nvec4* vec4multiply(vec4* out, const vec4* v, const matrix* m);\r\nmatrix3* mat3identity(matrix3* out);\r\nbool mat3isidentity(const matrix3* m);\r\nfloat mat3determinant(const matrix3* m);\r\nmatrix3* mat3inverse(matrix3* out, float* det, const matrix3* m);\r\nmatrix3* mat3multiply(matrix3* out, const matrix3* m1, const matrix3* m2);\r\nmatrix3* mat3transpose(matrix3* out, const matrix3* m);\r\nmatrix3* mat3scaling(matrix3* out, float sx, float sy);\r\nmatrix3* mat3translation(matrix3* out, float x, float y);\r\nmatrix3* mat3rotation(matrix3* out, float angle);\r\nmatrix3* mat3rotationpos(matrix3* out, const vec2* p, float angle);\r\nmatrix* matidentity(matrix* out);\r\nbool matisidentity(const matrix* m);\r\nbool matdecompose(vec3* scale, quat* rot, vec3* trans, const matrix* m);\r\nmatrix* mattranspose(matrix* out, const matrix* m);\r\nmatrix* matscaling(matrix* out, float sx, float sy, float sz);\r\nmatrix* mattranslation(matrix* out, float x, float y, float z);\r\nmatrix* matrotation_x(matrix* out, float angle);\r\nmatrix* matrotation_y(matrix* out, float angle); \r\nmatrix* matrotation_z(matrix* out, float angle);\r\nmatrix* matrotationaxis(matrix* out, const vec3* v, float angle);\r\nmatrix* matrotationquatern(matrix* out, const quat* q);\r\nmatrix* matrotationeuler(matrix* out, float yaw, float pitch, float roll);\r\nmatrix* matlookatlh(matrix* out, const vec3* eye, const vec3* at, const vec3* up);\r\nmatrix* matlookatrh(matrix* out, const vec3* eye, const vec3* at, const vec3* up);\r\nmatrix* matperspectivelh(matrix* out, float w, float h, float zn, float zf);\r\nmatrix* matperspectiverh(matrix* out, float w, float h, float zn, float zf);\r\nmatrix* matperspectivefovlh(matrix* out, float fovy, float aspect, float zn, float zf);\r\nmatrix* matperspectivefovrh(matrix* out, float fovy, float aspect, float zn, float zf);\r\nmatrix* matperspectiveoffcenterlh(matrix* out, float l, float r, float b, float t, float zn, float zf);\r\nmatrix* matperspectiveoffcenterrh(matrix* out, float l, float r, float b, float t, float zn, float zf);\r\nmatrix* matortholh(matrix* out, float w, float h, float zn, float zf);\r\nmatrix* matorthorh(matrix* out, float w, float h, float zn, float zf);\r\nmatrix* matorthooffcenterlh(matrix* out, float l, float r, float b, float t, float zn, float zf);\r\nmatrix* matorthooffcenterrh(matrix* out, float l, float r, float b, float t, float zn, float zf);\r\nmatrix* matviewportproject(matrix* out, const viewport* vp);\r\nmatrix* matviewportunproject(matrix* out, const viewport* vp);\r\nmatrix* mattransform(matrix* out, const vec3* scalecenter, const quat* scalerot, const vec3* scale, const vec3* rotcenter, const quat* rot, const vec3* trans);\r\nmatrix* mattransform2d(matrix* out, const vec2* scalecenter, float scalerot, const vec2* scale, const vec2* rotcenter, float rot, const vec2* trans);\r\nmatrix* mataffinetransform(matrix* out, float scale, const vec3* rotcenter, const quat* rot, const vec3* trans);\r\nmatrix* mataffinetransform2d(matrix* out, float scale, const vec2* rotcenter, float rot, const vec2* trans);\r\nfloat quatlength(const quat* q);\r\nfloat quatlengthsq(const quat* q);\r\nfloat quatdot(const quat* q1, const quat* q2);\r\nquat* quatidentity(quat* out);\r\nbool quatisidenetity(const quat* q);\r\nquat* quatconjugate(quat* out, const quat* q);\r\nvoid quattoaxisangle(const quat* q, vec3* axis, float* angle);\r\nquat* quatrotatematrix(quat* out, const matrix* m);\r\nquat* quatrotateaxis(quat* out, const vec3* v, float angle);\r\nquat* quatln(quat* out, const quat* q);\r\nquat* quatexp(quat* out, const quat* q);\r\nquat* quatslerp(quat* out, const quat* q1, const quat* q2, float t);\r\nquat* quatsquad(quat* out, const quat* q, const quat* a, const quat* b, const quat* c, float t);\r\nquat* quatbarycentric(quat* out, const quat* q1, const quat* q2, const quat* q3, float f, float g);\r\nvoid quatsquadsetup(quat* a, quat* b, quat* c, const quat* q1, const quat* q2, const quat* q3, const quat* q4);\r\nfloat planedot(const plane* p, const vec4* v);\r\nfloat planedotcoord(const plane* p, const vec3* v);\r\nfloat planedotnormal(const plane* p, const vec3* v);\r\nplane* planescale(plane* out, const plane* p, float s);\r\nplane* planefrompointnormal(plane* out, const vec3* p, const vec3* normal);\r\n\r\n/* non-inline */\r\ntypedef vec2* (__stdcall *fnvec2normalize)(vec2* out, const vec2* v);\r\ntypedef vec2* (__stdcall *fnvec2hermite)(vec2* out, const vec2* p1, const vec2* t1, const vec2* p2, const vec2* t2, float s);\r\ntypedef vec2* (__stdcall *fnvec2catmullrom)(vec2* out, const vec2* p1, const vec2* p2, const vec2* p3, const vec2* p4, float s);\r\ntypedef vec2* (__stdcall *fnvec2barycentric)(vec2* out, const vec2* p1, const vec2* p2, const vec2* p3, float f, float g);\r\ntypedef vec4* (__stdcall *fnvec2transform)(vec4* out, const vec2* p, const matrix* m);\r\ntypedef vec2* (__stdcall *fnvec2transformcoord)(vec2* out, const vec2* p, const matrix* m);\r\ntypedef vec2* (__stdcall *fnvec2transformnormal)(vec2* out, const vec2* p, const matrix* m);\r\ntypedef vec4* (__stdcall *fnvec2transformarray)(vec4* out, uint ostride, const vec2* v, uint vstride, const matrix* m, uint n);\r\ntypedef vec2* (__stdcall *fnvec2transformcoordarray)(vec2* out, uint ostride, const vec2* v, uint vstride, const matrix* m, uint n);\r\ntypedef vec2* (__stdcall *fnvec2transformnormalarray)(vec2* out, uint ostride, const vec2* v, uint vstride, const matrix* m, uint n);\r\ntypedef vec3* (__stdcall *fnvec3normalize)(vec3* out, const vec3* v);\r\ntypedef vec3* (__stdcall *fnvec3hermite)(vec3* out, const vec3* v1, const vec3* t1, const vec3* v2, const vec3* t2, float s);\r\ntypedef vec3* (__stdcall *fnvec3catmullrom)(vec3* out, const vec3* v1, const vec3* v2, const vec3* v3, const vec3* v4, float s);\r\ntypedef vec3* (__stdcall *fnvec3barycentric)(vec3* out, const vec3* v1, const vec3* v2, const vec3* v3, float f, float g);\r\ntypedef vec4* (__stdcall *fnvec3transform)(vec4* out, const vec3* v, const matrix* m);\r\ntypedef vec3* (__stdcall *fnvec3transformcoord)(vec3* out, const vec3* v, const matrix* m);\r\ntypedef vec3* (__stdcall *fnvec3transformnormal)(vec3* out, const vec3* v, const matrix* m);\r\ntypedef vec4* (__stdcall *fnvec3transformarray)(vec4* out, uint ostride, const vec3* v, uint vstride, const matrix* m, uint n);\r\ntypedef vec3* (__stdcall *fnvec3transformcoordarray)(vec3* out, uint ostride, const vec3* v, uint vstride, const matrix* m, uint n);\r\ntypedef vec3* (__stdcall *fnvec3transformnormalarray)(vec3* out, uint ostride, const vec3* v, uint vstride, const matrix* m, uint n);\r\ntypedef vec4* (__stdcall *fnvec4cross)(vec4* out, const vec4* v1, const vec4* v2, const vec4* v3);\r\ntypedef vec4* (__stdcall *fnvec4normalize)(vec4* out, const vec4* v);\r\ntypedef vec4* (__stdcall *fnvec4hermite)(vec4* out, const vec4* v1, const vec4* t1, const vec4* v2, const vec4* t2, float s);\r\ntypedef vec4* (__stdcall *fnvec4catmullrom)(vec4* out, const vec4* v1, const vec4* v2, const vec4* v3, const vec4* v4, float s);\r\ntypedef vec4* (__stdcall *fnvec4barycentric)(vec4* out, const vec4* v1, const vec4* v2, const vec4* v3, float f, float g);\r\ntypedef vec4* (__stdcall *fnvec4transform)(vec4* out, const vec4* v, const matrix* m);\r\ntypedef vec4* (__stdcall *fnvec4transformarray)(vec4* out, uint ostride, const vec4* v, uint vstride, const matrix* m, uint n);\r\ntypedef float (__stdcall *fnmatdeterminant)(const matrix* m);\r\ntypedef matrix* (__stdcall *fnmatmultiply)(matrix* out, const matrix* m1, const matrix* m2);\r\ntypedef matrix* (__stdcall *fnmatmultiplytranspose)(matrix* out, const matrix* m1, const matrix* m2);\r\ntypedef matrix* (__stdcall *fnmatinverse)(matrix* out, float* determinant, const matrix* m);\r\ntypedef matrix* (__stdcall *fnmatshadow)(matrix* out, const vec4* plight, const plane* pln);\r\ntypedef matrix* (__stdcall *fnmatreflect)(matrix* out ,const plane* pln);\r\ntypedef quat* (__stdcall *fnquatrotateeuler)(quat* out, float yaw, float pitch, float roll);\r\ntypedef quat* (__stdcall *fnquatmultiply)(quat* out, const quat* q1, const quat* q2);\r\ntypedef quat* (__stdcall *fnquatnormalize)(quat* out, const quat* q);\r\ntypedef quat* (__stdcall *fnquatinverse)(quat* out, const quat* q);\r\ntypedef plane* (__stdcall *fnplanenormalize)(plane* out, const plane* p);\r\ntypedef vec3* (__stdcall *fnplaneintersectline)(vec3* out, const plane* p, const vec3* v1, const vec3* v2);\r\ntypedef plane* (__stdcall *fnplanefrompoints)(plane* out, const vec3* v1, const vec3* v2, const vec3* v3);\r\ntypedef plane* (__stdcall *fnplanetransform)(plane* out, const plane* p, const matrix* m);\r\ntypedef plane* (__stdcall *fnplanetransformarray)(plane* out, uint ostride, const plane* p, uint pstride, const matrix* m, uint n);\r\n\r\ngs_export extern fnvec2normalize vec2normalize;\r\ngs_export extern fnvec2hermite vec2hermite;\r\ngs_export extern fnvec2catmullrom vec2catmullrom;\r\ngs_export extern fnvec2barycentric vec2barycentric;\r\ngs_export extern fnvec2transform vec2transform;\r\ngs_export extern fnvec2transformarray vec2transformarray;\r\ngs_export extern fnvec2transformcoordarray vec2transformcoordarray;\r\ngs_export extern fnvec2transformnormalarray vec2transformnormalarray;\r\ngs_export extern fnvec3normalize vec3normalize;\r\ngs_export extern fnvec3hermite vec3hermite;\r\ngs_export extern fnvec3catmullrom vec3catmullrom;\r\ngs_export extern fnvec3barycentric vec3barycentric;\r\ngs_export extern fnvec3transform vec3transform;\r\ngs_export extern fnvec3transformcoord vec3transformcoord;\r\ngs_export extern fnvec3transformnormal vec3transformnormal;\r\ngs_export extern fnvec3transformarray vec3transformarray;\r\ngs_export extern fnvec3transformcoordarray vec3transformcoordarray;\r\ngs_export extern fnvec3transformnormalarray vec3transformnormalarray;\r\ngs_export extern fnvec4cross vec4cross;\r\ngs_export extern fnvec4normalize vec4normalize;\r\ngs_export extern fnvec4hermite vec4hermite;\r\ngs_export extern fnvec4catmullrom vec4catmullrom;\r\ngs_export extern fnvec4barycentric vec4barycentric;\r\ngs_export extern fnvec4transform vec4transform;\r\ngs_export extern fnvec4transformarray vec4transformarray;\r\ngs_export extern fnmatdeterminant matdeterminant;\r\ngs_export extern fnmatmultiply matmultiply;\r\ngs_export extern fnmatmultiplytranspose matmultiplytranspose;\r\ngs_export extern fnmatinverse matinverse;\r\ngs_export extern fnmatshadow matshadow;\r\ngs_export extern fnmatreflect matreflect;\r\ngs_export extern fnquatrotateeuler quatrotateeuler;\r\ngs_export extern fnquatmultiply quatmultiply;\r\ngs_export extern fnquatnormalize quatnormalize;\r\ngs_export extern fnquatinverse quatinverse;\r\ngs_export extern fnplanenormalize planenormalize;\r\ngs_export extern fnplaneintersectline planeintersectline;\r\ngs_export extern fnplanefrompoints planefrompoints;\r\ngs_export extern fnplanetransform planetransform;\r\ngs_export extern fnplanetransformarray planetransformarray;\r\n\r\nclass gs_export vec2:\r\n public _vec2\r\n{\r\npublic:\r\n vec2() {}\r\n vec2(const float*);\r\n vec2(float x, float y);\r\n\r\npublic:\r\n operator float*();\r\n operator const float*() const;\r\n\r\npublic:\r\n vec2& operator+=(const vec2&);\r\n vec2& operator-=(const vec2&);\r\n vec2& operator*=(float);\r\n vec2& operator/=(float);\r\n\r\npublic:\r\n vec2 operator+() const;\r\n vec2 operator-() const;\r\n\r\npublic:\r\n vec2 operator+(const vec2&) const;\r\n vec2 operator-(const vec2&) const;\r\n vec2 operator*(float) const;\r\n vec2 operator/(float) const;\r\n friend vec2 operator*(float, const vec2&);\r\n\r\npublic:\r\n bool operator==(const vec2&) const;\r\n bool operator!=(const vec2&) const;\r\n\r\npublic:\r\n float length() const { return vec2length(this); }\r\n float lengthsq() const { return vec2lengthsq(this); }\r\n float dot(const vec2& v) const { return vec2dot(this, &v); }\r\n float ccw(const vec2& v) const { return vec2ccw(this, &v); }\r\n vec2& add(const vec2& p1, const vec2& p2) { return *vec2add(this, &p1, &p2); }\r\n vec2& sub(const vec2& p1, const vec2& p2) { return *vec2sub(this, &p1, &p2); }\r\n vec2& scale(float s) { return *vec2scale(this, this, s); }\r\n vec2& scale(const vec2& v, float s) { return *vec2scale(this, &v, s); }\r\n vec2& lerp(const vec2& p1, const vec2& p2, float s) { return *vec2lerp(this, &p1, &p2, s); }\r\n vec2& multiply(const matrix2& m) { return *vec2multiply(this, this, &m); }\r\n vec2& multiply(const vec2& p, const matrix2& m) { return *vec2multiply(this, &p, &m); }\r\n vec2& normalize() { return *vec2normalize(this, this); }\r\n vec2& normalize(const vec2& v) { return *vec2normalize(this, &v); }\r\n vec2& hermite(const vec2& p1, const vec2& t1, const vec2& p2, const vec2& t2, float s) { return *vec2hermite(this, &p1, &t1, &p2, &t2, s); }\r\n vec2& catmullrom(const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4, float s) { return *vec2catmullrom(this, &p1, &p2, &p3, &p4, s); }\r\n vec2& barycentric(const vec2& p1, const vec2& p2, const vec2& p3, float f, float g) { return *vec2barycentric(this, &p1, &p2, &p3, f, g); }\r\n vec4& transform(vec4& v, const matrix& m) const { return *vec2transform(&v, this, &m); }\r\n vec2& transformcoord(const mat3& m) { return *vec2transformcoord(this, this, &m); }\r\n vec2& transformcoord(const vec2& p, const mat3& m) { return *vec2transformcoord(this, &p, &m); }\r\n vec2& transformnormal(const mat3& m) { return *vec2transformnormal(this, this, &m); }\r\n vec2& transformnormal(const vec2& p, const mat3& m) { return *vec2transformnormal(this, &p, &m); }\r\n};\r\n\r\nclass gs_export vec3:\r\n public _vec3\r\n{\r\npublic:\r\n vec3() {}\r\n vec3(const float*);\r\n vec3(float x, float y, float z);\r\n\r\npublic:\r\n operator float*();\r\n operator const float*() const;\r\n\r\npublic:\r\n vec3& operator+=(const vec3&);\r\n vec3& operator-=(const vec3&);\r\n vec3& operator*=(float);\r\n vec3& operator/=(float);\r\n\r\npublic:\r\n vec3 operator+() const;\r\n vec3 operator-() const;\r\n\r\npublic:\r\n vec3 operator+(const vec3&) const;\r\n vec3 operator-(const vec3&) const;\r\n vec3 operator*(float) const;\r\n vec3 operator/(float) const;\r\n friend vec3 operator*(float, const vec3&);\r\n\r\npublic:\r\n bool operator==(const vec3&) const;\r\n bool operator!=(const vec3&) const;\r\n\r\npublic:\r\n float length() const { return vec3length(this); }\r\n float lengthsq() const { return vec3lengthsq(this); }\r\n float dot(const vec3& v) const { return vec3dot(this, &v); }\r\n vec3& add(const vec3& v1, const vec3& v2) { return *vec3add(this, &v1, &v2); }\r\n vec3& sub(const vec3& v1, const vec3& v2) { return *vec3sub(this, &v1, &v2); }\r\n vec3& cross(const vec3& v) { return *vec3cross(this, &vec3(*this), &v); }\r\n vec3& cross(const vec3& v1, const vec3& v2) { return *vec3cross(this, &v1, &v2); }\r\n vec3& scale(float s) { return *vec3scale(this, this, s); }\r\n vec3& scale(const vec3& v, float s) { return *vec3scale(this, &v, s); }\r\n vec3& lerp(const vec3& p1, const vec3& p2, float s) { return *vec3lerp(this, &p1, &p2, s); }\r\n vec3& multiply(const vec3& p, const mat3& m) { return *vec3multiply(this, &p, &m); }\r\n vec3& project(const viewport& vp, const matrix& prj, const matrix& view, const matrix& world) { return *vec3project(this, this, &vp, &prj, &view, &world); }\r\n vec3& unproject(const viewport& vp, const matrix& prj, const matrix& view, const matrix& world) { return *vec3unproject(this, this, &vp, &prj, &view, &world); }\r\n vec3& normalize() { return *vec3normalize(this, this); }\r\n vec3& normalize(const vec3& v) { return *vec3normalize(this, &v); }\r\n vec3& hermite(const vec3& v1, const vec3& t1, const vec3& v2, const vec3& t2, float s) { return *vec3hermite(this, &v1, &t1, &v2, &t2, s); }\r\n vec3& catmullrom(const vec3& v1, const vec3& v2, const vec3& v3, const vec3& v4, float s) { return *vec3catmullrom(this, &v1, &v2, &v3, &v4, s); }\r\n vec3& barycentric(const vec3& v1, const vec3& v2, const vec3& v3, float f, float g) { return *vec3barycentric(this, &v1, &v2, &v3, f, g); }\r\n vec4& transform(vec4& v, const matrix& m) const { return *vec3transform(&v, this, &m); }\r\n vec3& transformcoord(const matrix& m) { return *vec3transformcoord(this, this, &m); }\r\n vec3& transformcoord(const vec3& v, const matrix& m) { return *vec3transformcoord(this, &v, &m); }\r\n vec3& transformnormal(const matrix& m) { return *vec3transformnormal(this, this, &m); }\r\n vec3& transformnormal(const vec3& v, const matrix& m) { return *vec3transformnormal(this, &v, &m); }\r\n};\r\n\r\nclass gs_export vec4:\r\n public _vec4\r\n{\r\npublic:\r\n vec4() {}\r\n vec4(const float*);\r\n vec4(const _vec3& xyz, float w);\r\n vec4(float x, float y, float z, float w);\r\n\r\npublic:\r\n operator float*();\r\n operator const float*() const;\r\n\r\npublic:\r\n vec4& operator+=(const vec4&);\r\n vec4& operator-=(const vec4&);\r\n vec4& operator*=(float);\r\n vec4& operator/=(float);\r\n\r\npublic:\r\n vec4 operator+() const;\r\n vec4 operator-() const;\r\n\r\npublic:\r\n vec4 operator+(const vec4&) const;\r\n vec4 operator-(const vec4&) const;\r\n vec4 operator*(float) const;\r\n vec4 operator/(float) const;\r\n friend vec4 operator*(float, const vec4&);\r\n\r\npublic:\r\n bool operator==(const vec4&) const;\r\n bool operator!=(const vec4&) const;\r\n\r\npublic:\r\n float length() const { return vec4length(this); }\r\n float lengthsq() const { return vec4lengthsq(this); }\r\n float dot(const vec4& v) const { return vec4dot(this, &v); }\r\n vec4& add(const vec4& v1, const vec4& v2) { return *vec4add(this, &v1, &v2); }\r\n vec4& sub(const vec4& v1, const vec4& v2) { return *vec4sub(this, &v1, &v2); }\r\n vec4& scale(float s) { return *vec4scale(this, this, s); }\r\n vec4& scale(const vec4& v, float s) { return *vec4scale(this, &v, s); }\r\n vec4& lerp(const vec4& v1, const vec4& v2, float s) { return *vec4lerp(this, &v1, &v2, s); }\r\n vec4& multiply(const matrix& m) { return *vec4multiply(this, this, &m); }\r\n vec4& multiply(const vec4& v, const matrix& m) { return *vec4multiply(this, &v, &m); }\r\n vec4& cross(const vec4& v1, const vec4& v2, const vec4& v3) { return *vec4cross(this, &v1, &v2, &v3); }\r\n vec4& hermite(const vec4& v1, const vec4& t1, const vec4& v2, const vec4& t2, float s) { return *vec4hermite(this, &v1, &t1, &v2, &t2, s); }\r\n vec4& catmullrom(const vec4& v1, const vec4& v2, const vec4& v3, const vec4& v4, float s) { return *vec4catmullrom(this, &v1, &v2, &v3, &v4, s); }\r\n vec4& barycentric(const vec4& v1, const vec4& v2, const vec4& v3, float f, float g) { return *vec4barycentric(this, &v1, &v2, &v3, f, g); }\r\n vec4& transform(const matrix& m) { return *vec4transform(this, this, &m); }\r\n vec4& transform(const vec4& v, const matrix& m) { return *vec4transform(this, &v, &m); }\r\n};\r\n\r\nclass gs_export mat3:\r\n public _mat3\r\n{\r\npublic:\r\n mat3() {}\r\n mat3(const float*);\r\n mat3(const mat3&);\r\n mat3(float f11, float f12, float f13,\r\n float f21, float f22, float f23,\r\n float f31, float f32, float f33\r\n );\r\n\r\npublic:\r\n float& operator()(uint row, uint col);\r\n float operator()(uint row, uint col) const;\r\n operator float*();\r\n operator const float*() const;\r\n\r\npublic:\r\n mat3& operator*=(const mat3&);\r\n mat3& operator+=(const mat3&);\r\n mat3& operator-=(const mat3&);\r\n mat3& operator*=(float);\r\n mat3& operator/=(float);\r\n\r\npublic:\r\n mat3 operator+() const;\r\n mat3 operator-() const;\r\n\r\npublic:\r\n mat3 operator*(const mat3&) const;\r\n mat3 operator+(const mat3&) const;\r\n mat3 operator-(const mat3&) const;\r\n mat3 operator*(float) const;\r\n mat3 operator/(float) const;\r\n friend mat3 operator*(float, const mat3&);\r\n\r\npublic:\r\n bool operator==(const mat3&) const;\r\n bool operator!=(const mat3&) const;\r\n\r\npublic:\r\n mat3& identity() { return *mat3identity(this); }\r\n bool isidentity() const { return mat3isidentity(this); }\r\n mat3& transpose() { return *mat3transpose(this, this); }\r\n mat3& transpose(const mat3& m) { return *mat3transpose(this, &m); }\r\n mat3& scaling(float sx, float sy) { return *mat3scaling(this, sx, sy); }\r\n mat3& translation(float x, float y) { return *mat3translation(this, x, y); }\r\n mat3& rotation(float angle) { return *mat3rotation(this, angle); }\r\n mat3& rotationpos(const vec2& p, float angle) { return *mat3rotationpos(this, &p, angle); }\r\n mat3& multiply(const mat3& m) { return *mat3multiply(this, this, &m); }\r\n mat3& multiply(const mat3& m1, const mat3& m2) { return *mat3multiply(this, &m1, &m2); }\r\n float determinant() const { return mat3determinant(this); }\r\n mat3& inverse(float* det, const mat3& m) { return *mat3inverse(this, det, &m); }\r\n};\r\n\r\nclass gs_export mat4:\r\n public _mat4\r\n{\r\npublic:\r\n mat4() {}\r\n mat4(const float*);\r\n mat4(const mat4&);\r\n mat4(float f11, float f12, float f13, float f14,\r\n float f21, float f22, float f23, float f24,\r\n float f31, float f32, float f33, float f34,\r\n float f41, float f42, float f43, float f44);\r\n\r\npublic:\r\n float& operator()(uint row, uint col);\r\n float operator()(uint row, uint col) const;\r\n operator float*();\r\n operator const float*() const;\r\n\r\npublic:\r\n mat4& operator*=(const mat4&);\r\n mat4& operator+=(const mat4&);\r\n mat4& operator-=(const mat4&);\r\n mat4& operator*=(float);\r\n mat4& operator/=(float);\r\n\r\npublic:\r\n mat4 operator+() const;\r\n mat4 operator-() const;\r\n\r\npublic:\r\n mat4 operator*(const mat4&) const;\r\n mat4 operator+(const mat4&) const;\r\n mat4 operator-(const mat4&) const;\r\n mat4 operator*(float) const;\r\n mat4 operator/(float) const;\r\n friend mat4 operator*(float, const mat4&);\r\n\r\npublic:\r\n bool operator==(const mat4&) const;\r\n bool operator!=(const mat4&) const;\r\n\r\npublic:\r\n mat4& identity() { return *matidentity(this); }\r\n bool isidentity() const { return matisidentity(this); }\r\n bool decompose(vec3& scale, quat& rot, vec3& trans) { return matdecompose(&scale, &rot, &trans, this); }\r\n mat4& transpose() { return *mattranspose(this, this); }\r\n mat4& transpose(const mat4& m) { return *mattranspose(this, &m); }\r\n mat4& scaling(float sx, float sy, float sz) { return *matscaling(this, sx, sy, sz); }\r\n mat4& translation(float x, float y, float z) { return *mattranslation(this, x, y, z); }\r\n mat4& rotation_x(float angle) { return *matrotation_x(this, angle); }\r\n mat4& rotation_y(float angle) { return *matrotation_y(this, angle); }\r\n mat4& rotation_z(float angle) { return *matrotation_z(this, angle); }\r\n mat4& rotation(const vec3& v, float angle) { return *matrotationaxis(this, &v, angle); }\r\n mat4& rotation(const quat& q) { return *matrotationquatern(this, &q); }\r\n mat4& rotation(float yaw, float pitch, float roll) { return *matrotationeuler(this, yaw, pitch, roll); }\r\n mat4& lookatlh(const vec3& eye, const vec3& at, const vec3& up) { return *matlookatlh(this, &eye, &at, &up); }\r\n mat4& lookatrh(const vec3& eye, const vec3& at, const vec3& up) { return *matlookatrh(this, &eye, &at, &up); }\r\n mat4& perspectivelh(float w, float h, float zn, float zf) { return *matperspectivelh(this, w, h, zn, zf); }\r\n mat4& perspectiverh(float w, float h, float zn, float zf) { return *matperspectiverh(this, w, h, zn, zf); }\r\n mat4& perspectivefovlh(float fovy, float aspect, float zn, float zf) { return *matperspectivefovlh(this, fovy, aspect, zn, zf); }\r\n mat4& perspectivefovrh(float fovy, float aspect, float zn, float zf) { return *matperspectivefovrh(this, fovy, aspect, zn, zf); }\r\n mat4& perspectiveoffcenterlh(float l, float r, float b, float t, float zn, float zf) { return *matperspectiveoffcenterlh(this, l ,r, b, t, zn, zf); }\r\n mat4& perspectiveoffcenterrh(float l, float r, float b, float t, float zn, float zf) { return *matperspectiveoffcenterlh(this, l ,r, b, t, zn, zf); }\r\n mat4& ortholh(float w, float h, float zn, float zf) { return *matortholh(this, w, h, zn, zf); }\r\n mat4& orthorh(float w, float h, float zn, float zf) { return *matorthorh(this, w, h, zn, zf); }\r\n mat4& orthooffcenterlh(float l, float r, float b, float t, float zn, float zf) { return *matorthooffcenterlh(this, l, r, b, t, zn, zf); }\r\n mat4& orthooffcenterrh(float l, float r, float b, float t, float zn, float zf) { return *matorthooffcenterrh(this, l, r, b, t, zn, zf); }\r\n mat4& viewportproject(const viewport& vp) { return *matviewportproject(this, &vp); }\r\n mat4& viewportunproject(const viewport& vp) { return *matviewportunproject(this, &vp); }\r\n mat4& transform(const vec3& scalecenter, const quat& scalerot, const vec3& scale, const vec3& rotcenter, const quat& rot, const vec3& trans) { return *mattransform(this, &scalecenter, &scalerot, &scale, &rotcenter, &rot, &trans); }\r\n mat4& transform2d(const vec2& scalecenter, float scalerot, const vec2& scale, const vec2& rotcenter, float rot, const vec2& trans) { return *mattransform2d(this, &scalecenter, scalerot, &scale, &rotcenter, rot, &trans); }\r\n mat4& affinetransform(float scale, const vec3& rotcenter, const quat& rot, const vec3& trans) { return *mataffinetransform(this, scale, &rotcenter, &rot, &trans); }\r\n mat4& affinetransform2d(float scale, const vec2& rotcenter, float rot, const vec2& trans) { return *mataffinetransform2d(this, scale, &rotcenter, rot, &trans); }\r\n float determinant() const { return matdeterminant(this); }\r\n mat4& multiply(const mat4& m) { return *matmultiply(this, this, &m); }\r\n mat4& multiply(const mat4& m1, const mat4& m2) { return *matmultiply(this, &m1, &m2); }\r\n mat4& multiplytranspose(const mat4& m) { return *matmultiplytranspose(this, this, &m); }\r\n mat4& multiplytranspose(const mat4& m1, const mat4& m2) { return *matmultiplytranspose(this, &m1, &m2); }\r\n mat4& inverse(float* determinant, const mat4& m) { return *matinverse(this, determinant, &m); }\r\n mat4& shadow(const vec4& plight, const plane& pln) { return *matshadow(this, &plight, &pln); }\r\n mat4& reflect(const plane& pln) { return *matreflect(this, &pln); }\r\n};\r\n\r\nclass gs_export quat:\r\n public _quat\r\n{\r\npublic:\r\n quat() {}\r\n quat(const float*);\r\n quat(float x, float y, float z, float w);\r\n\r\npublic:\r\n operator float*();\r\n operator const float*() const;\r\n\r\npublic:\r\n quat& operator+=(const quat&);\r\n quat& operator-=(const quat&);\r\n quat& operator*=(const quat&);\r\n quat& operator*=(float);\r\n quat& operator/=(float);\r\n\r\npublic:\r\n quat operator+() const;\r\n quat operator-() const;\r\n\r\npublic:\r\n quat operator+(const quat&) const;\r\n quat operator-(const quat&) const;\r\n quat operator*(const quat&) const;\r\n quat operator*(float) const;\r\n quat operator/(float) const;\r\n friend quat operator*(float, const quat&);\r\n\r\npublic:\r\n bool operator==(const quat&) const;\r\n bool operator!=(const quat&) const;\r\n\r\npublic:\r\n float length() const { return quatlength(this); }\r\n float lengthsq() const { return quatlengthsq(this); }\r\n float dot(const quat& q) const { return quatdot(this, &q); }\r\n quat& identity() { return *quatidentity(this); }\r\n bool isidentity() const { return quatisidenetity(this); }\r\n quat& conjugate() { return *quatconjugate(this, this); }\r\n quat& conjugate(const quat& q) { return *quatconjugate(this, &q); }\r\n float toaxisangle(vec3& axis) const\r\n {\r\n float f;\r\n quattoaxisangle(this, &axis, &f);\r\n return f;\r\n }\r\n quat& rotate(const matrix& m) { return *quatrotatematrix(this, &m); }\r\n quat& rotate(const vec3& v, float angle) { return *quatrotateaxis(this, &v, angle); }\r\n quat& ln() { return *quatln(this, this); }\r\n quat& ln(const quat& q) { return *quatln(this, &q); }\r\n quat& exp() { return *quatexp(this, this); }\r\n quat& exp(const quat& q) { return *quatexp(this, &q); }\r\n quat& slerp(const quat& q1, const quat& q2, float t) { return *quatslerp(this, &q1, &q2, t); }\r\n quat& squad(const quat& q, const quat& a, const quat& b, const quat& c, float f) { return *quatsquad(this, &q, &a, &b, &c, f); }\r\n quat& squad(const quat& a, const quat& b, const quat& c, float f) { return *quatsquad(this, this, &a, &b, &c, f); }\r\n quat& barycentric(const quat& q1, const quat& q2, const quat& q3, float f, float g) { return *quatbarycentric(this, &q1, &q2, &q3, f, g); }\r\n quat& rotate(float yaw, float pitch, float roll) { return *quatrotateeuler(this, yaw, pitch, roll); }\r\n quat& multiply(const quat& q1, const quat& q2) { return *quatmultiply(this, &q1, &q2); }\r\n quat& normalize() { return *quatnormalize(this, this); }\r\n quat& normalize(const quat& q) { return *quatnormalize(this, &q); }\r\n quat& inverse() { return *quatinverse(this, this); }\r\n quat& inverse(const quat& q) { return *quatinverse(this, &q); }\r\n};\r\n\r\nclass gs_export plane:\r\n public _plane\r\n{\r\npublic:\r\n plane() {}\r\n plane(const float*);\r\n plane(float a, float b, float c, float d);\r\n\r\npublic:\r\n operator float*();\r\n operator const float*() const;\r\n\r\npublic:\r\n plane& operator*=(float);\r\n plane& operator/=(float);\r\n plane operator+() const;\r\n plane operator-() const;\r\n plane operator*(float) const;\r\n plane operator/(float) const;\r\n friend plane operator*(float, const plane&);\r\n\r\npublic:\r\n bool operator==(const plane&) const;\r\n bool operator!=(const plane&) const;\r\n\r\npublic:\r\n float dot(const vec4& v) const { return planedot(this, &v); }\r\n float dotcoord(const vec3& v) const { return planedotcoord(this, &v); }\r\n float dotnormal(const vec3& v) const { return planedotnormal(this, &v); }\r\n plane& scale(float s) { return *planescale(this, this, s); }\r\n plane& scale(const plane& p, float s) { return *planescale(this, &p, s); }\r\n plane& frompointnormal(const vec3& p, const vec3& normal) { return *planefrompointnormal(this, &p, &normal); }\r\n plane& normalize() { return *planenormalize(this, this); }\r\n plane& normalize(const plane& p) { return *planenormalize(this, &p); }\r\n vec3& intersectline(vec3& v, const vec3& v1, const vec3& v2) const { return *planeintersectline(&v, this, &v1, &v2); }\r\n plane& frompoints(const vec3& v1, const vec3& v2, const vec3& v3) { return *planefrompoints(this, &v1, &v2, &v3); }\r\n plane& transform(const matrix& m) { return *planetransform(this, this, &m); }\r\n plane& transform(const plane& p, const matrix& m) { return *planetransform(this, &p, &m); }\r\n};\r\n\r\n__gslib_end__\r\n\r\n#include \r\n\r\n#endif\r\n", "meta": {"hexsha": "44d442cd7d0d597c7dc9753870ead1027c8310b0", "size": 35576, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/math.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/math.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/math.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 49.2060857538, "max_line_length": 236, "alphanum_fraction": 0.6766078255, "num_tokens": 10973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.44317261983126344}} {"text": "// @file ker2col_conv.c\n//\n// \\date Created on: Sep 24, 2017\n// \\author Gopalakrishna Hegde\n//\n// Description:\n//\n//\n//\n\n#include \n#include \n#include \n#include \n#include \n#include \"common_types.h\"\n#include \"data_reshape.h\"\n#include \"utils.h\"\n#include \"conv_layers.h\"\n\nbool Kn2ColConvLayer(const float *in_data, const float *filters,\n const float *bias, TensorDim in_dim,\n TensorDim filt_dim, int stride, int pad, int group,\n float *output) {\n // Currently we have limited support.\n assert(group == 1);\n assert((pad == 0) || (pad == filt_dim.w / 2));\n assert(in_dim.n == 1);\n assert(filt_dim.h == filt_dim.w);\n assert(stride == 1);\n\n // Output dimensions.\n TensorDim out_dim;\n out_dim.w = (in_dim.w + (pad + pad) - filt_dim.w) / stride + 1;\n out_dim.h = (in_dim.h + (pad + pad) - filt_dim.h) / stride + 1;\n out_dim.c = filt_dim.n;\n out_dim.n = in_dim.n;\n\n // Reshape filters in CHWN (ker_size x ker_size x no_in_ch x no_out_ch) format\n float *kkcm_filters = malloc(filt_dim.n * filt_dim.c * filt_dim.h *\n filt_dim.w * sizeof(float));\n NCHW2HWCN(filters, filt_dim.n, filt_dim.c, filt_dim.h, filt_dim.w,\n kkcm_filters);\n\n // Just for convenience\n int H = in_dim.h;\n int W = in_dim.w;\n float alpha = 1.0;\n float beta = 0.0;\n\n // We need separate buffer because GEMM output will have width = H*W even\n // if there is no padding (pad = 0).\n float *gemm_output = malloc(out_dim.c * H * W * sizeof(float));\n float *nchw_gemm_output = malloc(out_dim.c * H * W * sizeof(float));\n // Prefill output buffer with bias if present else set to zero.\n if (bias) {\n for (int m = 0; m < out_dim.c; ++m) {\n for (int a = 0; a < out_dim.h * out_dim.w; ++a) {\n output[m * out_dim.h * out_dim.w + a] = bias[m];\n }\n // For batch size > 1\n for (int b = 1; b < out_dim.n; ++b) {\n memcpy(output + b * out_dim.c * out_dim.h * out_dim.w,\n output, out_dim.c * out_dim.h * out_dim.w * sizeof(float));\n }\n }\n } else {\n memset(output, 0, out_dim.n * out_dim.c * out_dim.h * out_dim.w *\n sizeof(float));\n }\n\n for (int kr = 0; kr < filt_dim.h; kr++) {\n int row_shift = pad - kr;\n for (int kc = 0; kc < filt_dim.w; kc++) {\n int group_no = kr * filt_dim.w + kc;\n int col_shift = pad - kc;\n // Matrix dimensions - A -> mxk B -> kxn C --> mxn\n int m = in_dim.h * in_dim.w;\n int k = filt_dim.c;\n int n = filt_dim.n;\n\n // output is in H x W x C format.\n cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans,\n m, n, k, alpha, in_data, m,\n kkcm_filters + group_no * filt_dim.c * filt_dim.n, n, beta,\n gemm_output, n);\n\n // convert to CxHxW format.\n // FIXME: this will be slow. Need to find other ways :(\n NHWC2NCHW(gemm_output, 1, filt_dim.n, H, W, nchw_gemm_output);\n\n for (int omap = 0; omap < filt_dim.n; omap++) {\n MatrixShiftAdd(output + omap * out_dim.h * out_dim.w,\n out_dim.h, out_dim.w,\n nchw_gemm_output + omap * H * W,\n H, W, row_shift, col_shift);\n }\n }\n }\n free(kkcm_filters);\n free(gemm_output);\n free(nchw_gemm_output);\n return true;\n}\n", "meta": {"hexsha": "adee7eb66f1920c78383bab2b45d527be66d9b89", "size": 3382, "ext": "c", "lang": "C", "max_stars_repo_path": "src/kn2col_conv.c", "max_stars_repo_name": "gplhegde/convolution-flavors", "max_stars_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2017-10-03T18:10:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T06:38:50.000Z", "max_issues_repo_path": "src/kn2col_conv.c", "max_issues_repo_name": "chayitw/convolution-flavors", "max_issues_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-16T02:49:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T02:49:23.000Z", "max_forks_repo_path": "src/kn2col_conv.c", "max_forks_repo_name": "chayitw/convolution-flavors", "max_forks_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2017-10-24T05:17:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T14:16:14.000Z", "avg_line_length": 32.2095238095, "max_line_length": 80, "alphanum_fraction": 0.5712596097, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925402, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4429463927139076}} {"text": "/* histogram/pdf.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n\n#include \"find.c\"\n\ndouble\ngsl_histogram_pdf_sample (const gsl_histogram_pdf * p, double r)\n{\n size_t i;\n int status;\n\n/* Wrap the exclusive top of the bin down to the inclusive bottom of\n the bin. Since this is a single point it should not affect the\n distribution. */\n\n if (r == 1.0)\n {\n r = 0.0;\n }\n\n status = find (p->n, p->sum, r, &i);\n\n if (status)\n {\n GSL_ERROR_VAL (\"cannot find r in cumulative pdf\", GSL_EDOM, 0);\n }\n else\n {\n double delta = (r - p->sum[i]) / (p->sum[i + 1] - p->sum[i]);\n double x = p->range[i] + delta * (p->range[i + 1] - p->range[i]);\n return x;\n }\n}\n\ngsl_histogram_pdf *\ngsl_histogram_pdf_alloc (const size_t n)\n{\n gsl_histogram_pdf *p;\n\n if (n == 0)\n {\n GSL_ERROR_VAL (\"histogram pdf length n must be positive integer\",\n GSL_EDOM, 0);\n }\n\n p = (gsl_histogram_pdf *) malloc (sizeof (gsl_histogram_pdf));\n\n if (p == 0)\n {\n GSL_ERROR_VAL (\"failed to allocate space for histogram pdf struct\",\n GSL_ENOMEM, 0);\n }\n\n p->range = (double *) malloc ((n + 1) * sizeof (double));\n\n if (p->range == 0)\n {\n free (p); /* exception in constructor, avoid memory leak */\n\n GSL_ERROR_VAL (\"failed to allocate space for histogram pdf ranges\",\n GSL_ENOMEM, 0);\n }\n\n p->sum = (double *) malloc ((n + 1) * sizeof (double));\n\n if (p->sum == 0)\n {\n free (p->range);\n free (p); /* exception in constructor, avoid memory leak */\n\n GSL_ERROR_VAL (\"failed to allocate space for histogram pdf sums\",\n GSL_ENOMEM, 0);\n }\n\n p->n = n;\n\n return p;\n}\n\nint \ngsl_histogram_pdf_init (gsl_histogram_pdf * p, const gsl_histogram * h)\n{\n size_t i;\n size_t n = p->n;\n\n if (n != h->n)\n {\n GSL_ERROR (\"histogram length must match pdf length\", GSL_EINVAL);\n }\n\n for (i = 0; i < n; i++)\n {\n if (h->bin[i] < 0)\n {\n GSL_ERROR (\"histogram bins must be non-negative to compute\"\n \"a probability distribution\", GSL_EDOM);\n }\n }\n\n for (i = 0; i < n + 1; i++)\n {\n p->range[i] = h->range[i];\n }\n\n {\n double mean = 0, sum = 0;\n\n for (i = 0; i < n; i++)\n {\n mean += (h->bin[i] - mean) / ((double) (i + 1));\n }\n\n p->sum[0] = 0;\n\n for (i = 0; i < n; i++)\n {\n sum += (h->bin[i] / mean) / n;\n p->sum[i + 1] = sum;\n }\n }\n\n return GSL_SUCCESS;\n}\n\n\nvoid\ngsl_histogram_pdf_free (gsl_histogram_pdf * p)\n{\n RETURN_IF_NULL (p);\n free (p->range);\n free (p->sum);\n free (p);\n}\n", "meta": {"hexsha": "529863bbf5c0b1001f1d619937ca7eb08271e5dc", "size": 3531, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/histogram/pdf.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/pdf.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/pdf.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 22.7806451613, "max_line_length": 81, "alphanum_fraction": 0.575191164, "num_tokens": 1030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.44291492722072373}} {"text": "/*\n code to do weak lensing power spectrum computations\n \n Matthew Becker, UofC 2011\n*/\n\n#include \n\n#ifndef _WEAKLENS_\n#define _WEAKLENS_\n\ntypedef struct {\n int wlNum;\n double lmin;\n double lmax;\n double tmin;\n double tmax;\n} weaklensData;\n\nextern weaklensData wlData;\n\ntypedef struct {\n int initFlag;\n int currCosmoNum;\n int currWLNum;\n double zs1;\n double zs2;\n double chis1;\n double chis2;\n double chiLim;\n double sn;\n double ell; //temp var for integrals\n gsl_spline *spline;\n gsl_interp_accel *accel;\n} _lensPowerSpectra;\n\ntypedef _lensPowerSpectra *lensPowerSpectra;\n\ntypedef struct {\n int initFlag;\n int currCosmoNum;\n int currWLNum;\n lensPowerSpectra lps;\n double theta; //temp var for integrals\n gsl_spline *splineP;\n gsl_interp_accel *accelP;\n gsl_spline *splineM;\n gsl_interp_accel *accelM;\n} _lensCorrFunc;\n\ntypedef _lensCorrFunc * lensCorrFunc;\n\n//functions to compute lensing power and cross spectra\ndouble nonlinear_powspec_for_lens(double k, double a);\ndouble lens_power_spectrum(double ell, lensPowerSpectra lps);\nlensPowerSpectra init_lens_power_spectrum(double zs1, double zs2);\nvoid free_lens_power_spectrum(lensPowerSpectra lps);\n\n//functions to compute lens corr func.\ndouble lens_corr_func_minus(double theta, lensCorrFunc lcf);\ndouble lens_corr_func_plus(double theta, lensCorrFunc lcf);\nlensCorrFunc init_lens_corr_func(lensPowerSpectra lps);\nvoid free_lens_corr_func(lensCorrFunc lcf);\n\n#endif /* _WEAKLENS_ */\n", "meta": {"hexsha": "e2e650ad7f64c3dbfd4cac125da3fde385db97aa", "size": 1484, "ext": "h", "lang": "C", "max_stars_repo_path": "src/weaklens.h", "max_stars_repo_name": "beckermr/cosmocalc", "max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/weaklens.h", "max_issues_repo_name": "beckermr/cosmocalc", "max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z", "max_forks_repo_path": "src/weaklens.h", "max_forks_repo_name": "beckermr/cosmocalc", "max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z", "avg_line_length": 22.4848484848, "max_line_length": 66, "alphanum_fraction": 0.7789757412, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.44278994262131144}} {"text": "/*\n** Copyright (C) 2004 Jonathan G. Underwood \n** \n** This program is free software; you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 3 of the License, or\n** (at your option) any later version.\n** \n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n** \n** You should have received a copy of the GNU General Public License\n** along with this program; if not, write to the Free Software \n** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n*/\n\n/* Things to check: Not sure I'm using the correct error macros - should I be\n using the ones in the GSL manual? Based the ones here on what i see in\n coupling.c. */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* Static prototypes. */\nstatic int istriangle (const int two_ja, const int two_jb, const int two_jc);\nstatic int lndelta_e (const int two_j1, const int two_j2, const int two_j3, \n\t\t gsl_sf_result * lndelta);\n\n/* This macro returns 1 if n is even, -1 if n is odd. */\n#define PHASE(n) (GSL_IS_ODD(n) ? -1.0 : 1.0)\n\nstatic int\nistriangle (const int two_ja, const int two_jb, const int two_jc)\n /* Returns 0 if the triangle condition is met, and the sum of twice the\n angular momenta is even. Arguments are twice the value of the angular\n momenta. */\n{\n if ((two_jc <= two_ja + two_jb) && (two_jc >= abs (two_ja - two_jb))\n && (GSL_IS_EVEN (two_ja + two_jb + two_jc)))\n return 1;\n else\n return 0;\n}\n\nstatic int\nlndelta_e (const int two_j1, const int two_j2,\n const int two_j3, gsl_sf_result * lndelta)\n /* Calculates the natural log of the delta function - Zare Eq. A-2. Note:\n values returned from gsl_sf_ln_fact_e are always positive. */\n{\n gsl_sf_result a1, a2, a3, a4;\n int status;\n\n status = gsl_sf_lnfact_e ((two_j1 + two_j2 - two_j3) / 2, &a1);\n status += gsl_sf_lnfact_e ((two_j1 - two_j2 + two_j3) / 2, &a2);\n status += gsl_sf_lnfact_e ((-two_j1 + two_j2 + two_j3) / 2, &a3);\n status += gsl_sf_lnfact_e ((two_j1 + two_j2 + two_j3) / 2 + 1, &a4);\n\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (lndelta);\n\n lndelta->val = 0.5 * (a1.val + a2.val + a3.val - a4.val);\n lndelta->err = 0.5 * (a1.err + a2.err + a3.err + a4.err);\n lndelta->err += 2.0 * GSL_DBL_EPSILON * (a1.val + a2.val + a3.val + a4.val);\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_sf_wigner_3j_e (const int two_j1, const int two_j2, const int two_j3,\n const int two_m1, const int two_m2, const int two_m3,\n gsl_sf_result * result)\n /* Returns the value of the wigner 3j symbol - Zare Eq. A-1. Note that in\n Zare's book, this equation contains typos. */\n{\n int v, vmin, vmax, t1, t2, t3, t4, t5, status;\n gsl_sf_result a, a1, a2, a3, a4, a5, a6, a7, a8;\n\n if ((two_j1 < 0) || (two_j2 < 0) || (two_j3 < 0) ||\n (abs (two_m1) > two_j1) || (abs (two_m2) > two_j2) ||\n (abs (two_m3) > two_j3) || GSL_IS_ODD (two_j1 + two_m1) ||\n GSL_IS_ODD (two_j2 + two_m2) || GSL_IS_ODD (two_j3 + two_m3))\n DOMAIN_ERROR (result);\n\n result->val = 0.0;\n result->err = 0.0;\n\n if ((!istriangle (two_j1, two_j2, two_j3)) ||\n (two_m1 + two_m2 + two_m3) != 0)\n return GSL_SUCCESS;\n\n t1 = (two_j1 + two_j2 - two_j3) / 2;\n t2 = (two_j1 - two_m1) / 2;\n t3 = (two_j2 + two_m2) / 2;\n t4 = (two_j3 - two_j2 + two_m1) / 2;\n t5 = (two_j3 - two_j1 - two_m2) / 2;\n\n vmin = (t4 < t5) ? -t4 : -t5;\n vmin = (vmin < 0) ? 0 : vmin;\n\n vmax = t1;\n vmax = (t2 < vmax) ? t2 : vmax;\n vmax = (t3 < vmax) ? t3 : vmax;\n\n if (vmin > vmax)\n return GSL_SUCCESS;\n\n status = gsl_sf_lnfact_e ((two_j1 + two_m1) / 2, &a1);\n status += gsl_sf_lnfact_e (t2, &a2);\n status += gsl_sf_lnfact_e (t3, &a3);\n status += gsl_sf_lnfact_e ((two_j2 - two_m2) / 2, &a4);\n status += gsl_sf_lnfact_e ((two_j3 + two_m3) / 2, &a5);\n status += gsl_sf_lnfact_e ((two_j3 - two_m3) / 2, &a6);\n status += lndelta_e (two_j1, two_j2, two_j3, &a7);\n\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n a.val =\n 0.5 * (a1.val + a2.val + a3.val + a4.val + a5.val + a6.val) + a7.val;\n a.err =\n 0.5 * (a1.err + a2.err + a3.err + a4.err + a5.err + a6.err) + a7.err;\n a.err += 2.0 * GSL_DBL_EPSILON * a.val;\n\n for (v = vmin; v <= vmax; v++)\n {\n status += gsl_sf_lnfact_e (v, &a1);\n status += gsl_sf_lnfact_e (t1 - v, &a2);\n status += gsl_sf_lnfact_e (t2 - v, &a3);\n status += gsl_sf_lnfact_e (t3 - v, &a4);\n status += gsl_sf_lnfact_e (t4 + v, &a5);\n status += gsl_sf_lnfact_e (t5 + v, &a6);\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n a7.val = a.val - (a1.val + a2.val + a3.val + a4.val + a5.val + a6.val);\n a7.err = (a.err + a1.err + a2.err + a3.err + a4.err + a5.err + a6.err);\n a7.err += 2.0 * GSL_DBL_EPSILON *\n (a.val + a1.val + a2.val + a3.val + a4.val + a5.val + a6.val);\n\n status += gsl_sf_exp_err_e (a7.val, a7.err, &a8);\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n result->val += PHASE (v) * a8.val;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs (result->val);\n }\n\n result->val *= PHASE ((two_j1 - two_j2 - two_m3) / 2);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs (result->val);\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_sf_wigner_6j_e (const int two_j1, const int two_j2, const int two_j3,\n const int two_j4, const int two_j5, const int two_j6,\n gsl_sf_result * result)\n /* Returns the value of the 6j symbol - Zare Eq. A-4 */\n{\n int v, vmin, vmax, t1, t2, t3, t4, t5, t6, t7, status;\n gsl_sf_result a, a1, a2, a3, a4;\n\n if ((two_j1 < 0) || (two_j2 < 0) || (two_j3 < 0) ||\n (two_j4 < 0) || (two_j5 < 0) || (two_j6 < 0))\n DOMAIN_ERROR (result);\n\n result->val = 0.0;\n result->err = 0.0;\n\n if (!istriangle (two_j1, two_j2, two_j3) ||\n !istriangle (two_j1, two_j5, two_j6) ||\n !istriangle (two_j4, two_j2, two_j6) ||\n !istriangle (two_j4, two_j5, two_j3))\n return GSL_SUCCESS;\n\n t1 = (two_j1 + two_j2 + two_j3) / 2;\n t2 = (two_j1 + two_j5 + two_j6) / 2;\n t3 = (two_j4 + two_j2 + two_j6) / 2;\n t4 = (two_j4 + two_j5 + two_j3) / 2;\n t5 = (two_j1 + two_j2 + two_j4 + two_j5) / 2;\n t6 = (two_j2 + two_j3 + two_j5 + two_j6) / 2;\n t7 = (two_j3 + two_j1 + two_j6 + two_j4) / 2;\n\n vmin = t1;\n vmin = (t2 > vmin) ? t2 : vmin;\n vmin = (t3 > vmin) ? t3 : vmin;\n vmin = (t4 > vmin) ? t4 : vmin;\n\n vmax = t5;\n vmax = (t6 < vmax) ? t6 : vmax;\n vmax = (t7 < vmax) ? t7 : vmax;\n\n if (vmin > vmax)\n return GSL_SUCCESS;\n\n status = lndelta_e (two_j1, two_j2, two_j3, &a1);\n status += lndelta_e (two_j1, two_j5, two_j6, &a2);\n status += lndelta_e (two_j4, two_j2, two_j6, &a3);\n status += lndelta_e (two_j4, two_j5, two_j3, &a4);\n\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n a.val = a1.val + a2.val + a3.val + a4.val;\n a.err = a1.err + a2.err + a3.err + a4.err;\n a.err += 2.0 * GSL_DBL_EPSILON * a.val;\n\n for (v = vmin; v <= vmax; v++)\n {\n gsl_sf_result b1, b2, b3, b4, b5, b6, b7, b8, b9, b10;\n status += gsl_sf_lnfact_e (v + 1, &b1);\n status += gsl_sf_lnfact_e (v - t1, &b2);\n status += gsl_sf_lnfact_e (v - t2, &b3);\n status += gsl_sf_lnfact_e (v - t3, &b4);\n status += gsl_sf_lnfact_e (v - t4, &b5);\n status += gsl_sf_lnfact_e (t5 - v, &b6);\n status += gsl_sf_lnfact_e (t6 - v, &b7);\n status += gsl_sf_lnfact_e (t7 - v, &b8);\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n b9.val = a.val + b1.val - b2.val - b3.val - b4.val - b5.val - b6.val -\n b7.val - b8.val;\n b9.err = a.err + b1.err + b2.err + b3.err + b4.err + b5.err + b6.err +\n b7.err + b8.err;\n b9.err += 2.0 * GSL_DBL_EPSILON * (a.val + b1.val + b2.val + b3.val +\n b4.val + b5.val + b6.val + b7.val +\n b8.val);\n\n status += gsl_sf_exp_err_e (b9.val, b9.err, &b10);\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n result->val += b10.val * PHASE (v);\n result->err += b10.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs (result->val);\n }\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_sf_wigner_9j_e (const int two_j1, const int two_j2, const int two_j3,\n const int two_j4, const int two_j5, const int two_j6,\n const int two_j7, const int two_j8, const int two_j9,\n gsl_sf_result * result)\n /* Returns the value of 9j symbol - Zare Eq. 4.24 */\n{\n int two_k, two_kmin, two_kmax, status = GSL_SUCCESS;\n\n if ((two_j1 < 0) || (two_j2 < 0) || (two_j3 < 0) ||\n (two_j4 < 0) || (two_j5 < 0) || (two_j6 < 0) ||\n (two_j7 < 0) || (two_j8 < 0) || (two_j9 < 0))\n DOMAIN_ERROR (result);\n\n result->val = 0.0;\n result->err = 0.0;\n\n if (!istriangle (two_j1, two_j2, two_j3) ||\n !istriangle (two_j4, two_j5, two_j6) ||\n !istriangle (two_j7, two_j8, two_j9) ||\n !istriangle (two_j1, two_j4, two_j7) ||\n !istriangle (two_j2, two_j5, two_j8) ||\n !istriangle (two_j3, two_j6, two_j9))\n return GSL_SUCCESS;\n\n two_kmin = abs (two_j1 - two_j9);\n two_kmin =\n (abs (two_j8 - two_j4) < two_kmin) ? abs (two_j8 - two_j4) : two_kmin;\n two_kmin =\n (abs (two_j6 - two_j2) < two_kmin) ? abs (two_j6 - two_j2) : two_kmin;\n\n two_kmax = (two_j1 + two_j9);\n two_kmax = (two_j8 + two_j4 > two_kmax) ? two_j8 + two_j4 : two_kmax;\n two_kmax = (two_j6 + two_j2 > two_kmax) ? two_j6 + two_j2 : two_kmax;\n\n if (two_kmax < two_kmin)\n {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n\n for (two_k = two_kmin; two_k <= two_kmax; two_k += 2)\n {\n gsl_sf_result a1, a2, a3;\n status += gsl_sf_wigner_6j_e (two_j1, two_j4, two_j7,\n two_j8, two_j9, two_k, &a1);\n status +=\n gsl_sf_wigner_6j_e (two_j2, two_j5, two_j8,\n two_j4, two_k, two_j6, &a2);\n status +=\n gsl_sf_wigner_6j_e (two_j3, two_j6, two_j9,\n two_k, two_j1, two_j2, &a3);\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n result->val += (two_k + 1.0) * PHASE (two_k) * a1.val * a2.val * a3.val;\n\n result->err += result->val * (fabs (a1.err / a1.val) +\n fabs (a2.err / a2.val) +\n fabs (a3.err / a3.val));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs (result->val);\n }\n return GSL_SUCCESS;\n}\n\nint\ngsl_sf_wigner_drot_e (const int two_j, const int two_m1, const int two_m2,\n const double theta, gsl_sf_result * result)\n /* Returns the value of the reduced rotation matrix - Zare Eq. 3.57. (which\n contains typos). Angle theta is in radians. */\n{\n int v, vmin, vmax, t1, t2, t3, t4, tv, status = GSL_SUCCESS;\n gsl_sf_result a, a1, a2, a3, a4, st, ct;\n\n if ((two_j) < 0 || abs (two_m1) > two_j || abs (two_m2) > two_j ||\n (GSL_IS_ODD (two_j + two_m1)) || (GSL_IS_ODD (two_j + two_m2)))\n DOMAIN_ERROR (result);\n\n result->val = 0.0;\n result->err = 0.0;\n\n t1 = (two_j + two_m1) / 2;\n t2 = (two_j - two_m2) / 2;\n t3 = (two_m2 - two_m1) / 2;\n t4 = (2 * two_j + two_m1 - two_m2) / 2;\n\n vmin = (-t3 < 0) ? 0 : -t3;\n vmax = (t2 < t1) ? t2 : t1;\n\n if (vmin > vmax)\n return GSL_SUCCESS;\n\n status += gsl_sf_cos_e (theta * 0.5, &ct);\n status += gsl_sf_sin_e (theta * 0.5, &st);\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n status += gsl_sf_lnfact_e (t1, &a1);\n status += gsl_sf_lnfact_e (t2, &a2);\n status += gsl_sf_lnfact_e ((two_j - two_m1) / 2, &a3);\n status += gsl_sf_lnfact_e ((two_j + two_m2) / 2, &a4);\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n a.val = 0.5 * (a1.val + a2.val + a3.val + a4.val);\n a.err = 0.5 * (a1.err + a2.err + a3.err + a4.err);\n a.err += 2.0 * GSL_DBL_EPSILON * a.val;\n\n for (v = vmin; v <= vmax; v++)\n {\n gsl_sf_result b1, b2, b3, b4, b5, b6, b7, b8;\n int i1, i2;\n\n status += gsl_sf_lnfact_e (t1 - v, &b1);\n status += gsl_sf_lnfact_e (t2 - v, &b2);\n status += gsl_sf_lnfact_e (t3 + v, &b3);\n status += gsl_sf_lnfact_e (v, &b4);\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n b5.val = a.val - b1.val - b2.val - b3.val - b4.val;\n b5.err = a.err + b1.err + b2.err + b3.err + b4.err;\n b5.err +=\n 2.0 * GSL_DBL_EPSILON * (a.val + b1.val + b2.val + b3.val + b4.val);\n\n status += gsl_sf_exp_err_e (b5.val, b5.err, &b6);\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n tv = 2 * v;\n i1 = t4 - tv;\n i2 = t3 + tv;\n\n status += gsl_sf_pow_int_e (ct.val, i1, &b7);\n status += gsl_sf_pow_int_e (st.val, i2, &b8);\n if (status != GSL_SUCCESS)\n OVERFLOW_ERROR (result);\n\n /* Bolt on error in pow_int for the error in the input values */\n b7.err += i1 * fabs (ct.err);\n b8.err += i2 * fabs (st.err);\n\n result->val += PHASE (v) * b6.val * b7.val * b8.val;\n\n result->err += fabs (result->val) *\n (fabs (b6.err / b6.val) + fabs (b7.err / b7.val) +\n fabs (b8.err / b8.val));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs (result->val);\n }\n\n return GSL_SUCCESS;\n}\n\n#include \"eval.h\"\n\ndouble\ngsl_sf_wigner_3j (const int two_j1, const int two_j2, const int two_j3,\n const int two_m1, const int two_m2, const int two_m3)\n{\n EVAL_RESULT (gsl_sf_wigner_3j_e (two_j1, two_j2, two_j3,\n two_m1, two_m2, two_m3, &result));\n}\n\ndouble\ngsl_sf_wigner_6j (const int two_j1, const int two_j2, const int two_j3,\n const int two_j4, const int two_j5, const int two_j6)\n{\n EVAL_RESULT (gsl_sf_wigner_6j_e (two_j1, two_j2, two_j3,\n two_j4, two_j5, two_j6, &result));\n}\n\ndouble\ngsl_sf_wigner_9j (const int two_j1, const int two_j2, const int two_j3,\n const int two_j4, const int two_j5, const int two_j6,\n const int two_j7, const int two_j8, const int two_j9)\n{\n EVAL_RESULT (gsl_sf_wigner_9j_e (two_j1, two_j2, two_j3,\n two_j4, two_j5, two_j6,\n two_j7, two_j8, two_j9, &result));\n}\n\ndouble\ngsl_sf_wigner_drot (const int two_j, const int two_m1, const int two_m2,\n const double theta)\n{\n EVAL_RESULT (gsl_sf_wigner_drot_e (two_j, two_m1, two_m2, theta, &result));\n}\n\n#undef PHASE\n", "meta": {"hexsha": "9754d7bf37ee1fce52bf61f35682a68a6e7fb853", "size": 14971, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/contrib/wigner.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/contrib/wigner.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/contrib/wigner.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 33.7184684685, "max_line_length": 81, "alphanum_fraction": 0.5835949502, "num_tokens": 5455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.44277121610685904}} {"text": "/* \r\n This code is written by .\r\n (C) 2010 mlpy Developers.\r\n\r\n This program is free software: you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program. If not, see .\r\n*/\r\n\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#define MIN( A , B ) ((A) < (B) ? (A) : (B))\r\n\r\n#define INIT_STD 0\r\n#define INIT_PLUSPLUS 1\r\n\r\nvoid init_std(double *data, /* data points (nn points x pp dimensions) */\r\n\t double *means, /* means (kk clusters x pp dimensions) */\r\n\t int nn, /* number od data points */\r\n\t int pp, /* number of dimensions */\r\n\t int kk, /* number of clusters */\r\n\t unsigned long seed /* random seed for init */\r\n\t )\r\n{\r\n int n, p, k;\r\n int *ridx;\r\n const gsl_rng_type * T;\r\n gsl_rng * r;\r\n \r\n T = gsl_rng_default;\r\n r = gsl_rng_alloc (T);\r\n gsl_rng_set (r, seed);\r\n\r\n ridx = (int *) malloc (nn * sizeof(int));\r\n \r\n for (n=0; n max)\r\n {\r\n\tmax = a[n];\r\n\tidx = n;\r\n }\r\n \r\n return idx;\r\n}\r\n\r\n\r\nvoid\r\ninit_plus(double *data, /* data points (nn points x pp dimensions) */\r\n\t double *means, /* means (kk clusters x pp dimensions) */\r\n\t int nn, /* number od data points */\r\n\t int pp, /* number of dimensions */\r\n\t int kk, /* number of clusters */\r\n\t unsigned long seed /* random seed for init */\r\n\t )\r\n{\r\n int n, p, k;\r\n double *dist, *distk;\r\n int sidx;\r\n\r\n const gsl_rng_type *T;\r\n gsl_rng *r;\r\n \r\n \r\n T = gsl_rng_default;\r\n r = gsl_rng_alloc (T);\r\n gsl_rng_set (r, seed);\r\n \r\n dist = (double *) malloc (nn * sizeof(double));\r\n distk = (double *) malloc (nn * sizeof(double));\r\n \r\n /* first mean (randomly selected) */\r\n sidx = (int) gsl_rng_uniform_int (r, nn);\r\n gsl_rng_free(r);\r\n for (p=0; p 0)\r\n for (p=0; p\n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint jordan_s (float *Y, const float *X, const float *U, float *Y1, const float *W, const float *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\nint jordan_d (double *Y, const double *X, const double *U, double *Y1, const double *W, const double *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\n\n\nint jordan_s (float *Y, const float *X, const float *U, float *Y1, const float *W, const float *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim)\n{\n const float o = 1.0f;\n\n float *H;\n if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in jordan_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n if (N==1u)\n {\n H[0] = 1.0f / (1.0f+expf(-X[0]-U[0]*Y1[0]));\n Y[0] = 1.0f / (1.0f+expf(-B[0]-W[0]*H[0]));\n for (size_t t=1; t\nLicensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n*/\n \n#include \n#include \n#include \n#include \n\n#include \n#include \"morn_tensor.h\"\n\nvoid DeconvTensorToMatData(MTensor *tns,int bc,float *mdata,int knl_height,int knl_width,int y_stride,int x_stride)\n{\n int height = tns->height;\n int width = tns->width;\n int channel= tns->channel;\n \n int out_width = width*x_stride;\n int out_height=height*y_stride;\n int mwidth = knl_height*knl_width*channel+1;\n int mheight= out_height*out_width;\n \n memset(mdata,0,mwidth*mheight*sizeof(float));\n \n float *tdata = tns->data[bc];\n int tsize = tns->height*tns->width;\n \n int i,j,c;\n for(j=0;j=height)h=height-1;\n if(w<0)w=0;else if(w>= width)w= width-1;\n \n for(c=0;cheight;\n int width = tns->width;\n int channel= tns->channel;\n \n int out_width = width*x_stride;\n int out_height=height*y_stride;\n \n int mwidth = knl_height*knl_width*channel+1;\n int mheight= out_height*out_width;\n \n float *tdata = tns->data[bc];\n int tsize = tns->height*tns->width;\n \n int i,j,c;\n for(j=0;j=height)h=height-1;\n if(w<0)w=0;else if(w>= width)w= width-1;\n \n for(c=0;cprev = mNetworkLayer(ini,value);\n mException((para->prev == NULL),EXIT,\"invalid prev\");\n \n para->res_valid = (strcmp(\"Input\",mLayerType(para->prev))!=0);\n \n value = mINIRead(ini,name,\"knl_num\");\n if(value != NULL) para->knl_num= atoi(value);else para->knl_num= 1; \n \n value = mINIRead(ini,name,\"knl_height\");\n if(value != NULL) para->knl_height= atoi(value);else para->knl_height= 1; \n \n value = mINIRead(ini,name,\"knl_width\");\n if(value != NULL) para->knl_width= atoi(value);else para->knl_width= 1; \n \n value = mINIRead(ini,name,\"x_stride\");\n if(value != NULL) para->x_stride= atoi(value);else para->x_stride= 1;\n \n value = mINIRead(ini,name,\"y_stride\");\n if(value != NULL) para->y_stride= atoi(value);else para->y_stride= 1;\n \n value = mINIRead(ini,name,\"rate\");\n if(value != NULL) para->rate = atof(value);\n else\n {\n value = mINIRead(ini,\"para\",\"rate\");\n if(value != NULL) para->rate = atof(value);\n else para->rate = 0.001;\n }\n \n value = mINIRead(ini,name,\"decay\");\n if(value != NULL) para->decay = atof(value);\n else\n {\n value = mINIRead(ini,\"para\",\"decay\");\n if(value != NULL) para->decay = atof(value);\n else para->decay = 0.01;\n }\n mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,\"invalid para decay\");\n \n value = mINIRead(ini,name,\"momentum\");\n if(value != NULL) para->momentum = atof(value); \n else\n {\n value = mINIRead(ini,\"para\",\"momentum\");\n if(value != NULL) para->momentum = atof(value);\n else para->momentum = 0.9;\n }\n\n return para;\n}\n \nstruct HandleTensorDeconv\n{\n float *mat;\n float *kernel;\n float *update;\n};\nvoid endTensorDeconv(void *info)\n{\n struct HandleTensorDeconv *handle = (struct HandleTensorDeconv *)info;\n if(handle->mat != NULL) mFree(handle->mat);\n if(handle->kernel!= NULL) mFree(handle->kernel);\n if(handle->update!= NULL) mFree(handle->update);\n}\n#define HASH_TensorDeconv 0x9087d39c\nvoid TensorDeconvSet(MLayer *layer)\n{\n if(layer->state != DFLT) return;\n struct TensorDeconvPara *para = (struct TensorDeconvPara *)(layer->para);\n MTensor *in = para->prev->tns;\n MTensor *res= para->prev->res;\n MTensor *out=layer->tns;\n \n MHandle *hdl=mHandle(out,TensorDeconv);\n struct HandleTensorDeconv *handle = (struct HandleTensorDeconv *)(hdl->handle);\n \n int out_height= in->height*para->y_stride;\n int out_width = in->width *para->x_stride;\n int mheight = (out_height*out_width);\n int mwidth = para->knl_height*para->knl_width*in->channel+1;\n int data_size = para->knl_num*mwidth;\n \n mTensorRedefine(out,in->batch,para->knl_num,out_height,out_width,NULL);\n if(morn_network_flag == MORN_TRAIN)\n {\n if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);\n else mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);\n\n if(handle->update != NULL) mFree(handle->update);\n handle->update =(float *)mMalloc(data_size*sizeof(float));\n memset(handle->update,0,data_size*sizeof(float));\n }\n\n if(handle->kernel !=NULL) mFree(handle->kernel);\n handle->kernel = (float *)mMalloc(data_size*sizeof(float));\n \n if(morn_network_parafile==NULL)\n {\n float scale = sqrt(2.0f/mwidth);\n for(int i=0;ikernel[i] = scale*mNormalRand(0.0f,1.0f);\n }\n else\n mNetworkParaRead(layer,\"kernel\",handle->kernel,data_size*sizeof(float));\n \n if(handle->mat!=NULL) mFree(handle->mat);\n handle->mat = (float *)mMalloc(mheight*mwidth*sizeof(float));\n \n hdl->valid = 1;\n}\n\nvoid mTensorDeconvForward(MLayer *layer)\n{\n mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n mException(strcmp(\"Deconv\",mLayerType(layer)),EXIT,\"invalid layer type\");\n struct TensorDeconvPara *para = (struct TensorDeconvPara *)(layer->para);\n MTensor *in = para->prev->tns;\n MTensor *out=layer->tns;\n \n TensorDeconvSet(layer);\n \n MHandle *hdl=mHandle(out,TensorDeconv);\n struct HandleTensorDeconv *handle = (struct HandleTensorDeconv *)(hdl->handle);\n \n int mheight = (out->height*out->width);\n int mwidth = para->knl_height*para->knl_width*in->channel+1;\n \n float *kernel_data= handle->kernel;\n float *in_data = handle->mat;\n \n for(int b=0;bbatch;b++)\n {\n DeconvTensorToMatData(in,b,in_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);\n float *out_data = out->data[b];\n \n in_data[mwidth-1]=1.0f;\n \n cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,\n para->knl_num,mheight,mwidth,\n 1.0f,\n kernel_data,mwidth,\n in_data,mwidth,\n 0.0f, out_data,mheight);\n }\n \n layer->state = MORN_FORWARD;\n}\n\nvoid mTensorDeconvBackward(MLayer *layer)\n{\n mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n mException(strcmp(\"Deconv\",mLayerType(layer)),EXIT,\"invalid layer type\");\n struct TensorDeconvPara *para = (struct TensorDeconvPara *)(layer->para);\n \n MTensor *in = para->prev->tns;\n MTensor *res= para->prev->res;\n MTensor *out=layer->res;\n \n MHandle *hdl=mHandle(layer->tns,TensorDeconv);\n struct HandleTensorDeconv *handle = (struct HandleTensorDeconv *)(hdl->handle);\n mException((hdl->valid == 0),EXIT,\"no forward operate\");\n \n int mheight = (out->height*out->width);\n int mwidth = para->knl_height*para->knl_width*in->channel+1;\n \n float *kernel_data= handle->kernel;\n float *update_data= handle->update;\n float * in_data= handle->mat;\n float * res_data= handle->mat;\n \n mNetworkParaWrite(layer,\"kernel\",kernel_data,para->knl_num*mwidth*sizeof(float));\n\n for(int b=0;bbatch;b++)\n {\n DeconvTensorToMatData(in,b,in_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);\n float *out_data = out->data[b];\n \n in_data[mwidth-1]=1.0f;\n \n cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,\n para->knl_num,mwidth,mheight,\n 1.0f,\n out_data,mheight,\n in_data,mwidth,\n (b==0)?para->momentum:1.0f,\n update_data,mwidth);\n }\n cblas_saxpby(para->knl_num*mwidth,\n (0.0f-(para->rate/(float)(in->batch))),update_data,1, \n (1.0f-(para->decay*para->rate)) ,kernel_data,1);\n \n if(para->res_valid==0) return;\n \n if(para->prev->state == MORN_FORWARD)\n {\n for(int b=0;bbatch;b++) \n memset(res->data[b],0,in->height*in->width*in->channel*sizeof(float));\n para->prev->state = MORN_BACKWARD;\n }\n \n for(int b=0;bbatch;b++)\n {\n float *out_data = out->data[b];\n \n cblas_sgemm(CblasRowMajor,CblasTrans,CblasNoTrans,\n mheight,mwidth,para->knl_num,\n 1.0f,\n out_data,mheight,\n kernel_data,mwidth,\n 0.0, res_data,mwidth);\n \n DeconvMatDataToTensor(res_data,res,b,para->knl_height,para->knl_width,para->y_stride,para->x_stride);\n }\n}\n\n\n\n\n\n", "meta": {"hexsha": "2eb044f8852e81ab201ad0c353e86cdb6d6879f4", "size": 10835, "ext": "c", "lang": "C", "max_stars_repo_path": "src/deep_learning/morn_tensor_deconv.c", "max_stars_repo_name": "Shaka0723/Morn", "max_stars_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/deep_learning/morn_tensor_deconv.c", "max_issues_repo_name": "Shaka0723/Morn", "max_issues_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/deep_learning/morn_tensor_deconv.c", "max_forks_repo_name": "Shaka0723/Morn", "max_forks_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T08:08:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-23T08:08:02.000Z", "avg_line_length": 33.236196319, "max_line_length": 501, "alphanum_fraction": 0.6086755884, "num_tokens": 3092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4425597808446093}} {"text": "//\n// emu.c\n// Created by Earl Lawrence on 11/10/16.\n// Modified E Chisari 05/10/17 for CCL\n// For details on the license, see ../LICENSE_COSMICEMU\n// in this repository.\n//\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"ccl.h\"\n\n#include \"ccl_emu17_params.h\"\n#include \"ccl_emu17.h\"\n\n// Sizes of stuff\nstatic int m[2] = {111, 36}, neta=2808, peta[2]={7, 28}, rs=8, p=8;\n\n// Kriging basis computed by emuInit\n// Sizes of each basis will be peta[ee] and m[ee]\nstatic double KrigBasis[2][28][111];\n\n// Need to combine some things into a big thing.\nstatic double beta[2][28][8];\nstatic double w[2][28][111];\nstatic double lamws[2][28];\nstatic double lamz[2][28];\n\n// Initialization to compute the kriging basis for the two parts\nstatic void emuInit() {\n \n int ee, i, j, k, l;\n double cov;\n gsl_matrix *SigmaSim;\n gsl_vector *b;\n\n // Because of the structure of this emu, I need to do this horrible part first.\n // Fill in the correlation lenghths\n for(i=0; i<7; i++) {\n for(j=0; j<8; j++) {\n beta[0][i][j] = beta1[i][j];\n }\n }\n \n for(i=0; i<28; i++) {\n for(j=0; j<8; j++) {\n beta[1][i][j] = beta2[i][j];\n }\n }\n \n // Fill in the PC weights\n for(i=0; i<7; i++) {\n for(j=0; j<111; j++) {\n w[0][i][j] = w1[i][j];\n }\n }\n \n for(i=0; i<28; i++) {\n for(j=0; j<36; j++) {\n w[1][i][j] = w2[i][j];\n }\n }\n \n // Fill in the precisions\n for(i=0; i<7; i++) {\n lamws[0][i] = lamws1[i];\n lamz[0][i] = lamz1[i];\n }\n \n for(i=0; i<28; i++) {\n lamws[1][i] = lamws2[i];\n lamz[1][i] = lamz2[i];\n }\n \n // This emu has two parts: one that uses all m[0] of the data for the the first peta[0] components\n // and another that uses only the m[1] complete data for the next peta[1] components.\n for(ee=0; ee<2; ee++) {\n \n // Allocate some stuff\n SigmaSim = gsl_matrix_alloc(m[ee], m[ee]);\n b = gsl_vector_alloc(m[ee]);\n \n // Loop over the basis\n for(i=0; i xmax[i])) {\n switch(i) {\n case 0:\n ccl_cosmology_set_status_message(cosmo, \n \"ccl_pkemu(): omega_m must be between %f and %f.\\n\", \n xmin[i], xmax[i]);\n break;\n case 1:\n ccl_cosmology_set_status_message(cosmo, \n \"ccl_pkemu(): omega_b must be between %f and %f.\\n\", \n xmin[i], xmax[i]);\n break;\n case 2:\n ccl_cosmology_set_status_message(cosmo, \n \"ccl_pkemu(): sigma8 must be between %f and %f.\\n\", \n xmin[i], xmax[i]);\n break;\n case 3:\n ccl_cosmology_set_status_message(cosmo, \n \"ccl_pkemu(): h must be between %f and %f.\\n\", \n xmin[i], xmax[i]);\n break;\n case 4:\n ccl_cosmology_set_status_message(cosmo, \n \"ccl_pkemu(): n_s must be between %f and %f.\\n\", \n xmin[i], xmax[i]);\n break;\n case 5:\n ccl_cosmology_set_status_message(cosmo, \n \"ccl_pkemu(): w_0 must be between %f and %f.\\n\", \n xmin[i], xmax[i]);\n break;\n case 6:\n ccl_cosmology_set_status_message(cosmo, \n \"ccl_pkemu(): (-w_0-w_a)^(1/4) must be between %f and %f.\\n\", \n xmin[i], xmax[i]);\n break;\n case 7:\n ccl_cosmology_set_status_message(cosmo, \n \"ccl_pkemu(): omega_nu must be between %f and %f.\\n\", \n xmin[i], xmax[i]);\n break;\n }\n *status = CCL_ERROR_EMULATOR_BOUND;\n ccl_raise_exception(*status, cosmo->status_message);\n\t gsl_spline_free(zinterp);\n\t gsl_interp_accel_free(accel);\n return;\n }\n } // for(i=0; i z[rs-1])) {\n ccl_cosmology_set_status_message(cosmo, \n \"ccl_pkemu(): z must be between %f and %f.\\n\", \n z[0], z[rs-1]);\n *status = CCL_ERROR_EMULATOR_BOUND;\n ccl_raise_exception(*status, cosmo->status_message);\n\tgsl_spline_free(zinterp);\n\tgsl_interp_accel_free(accel);\n return;\n }\n \n // Standardize the inputs\n for(i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n#include \"struct.h\"\n\n\n#if defined(__cplusplus)\nextern \"C\" {\n#elif 0\n} /* so that editors will match preceding brace */\n#endif\n\nvoid BuildNotAKnotSpline(\n gsl_matrix* splinecoeffs, /* Output: matrix containing all the spline coeffs (already allocated) */\n gsl_vector* vectx, /* Input: vector x*/\n gsl_vector* vecty, /* Input: vector y */\n int n); /* Size of x, y, and of output matrix */\n\nvoid BuildQuadSpline(\n gsl_matrix* splinecoeffs, /* Output: matrix containing all the spline coeffs (already allocated) */\n gsl_vector* vectx, /* Input: vector x*/\n gsl_vector* vecty, /* Input: vector y */\n int n); /* Size of x, y, and of output matrix */\n\nvoid BuildSplineCoeffs(\n CAmpPhaseSpline** splines, /* */\n CAmpPhaseFrequencySeries* freqseries); /* */\n\nvoid BuildListmodesCAmpPhaseSpline(\n ListmodesCAmpPhaseSpline** listspline, /* Output: list of modes of splines in matrix form */\n ListmodesCAmpPhaseFrequencySeries* listh); /* Input: list of modes in amplitude/phase form */\n\n/* Functions for spline evaluation */\n\n/* Note: for the spines in matrix form, the first column contains the x values, so the coeffs start at 1 */\ndouble EvalCubic(\n gsl_vector* coeffs, /**/\n double eps, /**/\n double eps2, /**/\n double eps3); /**/\n\ndouble EvalQuad(\n gsl_vector* coeffs, /**/\n double eps, /**/\n double eps2); /**/\n\nvoid EvalCAmpPhaseSpline(\n CAmpPhaseSpline* splines, //input\n CAmpPhaseFrequencySeries* freqseries); //in/out defines CAmpPhase from defined freqs \n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _SPLINECOEFFS_H */\n", "meta": {"hexsha": "2c0f659d347ea43e40d4b7a2d407bb3788d66fba", "size": 2506, "ext": "h", "lang": "C", "max_stars_repo_path": "tools/splinecoeffs.h", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "tools/splinecoeffs.h", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/splinecoeffs.h", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 27.5384615385, "max_line_length": 107, "alphanum_fraction": 0.6600159617, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4424337412119467}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"function.h\"\n#include \"norm.h\"\n\n// Exception system configuration\n#define ERR_T int\n#define ERR_V ERRNO\n#define OK 0\n#include \"exceptions.h\"\n\n// Input\n#define MAX_BUF 256\n#define MATCH(line, str) !strncmp(line, str, strlen(str))\n\n// User options\n#define DEFAULT_TOLERANCE 1.0e-12\n#define DEFAULT_REL_TOL 1\n#define DEFAULT_MAX_ZERO_DIST 1.0e-12\n#define DEFAULT_USER_NORM 0\n#define DEFAULT_MAX_ITER 25\n#define DEFAULT_MAX_DIV_ITER 10\n#define DEFAULT_JX_REUSE 5\n\nstruct options {\n\tdouble tolerance;\n\tchar rel_tol;\n\tdouble max_zero_dist;\n\tchar user_norm;\n\tunsigned int max_iter;\n\tunsigned int max_div_iter;\n\tunsigned int jx_reuse;\n};\n\n// Result\nstruct additional_data {\n\tdouble max_error;\n\tdouble* fx;\n\tunsigned int iter_count;\n\tdouble delta_t;\n};\n\n// Function declarations\n\n/*\n * The result will be stored in x and x0 will contain the difference between x\n * and the result of the previous iteration.\n */\nERR_T findroot(int dim, double* x0, double* x, struct options* options,\n\t\tstruct additional_data* data);\n\nERR_T norm(int dim, double* x, double* n, struct options* options);\n\nERR_T input_data(char* path, int* dim, double** x0, struct options* options);\n\nvoid output_result(int dim, double* result, struct additional_data* data);\n\nvoid output_vector(int dim, double* x);\n\nvoid handler(const char* reason, const char* file, int line, int gsl_errno);\n\n// Program\n\nint main(int argc, char** argv) {\n\tint dim;\n\tchar* path;\n\tdouble* x = NULL;\n\tdouble* x0 = NULL;\n\tstruct options options;\n\tstruct additional_data additional_data;\n\n\t// Save the conf file path\n\tTRY(1, argc == 2)\n\tpath = argv[1];\n\n\t// Initialize options with default data\n\toptions.tolerance = DEFAULT_TOLERANCE;\n\toptions.rel_tol = DEFAULT_REL_TOL;\n\toptions.max_zero_dist = DEFAULT_MAX_ZERO_DIST;\n\toptions.user_norm = DEFAULT_USER_NORM;\n\toptions.max_iter = DEFAULT_MAX_ITER;\n\toptions.max_div_iter = DEFAULT_MAX_DIV_ITER;\n\toptions.jx_reuse = DEFAULT_JX_REUSE;\n\n\t// Get conf file data\n\tTRY(2, input_data(path, &dim, &x0, &options) == OK)\n\n\t// Find root\n\tTRY(3, (x = (double*) malloc(dim * sizeof(double))) != NULL)\n\tTRY(4, findroot(dim, x0, x, &options, &additional_data) == OK)\n\n\toutput_result(dim, x, &additional_data);\n\n\tRETURN(0)\n\n\tEXCEPT(\n\t\tcase 1:\n\t\t\tprintf(\"Usage: findroot path\\n\");\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tfprintf(stderr,\n\t\t\t\t\t\"[x] Ezin izan da konfigurazio fitxategia ondo \"\n\t\t\t\t\t\"irakurri.\\n\");\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tfprintf(stderr,\n\t\t\t\t\t\"[x] Ezin izan da memoria nahikoa erreserbatu.\\n\");\n\t\t\tprintf(\"[?] MEMORIA KOPURUA: %lu\\n\", dim * sizeof(double));\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tfprintf(stderr, \"[x] Ezin izan da emaitza kalkulatu.\\n\");\n\t\t\tbreak;\n\t)\n\n\tFINALLY(\n\t\tfree(x);\n\t\tfree(x0);\n\t)\n}\n\nERR_T findroot(int dim, double* x0, double* x, struct options* options,\n\t\tstruct additional_data* data) {\n\tint s;\n\tunsigned int iter_count, iter_div_count, jx_reuse_count;\n\tdouble max_err, max_err_prev, zero_dist;\n\tdouble* fx = NULL;\n\tdouble* jx = NULL;\n\tclock_t begin, end;\n\n\t// INITIALIZATION\n\n\tTRY(1, (fx = (double*) malloc(dim * sizeof(double))) != NULL)\n\tTRY(2, (jx = (double*) malloc(dim * dim * sizeof(double))) != NULL)\n\n\tgsl_set_error_handler(&handler);\n\n\tgsl_vector_view x_gsl = gsl_vector_view_array(x, dim);\n\tgsl_vector_view x0_gsl = gsl_vector_view_array(x0, dim);\n\tgsl_vector_view fx_gsl = gsl_vector_view_array(fx, dim);\n\tgsl_matrix_view jx_gsl = gsl_matrix_view_array(jx, dim, dim);\n\tgsl_permutation* p = gsl_permutation_alloc(dim);\n\n\t// NEWTON-RAPHSON LOOP\n\tbegin = clock();\n\n\t/*\n\t * a, b and c are vectors of dim dimensions\n\t * FX and JX are square matrixes of dim dimensions\n\t *\n\t * b = a - c\n\t * WHERE JX * c = FX\n\t *\n\t * a beign the result of the previous iteration (or the initial point)\n\t * b beign the result of the current iteration (or the final result)\n\t */\n\n\t// x0 == a\n\n\tmemcpy(x, x0, dim * sizeof(double));\n\n\t// x == a\n\t// x0 == a\n\n\titer_count = 0;\n\titer_div_count = 0;\n\tmax_err = DBL_MAX;\n\tmax_err_prev = DBL_MAX;\n\tjx_reuse_count = options->jx_reuse;\n\n\tdo {\n\t\tf(dim, x, fx);\n\n\t\t// Reusage of the Jacobian matrix\n\t\tif (jx_reuse_count == options->jx_reuse) {\n\t\t\tjakobiarra(dim, x, jx);\n\t\t\tTRY(3, gsl_linalg_LU_decomp(&jx_gsl.matrix, p, &s) == OK)\n\t\t\tjx_reuse_count = 0;\n\t\t} else {\n\t\t\t++jx_reuse_count;\n\t\t}\n\n\t\tTRY(4,\n\t\t\tgsl_linalg_LU_solve(\n\t\t\t\t&jx_gsl.matrix, p, &fx_gsl.vector, &x0_gsl.vector) == OK\n\t\t)\n\n\t\t// x == a\n\t\t// x0 == c\n\n\t\tTRY(5, gsl_vector_sub(&x_gsl.vector, &x0_gsl.vector) == OK)\n\n\t\tTRY(6, norm(dim, x0, &max_err, options) == OK)\n\n\t\t// Relative error\n\t\tif (options->rel_tol) {\n\t\t\t// zero_dist is reused to save memory\n\t\t\tTRY(7, norm(dim, x, &zero_dist, options) == OK)\n\t\t\tmax_err /= zero_dist;\n\t\t}\n\n\t\t// Zero dist\n\t\tTRY(8, norm(dim, fx, &zero_dist, options) == OK)\n\n\t\t// x == b\n\t\t// x0 == c\n\n\t\t// UPDATES\n\n\t\t++iter_count;\n\n\t\t// Track divergence iterations\n\t\tif (max_err > max_err_prev) {\n\t\t\t++iter_div_count;\n\t\t} else {\n\t\t\titer_div_count = 0;\n\t\t}\n\t\tmax_err_prev = max_err;\n\n\t} while ((max_err > options->tolerance ||\n\t\t\tzero_dist > options->max_zero_dist) &&\n\t\t\titer_count < options->max_iter &&\n\t\t\titer_div_count < options->max_div_iter);\n\n\tend = clock();\n\n\tif (iter_count == options->max_iter)\n\t\tprintf(\"[!] Iterazio mugara iritsi da.\\n\");\n\tif (iter_div_count == options->max_div_iter)\n\t\tprintf(\"[!] Iterazio dibergente mugara iritsi da.\\n\");\n\n\tdata->max_error = max_err;\n\tdata->fx = fx;\n\tdata->iter_count = iter_count;\n\tdata->delta_t = (double) (end - begin) / (double) CLOCKS_PER_SEC;\n\n\tEXCEPT(\n\t\tcase 1:\n\t\t\tfprintf(stderr,\n\t\t\t\t\t\"[x] Ezin izan da memoria nahikoa erreserbatu.\\n\");\n\t\t\tprintf(\"[?] MEMORIA KOPURUA: %lu\\n\", dim * sizeof(double));\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tfprintf(stderr,\n\t\t\t\t\t\"[x] Ezin izan da memoria nahikoa erreserbatu.\\n\");\n\t\t\tprintf(\"[?] MEMORIA KOPURUA: %lun\", dim * dim * sizeof(double));\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tfprintf(stderr,\n\t\t\t\t\t\"[x] Ezin izan da JX * x = FX ekuazio sistema \"\n\t\t\t\t\t\"linealaren LU deskonposaketa egin.\\n\");\n\t\t\tprintf(\"[?] HURBILPEN PARTZIALA: \");\n\t\t\toutput_vector(dim, x);\n\t\t\tprintf(\"[?] ERRORE MAXIMOA: %.*g\\n\", DBL_DIG, max_err);\n\t\t\tprintf(\"[?] F(X): \");\n\t\t\toutput_vector(dim, fx);\n\t\t\tprintf(\"[?] ITERAZIO_KOPURUA: %u\\n\", iter_count);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tfprintf(stderr,\n\t\t\t\t\t\"[x] Ezin izan da JX * x = FX ekuazio sistema lineala \"\n\t\t\t\t\t\"ebatzi LU deskonposaketa erabiliz.\\n\");\n\t\t\tprintf(\"[?] HURBILPEN PARTZIALA: \");\n\t\t\toutput_vector(dim, x);\n\t\t\tprintf(\"[?] ERRORE MAXIMOA: %.*g\\n\", DBL_DIG, max_err);\n\t\t\tprintf(\"[?] F(X): \");\n\t\t\toutput_vector(dim, fx);\n\t\t\tprintf(\"[?] ITERAZIO_KOPURUA: %u\\n\", iter_count);\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tfprintf(stderr,\n\t\t\t\t\t\"[x] Bektoreen arteko kenketa egitean errore kritiko \"\n\t\t\t\t\t\"bat egon da.\");\n\t\t\tprintf(\"[?] F(X): \");\n\t\t\toutput_vector(dim, fx);\n\t\t\tprintf(\"[?] ITERAZIO_KOPURUA: %u\\n\", iter_count);\n\t\t\tbreak;\n\t\tcase 6:\n\t\t\tfprintf(stderr,\n\t\t\t\t\t\"[x] JX * x = FX ekuazio sistema linealaren emaitzaren \"\n\t\t\t\t\t\"norma kalkulatzean errore kritiko bat egon da.\\n\");\n\t\t\tprintf(\"[?] F(X): \");\n\t\t\toutput_vector(dim, fx);\n\t\t\tprintf(\"[?] ITERAZIO_KOPURUA: %u\\n\", iter_count);\n\t\t\tbreak;\n\t\tcase 7:\n\t\t\tfprintf(stderr,\n\t\t\t\t\t\"[x] x-ren norma kalkulatzean errore kritiko bat egon \"\n\t\t\t\t\t\"da.\\n\");\n\t\t\tprintf(\"[?] HURBILPEN PARTZIALA: \");\n\t\t\toutput_vector(dim, x);\n\t\t\tprintf(\"[?] F(X): \");\n\t\t\toutput_vector(dim, fx);\n\t\t\tprintf(\"[?] ITERAZIO_KOPURUA: %u\\n\", iter_count);\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\tfprintf(stderr,\n\t\t\t\t\t\"[x] f(x)-ren norma kalkulatzean errore kritiko bat egon \"\n\t\t\t\t\t\"da.\\n\");\n\t\t\tprintf(\"[?] HURBILPEN PARTZIALA: \");\n\t\t\toutput_vector(dim, x);\n\t\t\tprintf(\"[?] ERRORE MAXIMOA: %.*g\\n\", DBL_DIG, max_err);\n\t\t\toutput_vector(dim, fx);\n\t\t\tprintf(\"[?] ITERAZIO_KOPURUA: %u\\n\", iter_count);\n\t\t\tbreak;\n\t)\n\n\tFINALLY(\n\t\tfree(fx);\n\t\tfree(jx);\n\t\tgsl_permutation_free(p);\n\t)\n}\n\nERR_T norm(int dim, double* x, double* n, struct options* options) {\n\tif (options->user_norm) {\n\t\tnorma(dim, x, n);\n\t} else {\n\t\tgsl_vector_view x_gsl = gsl_vector_view_array(x, dim);\n\t\tTRY(1, (*n = gsl_blas_dnrm2(&x_gsl.vector)) >= 0.0)\n\t}\n\n\tEXCEPT(\n\t\tcase 1:\n\t\t\tfprintf(stderr, \"[x] Ezin izan da norma kalkulatu, posible da \"\n\t\t\t\t\t\"bektorea handiegia izatea.\\n\");\n\t\t\tbreak;\n\t)\n\n\tFINALLY()\n}\n\nERR_T input_data(char* path, int* dim, double** x0, struct options* options) {\n\tFILE* f;\n\tchar line[MAX_BUF];\n\tint count = 0;\n\n\tTRY(1, (f = fopen(path, \"r\")) != NULL)\n\n\t// Read dimension\n\t*dim = 0;\n\twhile (fgets(line, MAX_BUF, f) != NULL) {\n\t\tif (line[0] != '#' && (line[0] != '\\0')) {\n\t\t\tif (MATCH(line, \"dimentsioa\")) {\n\t\t\t\tTRY(2, sscanf(line, \"dimentsioa %d\", dim) == 1)\n\t\t\t\tTRY(3, *dim > 0)\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tTRY(4, *dim != 0)\n\n\tTRY(5, (*x0 = (double*) malloc((*dim) * sizeof(double))) != NULL)\n\n\t// Read x0 and optional parameters\n\twhile (fgets(line, MAX_BUF, f) != NULL) {\n\t\tif (line[0] != '#' && (line[0] != '\\0')) {\n\t\t\tif (MATCH(line, \"tolerantzia\")) {\n\t\t\t\tTRY(6,\n\t\t\t\t\tsscanf(line, \"tolerantzia %lf\", &(options->tolerance)) == 1)\n\t\t\t\tTRY(7, options->tolerance > 0.0)\n\t\t\t} else if (MATCH(line, \"erlatiboa\")) {\n\t\t\t\tif (MATCH(line, \"erlatiboa bai\")) {\n\t\t\t\t\toptions->rel_tol = 1;\n\t\t\t\t} else if (MATCH(line, \"erlatiboa ez\")) {\n\t\t\t\t\toptions->rel_tol = 0;\n\t\t\t\t} else {\n\t\t\t\t\tTRY(8, 0);\n\t\t\t\t}\n\t\t\t} else if (MATCH(line, \"max_zero_distantzia\")) {\n\t\t\t\tTRY(9,\n\t\t\t\t\tsscanf(line, \"max_zero_distantzia %lf\",\n\t\t\t\t\t\t\t&(options->max_zero_dist)) == 1)\n\t\t\t\tTRY(10, options->max_zero_dist > 0.0)\n\t\t\t} else if (MATCH(line, \"ordezko_norma\")) {\n\t\t\t\tif (MATCH(line, \"ordezko_norma bai\")) {\n\t\t\t\t\toptions->user_norm = 1;\n\t\t\t\t} else if (MATCH(line, \"ordezko_norma ez\")) {\n\t\t\t\t\toptions->user_norm = 0;\n\t\t\t\t} else {\n\t\t\t\t\tTRY(11, 0);\n\t\t\t\t}\n\t\t\t} else if (MATCH(line, \"iterazio_maximoa\")) {\n\t\t\t\tTRY(12,\tsscanf(line, \"iterazio_maximoa %u\",\n\t\t\t\t\t\t\t&(options->max_iter)) == 1)\n\t\t\t\tTRY(13, options->max_iter != 0)\n\t\t\t} else if (MATCH(line, \"dibergentzia_iterazio_maximoa\")) {\n\t\t\t\tTRY(14, sscanf(line, \"dibergentzia_iterazio_maximoa %u\",\n\t\t\t\t\t\t&(options->max_div_iter)) == 1)\n\t\t\t} else if (MATCH(line, \"jakobiar_berrerabilpena\")) {\n\t\t\t\tTRY(15, sscanf(line, \"jakobiar_berrerabilpena %u\",\n\t\t\t\t\t\t\t&(options->jx_reuse)) == 1)\n\t\t\t} else {\n\t\t\t\tTRY(16, count <= *dim)\n\t\t\t\tTRY(17, sscanf(line, \"%lf\", (*x0) + count) == 1)\n\t\t\t\t++count;\n\t\t\t}\n\t\t}\n\t}\n\n\tTRY(18, count == *dim)\n\n\n\tEXCEPT(\n\t\tcase 1:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Ezin izan da konfigurazio fitxategia ireki.\\n\");\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Sintaxi desegokia dimentsioa emateko lerroan\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Dimentsioak zero baina handiagoa izan behar du.\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tfprintf(stdout, \"[x] Ez da aurkitu dimentsioa.\\n\");\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Ezin izan da X0-rentzat memoria erreserbatu\\n.\");\n\t\t\tprintf(\"[?] MEMORIA KOPURUA: %lu\", (*dim) * sizeof(double));\n\t\t\tbreak;\n\t\tcase 6:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Sintaxi desegokia tolerantzia emateko lerroan\\n.\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 7:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Tolerantziak zero baina handiagoa izan behar du.\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Sintaxi desegokia tolerantzia erlatiboa aukeratzeko \"\n\t\t\t\t\t\"lerroan. Aukera honek 'bai' eta 'ez' balioak hartu \"\n\t\t\t\t\t\"ditzake soilik.\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 9:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Sintaxi okerra zerotik distantzia maximoa emateko \"\n\t\t\t\t\t\"lerroan.\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 10:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Zerotik distantzia maximoak zero baina handiagoa izan \"\n\t\t\t\t\t\"behar du.\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 11:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Sintaxi desegokia ordezko norma aukeratzeko \"\n\t\t\t\t\t\"lerroan. Aukera honek 'bai' eta 'ez' balioak hartu \"\n\t\t\t\t\t\"ditzake soilik.\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 12:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Sintaxi okerra iterazio kopuru maximoa emateko \"\n\t\t\t\t\t\"lerroan. Kopuruak ezin du negatiboa izan.\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 13:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Iterazio kopuru maximoak ezin du zero izan.\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 14:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Sintaxi okerra iterazio dibergente kopuru maximoa \"\n\t\t\t\t\t\"emateko lerroan. Kopuruak ezin du negatiboa izan.\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 15:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Sintaxi okerra jakobiarraren berrerabilpen ratioa \"\n\t\t\t\t\t\"emateko lerroan. Ratioak ezin du negatiboa izan.\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 16:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] X0-ren elementu kopurura dimentsioa baina handiagoa \"\n\t\t\t\t\t\"da.\\n\");\n\t\t\tprintf(\"[?] DIMENTSIOA: %i\\n\", *dim);\n\t\t\tbreak;\n\t\tcase 17:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Sintaxi desegokia.\\n\");\n\t\t\tprintf(\"[?] LERROA: %s\", line);\n\t\t\tbreak;\n\t\tcase 18:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Dimentsioa eta X0-ren tamaina ez datoz bat.\\n\");\n\t\t\tprintf(\"[?] DIMENTSIOA: %i\\n\", *dim);\n\t\t\tprintf(\"[?] TAMAINA: %i\\n\", count);\n\t\t\tbreak;\n\t\tcase 19:\n\t\t\tfprintf(stdout,\n\t\t\t\t\t\"[x] Konfigurazio fitxategia ixtean errore kritiko bat \"\n\t\t\t\t\t\"egon da.\\n\");\n\t\t\tbreak;\n\t)\n\n\tFINALLY(\n\t\tif (f != NULL) {\n\t\t\tTRY(19, fclose(f) == OK);\n\n\t\t\t// On fail, so that it doesn't try again and again\n\t\t\tf = NULL;\n\t\t}\n\t)\n}\n\nvoid output_result(int dim, double* result, struct additional_data* data) {\n\tprintf(\"\\n\");\n\n\tprintf(\"Erroa: \");\n\toutput_vector(dim, result);\n\n\tprintf(\"Errore maximoa: %.*g\\n\", DBL_DIG, data->max_error);\n\n\tprintf(\"Erroaren irudia: \");\n\toutput_vector(dim, data->fx);\n\n\tprintf(\"Iterazio kopurua: %u\\n\", data->iter_count);\n\n\tprintf(\"Denbora: %.*g seg\\n\", DBL_DIG, data->delta_t);\n\n\tprintf(\"\\n\");\n}\n\nvoid output_vector(int dim, double* x) {\n\tint i;\n\n\tprintf(\"(\");\n\tprintf(\"%.*g\", DBL_DIG, x[0]);\n\tfor (i = 1; i < dim; ++i)\n\t\tprintf(\", %.*g\", DBL_DIG, x[i]);\n\tprintf(\")\\n\");\n}\n\nvoid handler(const char* reason, const char* file, int line, int gsl_errno) {\n\tfprintf(stderr, \"[x] \");\n\n\tswitch(gsl_errno) {\n\t\tcase GSL_EDOM:\n\t\t\tfprintf(stderr, \"GSL DOMAIN ERROR: \");\n\t\t\tbreak;\n\t\tcase GSL_ERANGE:\n\t\t\tfprintf(stderr, \"GSL RANGE ERROR: \");\n\t\t\tbreak;\n\t\tcase GSL_ENOMEM:\n\t\t\tfprintf(stderr, \"GSL NO MEMORY AVAILABLE: \");\n\t\t\tbreak;\n\t\tcase GSL_EINVAL:\n\t\t\tfprintf(stderr, \"GSL INVALID ARGUMENT: \");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"GSL ERROR: \");\n\t\t\tbreak;\n\t}\n\n\tfprintf(stderr, \"%s\\n\", reason);\n}\n", "meta": {"hexsha": "abc958e244fb142e1bca1976dcb3dfd82a6cc04b", "size": 14456, "ext": "c", "lang": "C", "max_stars_repo_path": "src/findroot.c", "max_stars_repo_name": "oersted/find-root", "max_stars_repo_head_hexsha": "0262380d6558485559d9d05e24f58edf3c1c1188", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/findroot.c", "max_issues_repo_name": "oersted/find-root", "max_issues_repo_head_hexsha": "0262380d6558485559d9d05e24f58edf3c1c1188", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/findroot.c", "max_forks_repo_name": "oersted/find-root", "max_forks_repo_head_hexsha": "0262380d6558485559d9d05e24f58edf3c1c1188", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.924137931, "max_line_length": 78, "alphanum_fraction": 0.6329551743, "num_tokens": 4867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4421700664215281}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ellipsoid/ellipsoid.h\"\n#include \"tanhsinh.h\"\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"NormConstantIntFixed\"\nPetscErrorCode NormConstantIntFixed(EllipsoidalSystem *e, PetscInt n, PetscInt p, PetscInt prec, PetscInt nPts, PetscReal *intVals, PetscReal *normConst)\n{\n PetscErrorCode ierr;\n PetscInt flopCount;\n PetscFunctionBegin;\n flopCount = 0;\n\n FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 };\n FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 };\n FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 };\n FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 };\n\n PetscReal integrals[4];\n\n mpfr_t mpfrzero;\n mpfr_t mpfrone;\n mpfr_inits(mpfrzero, mpfrone, NULL);\n mpfr_set_d(mpfrzero, 0.0, MPFR_RNDN);\n mpfr_set_d(mpfrone, 1.0, MPFR_RNDN);\n \n ierr = DEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e->hp_h, e->hp_k, prec, nPts, integrals+0, &ctx1);\n intVals[0] = integrals[0];\n ierr = DEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e->hp_h, e->hp_k, prec, nPts, integrals+1, &ctx2);\n intVals[1] = integrals[1];\n ierr = DEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, mpfrzero, e->hp_h, prec, nPts, integrals+2, &ctx3);\n intVals[2] = integrals[2];\n ierr = DEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, mpfrzero, e->hp_h, prec, nPts, integrals+3, &ctx4);\n intVals[3] = integrals[3];\n *normConst = 8.0*(integrals[2]*integrals[1] - integrals[0]*integrals[3]); flopCount += 4;\n\n mpfr_clears(mpfrzero, mpfrone, NULL);\n \n ierr = PetscLogFlops(flopCount);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"NormConstantIntFixedSE\"\nPetscErrorCode NormConstantIntFixedSE(EllipsoidalSystem *e, PetscInt n, PetscInt p, PetscInt prec, PetscInt nPts, PetscReal *normConst)\n{\n PetscErrorCode ierr;\n PetscInt flopCount;\n PetscFunctionBegin;\n flopCount = 0;\n\n FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 };\n FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 };\n FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 };\n FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 };\n\n PetscReal integrals[4];\n\n mpfr_t mpfrzero;\n mpfr_t mpfrone;\n mpfr_inits(mpfrzero, mpfrone, NULL);\n mpfr_set_d(mpfrzero, 0.0, MPFR_RNDN);\n mpfr_set_d(mpfrone, 1.0, MPFR_RNDN);\n \n ierr = SEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e->hp_h, e->hp_k, prec, nPts, integrals+0, &ctx1);\n\n ierr = SEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e->hp_h, e->hp_k, prec, nPts, integrals+1, &ctx2);\n\n ierr = SEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, mpfrzero, e->hp_h, prec, nPts, integrals+2, &ctx3);\n\n ierr = SEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, mpfrzero, e->hp_h, prec, nPts, integrals+3, &ctx4);\n\n *normConst = 8.0*(integrals[2]*integrals[1] - integrals[0]*integrals[3]); flopCount += 4;\n\n mpfr_clears(mpfrzero, mpfrone, NULL);\n \n ierr = PetscLogFlops(flopCount);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"NormConstantIntFixedERF\"\nPetscErrorCode NormConstantIntFixedERF(EllipsoidalSystem *e, PetscInt n, PetscInt p, PetscInt prec, PetscInt nPts, PetscReal *normConst)\n{\n PetscErrorCode ierr;\n PetscInt flopCount;\n PetscFunctionBegin;\n flopCount = 0;\n\n FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 };\n FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 };\n FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 };\n FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 };\n\n PetscReal integrals[4];\n\n mpfr_t mpfrzero;\n mpfr_t mpfrone;\n mpfr_inits(mpfrzero, mpfrone, NULL);\n mpfr_set_d(mpfrzero, 0.0, MPFR_RNDN);\n mpfr_set_d(mpfrone, 1.0, MPFR_RNDN);\n \n ierr = ERFQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e->hp_h, e->hp_k, prec, nPts, integrals+0, &ctx1);\n //ierr = ERFQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) inte, mpfrzero, mpfrone, prec, nPts, integrals+0, &ctx1);\n //printf(\"inte: %15.15f\\n\", integrals[0]);\n ierr = ERFQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e->hp_h, e->hp_k, prec, nPts, integrals+1, &ctx2);\n\n ierr = ERFQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, mpfrzero, e->hp_h, prec, nPts, integrals+2, &ctx3);\n\n ierr = ERFQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, mpfrzero, e->hp_h, prec, nPts, integrals+3, &ctx4);\n\n *normConst = 8.0*(integrals[2]*integrals[1] - integrals[0]*integrals[3]); flopCount += 4;\n\n mpfr_clears(mpfrzero, mpfrone, NULL);\n \n ierr = PetscLogFlops(flopCount);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"NormPlot\"\nPetscErrorCode NormPlot()\n{\n const PetscInt MPFR_PREC = 128;\n const PetscInt NUM_SOLUTIONS = 100;\n const PetscInt POINTS_MIN = 4;\n const PetscInt POINTS_STEP = 2;\n const PetscInt prec = 16;\n const PetscReal a = 3.0;\n const PetscReal b = 2.0;\n const PetscReal c = 1.0;\n PetscReal solExact;\n PetscReal intExact[4];\n PetscReal solutions[NUM_SOLUTIONS];\n PetscReal errors [NUM_SOLUTIONS];\n PetscReal intSols[4*NUM_SOLUTIONS];\n PetscReal intErrors[4*NUM_SOLUTIONS];\n PetscReal sol2, sol3, sol4;\n PetscLogEvent flopCounts[NUM_SOLUTIONS];\n EllipsoidalSystem e;\n PetscErrorCode ierr;\n PetscInt i;\n PetscEventPerfInfo info;\n PetscInt n = 21;\n PetscInt p = 22;\n PetscFunctionBegin;\n\n mpfr_set_default_prec(4*MPFR_PREC);\n initEllipsoidalSystem(&e, a, b, c, MPFR_PREC);\n\n /* calculate \"exact\" solution */\n mpfr_t exactsol;\n mpfr_init(exactsol);\n ierr = calcNormalizationMPFR(&e, n, p, &exactsol);\n ierr = calcNormalization(&e, n, p, &solExact);CHKERRQ(ierr);\n ierr = calcNormalization2(&e, n, p, intExact, &solExact);CHKERRQ(ierr);\n solExact = mpfr_get_d(exactsol, MPFR_RNDN);\n printf(\"old norm constant: %15.15f\\n\", solExact);\n\n /* calculate approximate solutions and record flops */\n char text[40] = \"%d points\";\n char sText[40];\n for(i=0; i\r\n#include \"sweeny_uf.h\"\r\n#include \r\n#include \r\n#include \r\n#include \"../src/uf.h\"\r\n#include \"../src/queue.h\"\r\n#include \r\n#include //Verwendung von Mersenne-Twister Pseudozufallszahlengenerator\r\nstatic __s8 dN;\r\n\r\n#define MIN(a,b) a <= b ? a: b\r\n#define MAX(a,b) a >= b? a: b\r\n\r\nstatic char setup=0;\r\nstatic char verbose=0;\r\nstatic double rcWeights[4]; // array with precalculated mc weights\r\nstatic double p_min_del,p_max_del, p_min_ins,p_max_ins;\r\nstatic struct queue collect1,collect2;\r\nstatic struct queue_node *todo_pool, *collect_pool;\r\nstatic __u32 offset_1=1,offset_2=2;\r\nstatic __u64 *sec_cs_moment,*four_cs_moment;\r\nstatic __u32 *size_giant;\r\nstatic __u32 *num_bonds;\r\nstatic __u32 *num_cluster;\r\nstatic __u32 DX;\r\nstatic __u32 N;\r\nstatic __u32 seed;\r\nstatic double q; \r\nstatic double coupling;\r\nstatic double beta;\r\nstatic double v;\r\nstatic double K;\r\nstatic __u32 steps;\r\nstatic __s8 *bonds;\r\nstatic gsl_rng * r; \r\nstatic __u32 edge[2];\r\nstatic __s32 adj1[4];\r\nstatic __s32 adj2[4];\r\nstatic __s32 *uf1;\r\nstatic __u32 cs1,cs2;\r\nstatic __u32 activeEdges=0;\r\nstatic __u32 cutoff;\r\n/******************************************************************************\r\n *****************************************************************************/\r\nstatic char init(void)\r\n{\r\n K=coupling*beta;\r\n v = exp(K) - 1.0;\r\n N = DX*DX;\r\n rcWeights[0] = MIN(pow(v,-1),1); //db==-1,dN==0\r\n rcWeights[1] = MIN(pow(v,-1)*q,1); //db==-1,dN=1\r\n rcWeights[2] = MIN(v,1); //db==1,dN==0\r\n rcWeights[3] = MIN(v*pow(q,-1),1); //db==1,dN==-1\r\n p_min_del = MIN(rcWeights[0],rcWeights[1]); \r\n p_max_del = MAX(rcWeights[0],rcWeights[1]);\r\n p_min_ins = MIN(rcWeights[2],rcWeights[3]);\r\n p_max_ins = MAX(rcWeights[2],rcWeights[3]); \r\n if(verbose) {\r\n\t printf(\"p_min_del = %f\\n\",p_min_del);\r\n\t printf(\"p_max_del = %f\\n\",p_max_del);\r\n\t printf(\"p_min_ins = %f\\n\",p_min_ins);\r\n\t printf(\"p_max_ins = %f\\n\",p_max_ins);\r\n\r\n\r\n }\r\n r = gsl_rng_alloc(gsl_rng_mt19937);\r\n if(!r)\r\n return 0;\r\n gsl_rng_set(r,seed);\r\n __u32 i;\r\n uf1 = initUF(N);\r\n todo_pool = malloc(N*sizeof(struct queue_node));\r\n if(!todo_pool) {\r\n return 0;\r\n }\r\n collect_pool = malloc(N*sizeof(struct queue_node));\r\n if(!collect_pool) {\r\n return 0;\r\n }\r\n for(i=0;i= N - DX)\r\n return idx +DX- N ;\r\n else\r\n return idx+DX;\r\n}\r\n/******************************************************************************\r\n *****************************************************************************/\r\nstatic inline __u32 ltcYprev(__u32 idx)\r\n{\r\n if(idx <= DX - 1) \r\n return idx + N - DX;\r\n else\r\n return idx - DX;\r\n\r\n}\r\n/******************************************************************************\r\n *****************************************************************************/\r\nstatic void Adjacent(__u32 bidx)\r\n{\r\n\r\n if(bidx%2) { \r\n bidx = (bidx -1)/2;\r\n edge[0] = bidx;\r\n edge[1] = ltcXnext(bidx);\r\n }\r\n else {\r\n bidx = bidx/2;\r\n edge[0] = bidx;\r\n edge[1] = ltcYprev(bidx);\r\n }\r\n\r\n\r\n}\r\n/******************************************************************************\r\n *****************************************************************************/\r\nstatic void Adjacent2(__u32 idx, __u8 a) {\r\n if(a == 1)\r\n {\r\n if(bonds[2*idx] == 1) adj1[0] = ltcYprev(idx);\r\n else adj1[0] = -1;\r\n if(bonds[(2*idx)+1] == 1) adj1[1] = ltcXnext(idx);\r\n else adj1[1] = -1;\r\n if(bonds[2*ltcYnext(idx)] == 1)\tadj1[2] = ltcYnext(idx);\r\n else adj1[2] = -1;\r\n if(bonds[(2*ltcXprev(idx))+1] ==1)adj1[3] = ltcXprev(idx);\r\n else adj1[3] = -1;\r\n }\r\n else {\r\n if(bonds[2*idx] == 1)adj2[0] = ltcYprev(idx);\r\n else adj2[0] = -1;\r\n if(bonds[(2*idx)+1] == 1)adj2[1] = ltcXnext(idx);\r\n else adj2[1] = -1;\r\n if(bonds[2*ltcYnext(idx)] == 1)\tadj2[2] = ltcYnext(idx);\r\n else adj2[2] = -1;\r\n if(bonds[(2*ltcXprev(idx))+1] == 1)adj2[3] = ltcXprev(idx);\r\n else adj2[3] = -1;\r\n }\r\n\r\n}\r\n/******************************************************************************\r\n *****************************************************************************/\r\nstatic __u8 breadthFirstSearch(__u32 start, __u32 goal,__u8 accept_split)\r\n{\r\n\r\n static struct queue todo1,todo2;\r\n __u32 i=0,activeP1=0,activeP2=0;\r\n init_queue(&todo1,todo_pool);\r\n init_queue(&todo2,todo_pool);\r\n init_queue(&collect1,collect_pool);\r\n init_queue(&collect2,collect_pool);\r\n cs1=0;\r\n cs2=0;\r\n enqueue(&todo1,start); // Put starting point onto queue 1\r\n enqueue(&collect1,start);\r\n cs1++; // Increase cluster size of bfs 1\r\n collect_pool[start].visited = offset_1;\r\n enqueue(&todo2,goal); // Put goal point onto queue 2\r\n enqueue(&collect2,goal);\r\n collect_pool[goal].visited = offset_2;\r\n cs2++; // increase cluster size of bfs 2\r\n while(!queue_empty_p(&todo1) && !queue_empty_p(&todo2)) {\r\n dequeue(&todo2,&activeP2); // get next vertex of bfs 2\r\n Adjacent2(activeP2,2);\t // get all adjacent vertices of current vertex\r\n for(i=0;i<4;i++) {\r\n if(adj2[i] != -1) { // if accessable (edge exists)\r\n if(collect_pool[adj2[i]].visited == offset_2) continue; // already visited\r\n if((__u32)adj2[i] == start || collect_pool[adj2[i]].visited == offset_1) { // reconnected\r\n while(!queue_empty_p(&todo1)) dequeue(&todo1,&activeP1); // empty queue 1\r\n while(!queue_empty_p(&todo2)) dequeue(&todo2,&activeP2); // empty queue 2\r\n while(!queue_empty_p(&collect1)) dequeue(&collect1,&activeP1);\r\n while(!queue_empty_p(&collect2)) dequeue(&collect2,&activeP2);\r\n offset_1+=2;\r\n offset_2+=2;\r\n return 1; // 1 indicates success\r\n }\r\n enqueue(&todo2,adj2[i]);\r\n enqueue(&collect2,adj2[i]);\r\n collect_pool[adj2[i]].visited = offset_2; // mark as visited\r\n cs2++; // increase cluster size\r\n }\r\n }\r\n dequeue(&todo1,&activeP1);\r\n Adjacent2(activeP1,1);\r\n for(i=0;i<4;i++) {\r\n if(adj1[i] != -1) {\r\n if(collect_pool[adj1[i]].visited == offset_1) continue;\r\n if((__u32)adj1[i] == goal || collect_pool[adj1[i]].visited == offset_2) {\r\n while(!queue_empty_p(&todo1)) dequeue(&todo1,&activeP1);\r\n while(!queue_empty_p(&todo2)) dequeue(&todo2,&activeP2);\r\n while(!queue_empty_p(&collect1)) dequeue(&collect1,&activeP1);\r\n while(!queue_empty_p(&collect2)) dequeue(&collect2,&activeP2);\r\n offset_1+=2;\r\n offset_2+=2;\r\n return 1;\r\n }\r\n enqueue(&todo1,adj1[i]);\r\n enqueue(&collect1,adj1[i]);\r\n collect_pool[adj1[i]].visited = offset_1;\r\n cs1++;\r\n }\r\n }\r\n }\r\n /* Only if a deletion of a cutting edge has to be accepted, \r\n * completely traverse the unfinished cluster to \r\n * be able to update the UF datastructure afterwards based on\r\n * the collect1 and collect2 queues.\r\n */\r\n if(accept_split) { \r\n while(!queue_empty_p(&todo1)) {\r\n dequeue(&todo1,&activeP1);\r\n Adjacent2(activeP1,1);\r\n for(i=0;i<4;i++) {\r\n if(adj1[i] != -1) {\r\n if(collect_pool[adj1[i]].visited == offset_1) continue;\r\n enqueue(&todo1,adj1[i]);\r\n enqueue(&collect1,adj1[i]);\r\n collect_pool[adj1[i]].visited = offset_1;\r\n cs1++;\r\n }\r\n }\r\n\r\n } \r\n while(!queue_empty_p(&todo2)) {\r\n dequeue(&todo2,&activeP2);\r\n Adjacent2(activeP2,2);\r\n for(i=0;i<4;i++) {\r\n if(adj2[i] != -1) {\r\n if(collect_pool[adj2[i]].visited == offset_2) continue;\r\n enqueue(&todo2,adj2[i]);\r\n enqueue(&collect2,adj2[i]);\r\n collect_pool[adj2[i]].visited = offset_2;\r\n cs2++;\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n while(!queue_empty_p(&todo1)) dequeue(&todo1,&activeP1);\r\n while(!queue_empty_p(&todo2)) dequeue(&todo2,&activeP2);\r\n while(!queue_empty_p(&collect1)) dequeue(&collect1,&activeP1);\r\n while(!queue_empty_p(&collect2)) dequeue(&collect2,&activeP2);\r\n }\r\n offset_1+=2;\r\n offset_2+=2;\r\n\r\n return 0;\r\n}\r\n/******************************************************************************\r\n *****************************************************************************/\r\nstatic __u8 removeBond(__u32 a, __u32 b,__u8 accept_split,__u8 accept_non_split) {\r\n __u32 vertex;\r\n if(breadthFirstSearch(a,b,accept_split)) //replacement edge found\r\n return accept_non_split;\r\n else { // no replacement edge available and hence cluster will be splitted if move accepted\r\n if(accept_split) { // accept cluster splitting case? if yes rebuild uf\r\n while(!queue_empty_p(&collect1)) {\r\n dequeue(&collect1,&vertex);\r\n uf1[vertex] = a;\r\n }\r\n uf1[a] = -1*cs1;\r\n while(!queue_empty_p(&collect2)) {\r\n dequeue(&collect2,&vertex);\r\n uf1[vertex] = b;\r\n }\r\n uf1[b] = -1*cs2;\r\n return 1;\r\n } // not accepted\r\n else {\r\n return 0;\r\n }\r\n }\r\n \r\n}\t\r\n/******************************************************************************\r\n *****************************************************************************/\r\nstatic inline __u8 acceptChange(__s8 d_numCl, __s8 d_numAB, double randV)\r\n{\r\n return d_numAB == -1 ? (randV < rcWeights[d_numCl]) : (randV < rcWeights[2 - d_numCl]);\r\n}\r\n/******************************************************************************\r\n *****************************************************************************/\r\nstatic inline void mcStep(void)\r\n{\r\n\r\n static __u32 bidx;\r\n static double rnd_num;\r\n bidx = gsl_rng_uniform_int(r,2*N);\r\n rnd_num = gsl_rng_uniform(r);\r\n Adjacent(bidx);\r\n if(bonds[bidx] == 1) { //edge is active hence delete it\r\n if(rnd_num < p_min_del) {\r\n \t bonds[bidx] = -1;\r\n if(removeBond(edge[0],edge[1],1,1))\r\n activeEdges--;\r\n else {\r\n if(verbose)fprintf(stderr,\"ERROR!\\n\");\r\n exit(-1);\r\n }\r\n }\r\n else {\r\n\tif(rnd_num < p_max_del) {\r\n\t bonds[bidx] = -1;\r\n\t if(removeBond(edge[0],edge[1], acceptChange(1,-1,rnd_num),acceptChange(0,-1,rnd_num)))\r\n activeEdges--;\r\n else\r\n bonds[bidx] = 1;\r\n }\r\n\r\n }\r\n\r\n }\r\n else {\t\r\n if(rnd_num < p_min_ins) {\r\n bonds[bidx] = 1;\r\n activeEdges++;\r\n unite(edge[0],edge[1],uf1);\r\n }\r\n else {\r\n if(rnd_num < p_max_ins) {\r\n dN = connected(edge[0],edge[1],uf1) ? 0: -1;\r\n if(acceptChange(dN,1,rnd_num)) {\r\n bonds[bidx]=1;\r\n activeEdges++;\r\n if(dN == -1)\r\n unite(edge[0],edge[1],uf1);\r\n }\r\n }\r\n\r\n }\r\n }\r\n}\r\n/******************************************************************************\r\n *****************************************************************************/\r\nstatic void extract_observables(__u32 cnt)\r\n{\r\n __u32 i=0,tn=0,nclust=0;\r\n size_giant[cnt] = 0;\r\n sec_cs_moment[cnt] = 0;\r\n four_cs_moment[cnt] = 0;\r\n for(i=0;i size_giant[cnt]) size_giant[cnt] = (__u32)(-uf1[i]);\r\n }\r\n }\r\n num_bonds[cnt] = activeEdges;\r\n num_cluster[cnt] = nclust;\r\n}\r\n/******************************************************************************\r\n *****************************************************************************/\r\nstatic void generateTimeSeries(void)\r\n{ \r\n __u32 i=0,j=0;\r\n for(i=0;i\n#include \"../../quadrature.h\"\n\n#define COMM PETSC_COMM_WORLD\n\n/* cool dendritic failure:\n ./plap -snes_fd_color -snes_converged_reason -ksp_converged_reason -pc_type mg -plap_p 10.0 -da_refine 6 -snes_monitor_solution draw\nsucceeds in 11 snes iterations (on fine grid) with grid sequencing:\n ./plap -snes_fd_color -snes_converged_reason -ksp_converged_reason -pc_type mg -plap_p 10.0 -snes_grid_sequence 6 -snes_monitor_solution draw\n*/\n\n//STARTCTX\ntypedef struct {\n double p, eps, alpha;\n int quaddegree;\n PetscBool no_residual;\n} PLapCtx;\n//ENDCTX\n\nPetscErrorCode ConfigureCtx(PLapCtx *user) {\n PetscErrorCode ierr;\n user->p = 4.0;\n user->eps = 0.0;\n user->alpha = 1.0;\n user->quaddegree = 2;\n user->no_residual = PETSC_FALSE;\n ierr = PetscOptionsBegin(COMM,\"plap_\",\"p-laplacian solver options\",\"\"); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-p\",\"exponent p with 1 <= p < infty\",\n \"plap.c\",user->p,&(user->p),NULL); CHKERRQ(ierr);\n if (user->p < 1.0) { SETERRQ(COMM,1,\"p >= 1 required\"); }\n ierr = PetscOptionsReal(\"-eps\",\"regularization parameter eps\",\n \"plap.c\",user->eps,&(user->eps),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-alpha\",\"parameter alpha in exact solution\",\n \"plap.c\",user->alpha,&(user->alpha),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsInt(\"-quaddegree\",\"quadrature degree n (= 1,2,3 only)\",\n \"plap.c\",user->quaddegree,&(user->quaddegree),NULL); CHKERRQ(ierr);\n if ((user->quaddegree < 1) || (user->quaddegree > 3)) {\n SETERRQ(COMM,2,\"quadrature degree n=1,2,3 only\"); }\n ierr = PetscOptionsBool(\"-no_residual\",\"do not set the residual evaluation function\",\n \"plap.c\",user->no_residual,&(user->no_residual),NULL);CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n return 0;\n}\n\n//STARTEXACT\ndouble Uexact(double x, double y, double alpha) {\n return 0.5 * (x+alpha)*(x+alpha) * (y+alpha)*(y+alpha);\n}\n\ndouble Frhs(double x, double y, PLapCtx *user) {\n const double alf = user->alpha,\n XX = (x+alf)*(x+alf),\n YY = (y+alf)*(y+alf),\n D2 = XX + YY,\n C = PetscPowScalar(XX * YY * D2, (user->p - 2.0) / 2.0),\n gamma1 = 1.0/(x+alf) + (x+alf)/D2,\n gamma2 = 1.0/(y+alf) + (y+alf)/D2;\n return - (user->p - 2.0) * C * (gamma1*(x+alf)*YY + gamma2*XX*(y+alf))\n - C * D2;\n}\n//ENDEXACT\n\n//STARTINITIALITERATE\nPetscErrorCode InitialIterateLocal(DMDALocalInfo *info, Vec u, PLapCtx *user) {\n PetscErrorCode ierr;\n const double hx = 1.0 / (info->mx+1), hy = 1.0 / (info->my+1);\n double x, y, **au;\n int i, j;\n ierr = DMDAVecGetArray(info->da,u,&au); CHKERRQ(ierr);\n for (j = info->ys; j < info->ys + info->ym; j++) {\n y = hy * (j + 1);\n for (i = info->xs; i < info->xs + info->xm; i++) {\n x = hx * (i + 1);\n au[j][i] = (1.0 - x) * Uexact(0.0,y,user->alpha)\n + x * Uexact(1.0,y,user->alpha);\n }\n }\n ierr = DMDAVecRestoreArray(info->da,u,&au); CHKERRQ(ierr);\n return 0;\n}\n//ENDINITIALITERATE\n\nPetscErrorCode GetUexactLocal(DMDALocalInfo *info, Vec uex, PLapCtx *user) {\n PetscErrorCode ierr;\n const double hx = 1.0 / (info->mx+1), hy = 1.0 / (info->my+1);\n double x, y, **auex;\n int i, j;\n ierr = DMDAVecGetArray(info->da,uex,&auex); CHKERRQ(ierr);\n for (j = info->ys; j < info->ys + info->ym; j++) {\n y = hy * (j + 1);\n for (i = info->xs; i < info->xs + info->xm; i++) {\n x = hx * (i + 1);\n auex[j][i] = Uexact(x,y,user->alpha);\n }\n }\n ierr = DMDAVecRestoreArray(info->da,uex,&auex); CHKERRQ(ierr);\n return 0;\n}\n\n//STARTFEM\nstatic double xiL[4] = { 1.0, -1.0, -1.0, 1.0},\n etaL[4] = { 1.0, 1.0, -1.0, -1.0};\n\ndouble chi(int L, double xi, double eta) {\n return 0.25 * (1.0 + xiL[L] * xi) * (1.0 + etaL[L] * eta);\n}\n\n// evaluate v(xi,eta) on reference element using local node numbering\ndouble eval(const double v[4], double xi, double eta) {\n double sum = 0.0;\n int L;\n for (L=0; L<4; L++)\n sum += v[L] * chi(L,xi,eta);\n return sum;\n}\n\ntypedef struct {\n double xi, eta;\n} gradRef;\n\ngradRef dchi(int L, double xi, double eta) {\n const gradRef result = {0.25 * xiL[L] * (1.0 + etaL[L] * eta),\n 0.25 * etaL[L] * (1.0 + xiL[L] * xi)};\n return result;\n}\n\n// evaluate partial derivs of v(xi,eta) on reference element\ngradRef deval(const double v[4], double xi, double eta) {\n gradRef sum = {0.0,0.0}, tmp;\n int L;\n for (L=0; L<4; L++) {\n tmp = dchi(L,xi,eta);\n sum.xi += v[L] * tmp.xi; sum.eta += v[L] * tmp.eta;\n }\n return sum;\n}\n//ENDFEM\n\n//STARTTOOLS\nvoid GetUorG(DMDALocalInfo *info, int i, int j, double **au, double *u,\n PLapCtx *user) {\n const double hx = 1.0 / (info->mx+1), hy = 1.0 / (info->my+1),\n x = hx * (i + 1), y = hy * (j + 1);\n u[0] = ((i == info->mx) || (j == info->my))\n ? Uexact(x, y, user->alpha) : au[j][i];\n u[1] = ((i == 0) || (j == info->my))\n ? Uexact(x-hx,y, user->alpha) : au[j][i-1];\n u[2] = ((i == 0) || (j == 0))\n ? Uexact(x-hx,y-hy,user->alpha) : au[j-1][i-1];\n u[3] = ((i == info->mx) || (j == 0))\n ? Uexact(x, y-hy,user->alpha) : au[j-1][i];\n}\n\ndouble GradInnerProd(DMDALocalInfo *info, gradRef du, gradRef dv) {\n const double hx = 1.0 / (info->mx+1), hy = 1.0 / (info->my+1),\n cx = 4.0 / (hx * hx), cy = 4.0 / (hy * hy);\n return cx * du.xi * dv.xi + cy * du.eta * dv.eta;\n}\n\ndouble GradPow(DMDALocalInfo *info, gradRef du, double P, double eps) {\n return PetscPowScalar(GradInnerProd(info,du,du) + eps * eps, P / 2.0);\n}\n//ENDTOOLS\n\n//STARTOBJECTIVE\ndouble ObjIntegrandRef(DMDALocalInfo *info,\n const double f[4], const double u[4],\n double xi, double eta, double p, double eps) {\n const gradRef du = deval(u,xi,eta);\n return GradPow(info,du,p,eps) / p - eval(f,xi,eta) * eval(u,xi,eta);\n}\n\nPetscErrorCode FormObjectiveLocal(DMDALocalInfo *info, double **au,\n double *obj, PLapCtx *user) {\n PetscErrorCode ierr;\n const double hx = 1.0 / (info->mx+1), hy = 1.0 / (info->my+1);\n const Quad1D q = gausslegendre[user->quaddegree-1];\n const int XE = info->xs + info->xm, YE = info->ys + info->ym;\n double x, y, lobj = 0.0, u[4];\n int i,j,r,s;\n MPI_Comm com;\n\n // loop over all elements\n for (j = info->ys; j <= YE; j++) {\n y = hy * (j + 1);\n for (i = info->xs; i <= XE; i++) {\n x = hx * (i + 1);\n // owned elements include \"right\" and \"top\" edges of grid\n if (i < XE || j < YE || i == info->mx || j == info->my) {\n const double f[4] = {Frhs(x, y, user),\n Frhs(x-hx,y, user),\n Frhs(x-hx,y-hy,user),\n Frhs(x, y-hy,user)};\n GetUorG(info,i,j,au,u,user);\n // loop over quadrature points\n for (r = 0; r < q.n; r++) {\n for (s = 0; s < q.n; s++) {\n lobj += q.w[r] * q.w[s]\n * ObjIntegrandRef(info,f,u,q.xi[r],q.xi[s],\n user->p,user->eps);\n }\n }\n }\n }\n }\n lobj *= 0.25 * hx * hy;\n\n ierr = PetscObjectGetComm((PetscObject)(info->da),&com); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&lobj,obj,1,MPI_DOUBLE,MPI_SUM,com); CHKERRQ(ierr);\n return 0;\n}\n//ENDOBJECTIVE\n\n//STARTFUNCTION\ndouble FunIntegrandRef(DMDALocalInfo *info, int L,\n const double f[4], const double u[4],\n double xi, double eta, double p, double eps) {\n const gradRef du = deval(u,xi,eta),\n dchiL = dchi(L,xi,eta);\n return GradPow(info,du,p - 2.0,eps) * GradInnerProd(info,du,dchiL)\n - eval(f,xi,eta) * chi(L,xi,eta);\n}\n\nPetscErrorCode FormFunctionLocal(DMDALocalInfo *info, double **au,\n double **FF, PLapCtx *user) {\n const double hx = 1.0 / (info->mx+1), hy = 1.0 / (info->my+1);\n const Quad1D q = gausslegendre[user->quaddegree-1];\n const int XE = info->xs + info->xm, YE = info->ys + info->ym,\n li[4] = {0,-1,-1,0}, lj[4] = {0,0,-1,-1};\n double x, y, u[4];\n int i,j,l,r,s,PP,QQ;\n\n // clear residuals\n for (j = info->ys; j < YE; j++)\n for (i = info->xs; i < XE; i++)\n FF[j][i] = 0.0;\n\n // loop over all elements\n for (j = info->ys; j <= YE; j++) {\n y = hy * (j + 1);\n for (i = info->xs; i <= XE; i++) {\n x = hx * (i + 1);\n const double f[4] = {Frhs(x, y, user),\n Frhs(x-hx,y, user),\n Frhs(x-hx,y-hy,user),\n Frhs(x, y-hy,user)};\n GetUorG(info,i,j,au,u,user);\n // loop over corners of element i,j\n for (l = 0; l < 4; l++) {\n PP = i + li[l];\n QQ = j + lj[l];\n // only update residual if we own node\n if (PP >= info->xs && PP < XE\n && QQ >= info->ys && QQ < YE) {\n // loop over quadrature points\n for (r = 0; r < q.n; r++) {\n for (s = 0; s < q.n; s++) {\n FF[QQ][PP]\n += 0.25 * hx * hy * q.w[r] * q.w[s]\n * FunIntegrandRef(info,l,f,u,\n q.xi[r],q.xi[s],\n user->p,user->eps);\n }\n }\n }\n }\n }\n }\n return 0;\n}\n//ENDFUNCTION\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n DM da, da_after;\n SNES snes;\n Vec u_initial, u, u_exact;\n PLapCtx user;\n DMDALocalInfo info;\n double err, hx, hy;\n\n PetscInitialize(&argc,&argv,NULL,help);\n ierr = ConfigureCtx(&user); CHKERRQ(ierr);\n\n ierr = DMDACreate2d(COMM,\n DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_BOX,\n 3,3,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da); CHKERRQ(ierr);\n ierr = DMSetFromOptions(da); CHKERRQ(ierr);\n ierr = DMSetUp(da); CHKERRQ(ierr);\n ierr = DMSetApplicationContext(da,&user);CHKERRQ(ierr);\n\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n hx = 1.0 / (info.mx+1);\n hy = 1.0 / (info.my+1);\n ierr = DMDASetUniformCoordinates(da,hx,1.0-hx,hy,1.0-hy,0.0,1.0); CHKERRQ(ierr);\n\n ierr = SNESCreate(COMM,&snes); CHKERRQ(ierr);\n ierr = SNESSetDM(snes,da); CHKERRQ(ierr);\n ierr = DMDASNESSetObjectiveLocal(da,\n (DMDASNESObjective)FormObjectiveLocal,&user); CHKERRQ(ierr);\n if (!user.no_residual) {\n ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,\n (DMDASNESFunction)FormFunctionLocal,&user); CHKERRQ(ierr);\n }\n ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);\n\n ierr = DMCreateGlobalVector(da,&u_initial);CHKERRQ(ierr);\n ierr = InitialIterateLocal(&info,u_initial,&user); CHKERRQ(ierr);\n ierr = SNESSolve(snes,NULL,u_initial); CHKERRQ(ierr);\n ierr = VecDestroy(&u_initial); CHKERRQ(ierr);\n ierr = DMDestroy(&da); CHKERRQ(ierr);\n\n ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr);\n ierr = VecDuplicate(u,&u_exact); CHKERRQ(ierr);\n ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr);\n ierr = PetscPrintf(COMM,\n \"grid of %d x %d = %d interior nodes\\n\",\n info.mx,info.my,info.mx*info.my); CHKERRQ(ierr);\n ierr = GetUexactLocal(&info,u_exact,&user); CHKERRQ(ierr);\n ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); // u <- u + (-1.0) uexact\n ierr = VecNorm(u,NORM_INFINITY,&err); CHKERRQ(ierr);\n ierr = PetscPrintf(COMM,\"numerical error: |u-u_exact|_inf = %.3e\\n\",\n err); CHKERRQ(ierr);\n\n VecDestroy(&u_exact); SNESDestroy(&snes);\n return PetscFinalize();\n}\n\n", "meta": {"hexsha": "7751c28874f75d1d5ad878ff441c59291a5e63be", "size": 12844, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch9/solns/plap.c", "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/ch9/solns/plap.c", "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/ch9/solns/plap.c", "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6656891496, "max_line_length": 145, "alphanum_fraction": 0.5282622236, "num_tokens": 4140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.44146453037222166}} {"text": "/* linalg/choleskyc.c\n * \n * Copyright (C) 2007, 2019 Patrick Alken\n * Copyright (C) 2010 Huan Wu\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"recurse.h\"\n\n/*\n * This module contains routines related to the Cholesky decomposition\n * of a complex Hermitian positive definite matrix.\n */\n\nstatic void cholesky_complex_conj_vector(gsl_vector_complex *v);\nstatic int complex_cholesky_decomp_L2(gsl_matrix_complex * A);\nstatic int complex_cholesky_decomp_L3(gsl_matrix_complex * A);\n\n/*\ngsl_linalg_complex_cholesky_decomp()\n Perform the Cholesky decomposition on a Hermitian positive definite\nmatrix using Level 3 BLAS.\n\nInputs: A - (input/output) complex positive definite matrix\n\nReturn: success or error\n\nNotes:\n1) The lower triangle of A is overwritten with the Cholesky decomposition\n*/\n\nint\ngsl_linalg_complex_cholesky_decomp(gsl_matrix_complex *A)\n{\n const size_t N = A->size1;\n \n if (N != A->size2)\n {\n GSL_ERROR(\"Cholesky decomposition requires square matrix\", GSL_ENOTSQR);\n }\n else\n {\n return complex_cholesky_decomp_L3(A);\n }\n}\n\n/*\ngsl_linalg_complex_cholesky_solve()\n Solve A x = b where A is in cholesky form\n*/\n\nint\ngsl_linalg_complex_cholesky_solve (const gsl_matrix_complex * cholesky,\n const gsl_vector_complex * b,\n gsl_vector_complex * x)\n{\n if (cholesky->size1 != cholesky->size2)\n {\n GSL_ERROR (\"cholesky matrix must be square\", GSL_ENOTSQR);\n }\n else if (cholesky->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (cholesky->size2 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n gsl_vector_complex_memcpy (x, b);\n return gsl_linalg_complex_cholesky_svx(cholesky, x);\n }\n}\n\n/*\ngsl_linalg_complex_cholesky_svx()\n Solve A x = b in place where A is in cholesky form\n*/\n\nint\ngsl_linalg_complex_cholesky_svx (const gsl_matrix_complex * cholesky,\n gsl_vector_complex * x)\n{\n if (cholesky->size1 != cholesky->size2)\n {\n GSL_ERROR (\"cholesky matrix must be square\", GSL_ENOTSQR);\n }\n else if (cholesky->size2 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* solve for y using forward-substitution, L y = b */\n gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasNonUnit, cholesky, x);\n\n /* perform back-substitution, L^H x = y */\n gsl_blas_ztrsv (CblasLower, CblasConjTrans, CblasNonUnit, cholesky, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\n/******************************************************************************\n\ngsl_linalg_complex_cholesky_invert()\n Compute the inverse of an Hermitian positive definite matrix in\n Cholesky form.\n\nInputs: LLT - matrix in cholesky form on input\n A^{-1} = L^{-H} L^{-1} on output\n\nReturn: success or error\n******************************************************************************/\n\nint\ngsl_linalg_complex_cholesky_invert(gsl_matrix_complex * LLT)\n{\n if (LLT->size1 != LLT->size2)\n {\n GSL_ERROR (\"cholesky matrix must be square\", GSL_ENOTSQR);\n }\n else\n {\n int status;\n size_t N = LLT->size1;\n size_t i, j;\n\n /* invert the lower triangle of LLT */\n status = gsl_linalg_complex_tri_invert(CblasLower, CblasNonUnit, LLT);\n if (status)\n return status;\n\n /* compute A^{-1} = L^{-H} L^{-1} */\n status = gsl_linalg_complex_tri_LHL(LLT);\n if (status)\n return status;\n\n /* copy the Hermitian lower triangle to the upper triangle */\n for (i = 1; i < N; ++i)\n {\n for (j = 0; j < i; ++j)\n {\n gsl_complex z = gsl_matrix_complex_get(LLT, i, j);\n gsl_matrix_complex_set(LLT, j, i, gsl_complex_conjugate(z));\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n\n/********************************************\n * INTERNAL ROUTINES *\n ********************************************/\n\nstatic void\ncholesky_complex_conj_vector(gsl_vector_complex *v)\n{\n size_t i;\n\n for (i = 0; i < v->size; ++i)\n {\n gsl_complex * vi = gsl_vector_complex_ptr(v, i);\n GSL_IMAG(*vi) = -GSL_IMAG(*vi);\n }\n}\n\n/*\ncomplex_cholesky_decomp_L2()\n Perform the Cholesky decomposition on a Hermitian positive definite\nmatrix using Level 2 BLAS. See Golub & Van Loan, \"Matrix Computations\" (3rd ed),\nalgorithm 4.2.2.\n\nInputs: A - (input/output) complex postive definite matrix\n\nReturn: success or error\n\nNotes:\n1) The lower triangle of A is overwritten with the Cholesky decomposition\n*/\n\nstatic int\ncomplex_cholesky_decomp_L2(gsl_matrix_complex * A)\n{\n const size_t N = A->size1;\n \n if (N != A->size2)\n {\n GSL_ERROR(\"Cholesky decomposition requires square matrix\", GSL_ENOTSQR);\n }\n else\n {\n size_t j;\n gsl_complex z;\n double ajj;\n\n for (j = 0; j < N; ++j)\n {\n z = gsl_matrix_complex_get(A, j, j);\n ajj = GSL_REAL(z);\n\n if (j > 0)\n {\n gsl_vector_complex_const_view aj =\n gsl_matrix_complex_const_subrow(A, j, 0, j);\n\n gsl_blas_zdotc(&aj.vector, &aj.vector, &z);\n ajj -= GSL_REAL(z);\n }\n\n if (ajj <= 0.0)\n {\n GSL_ERROR(\"matrix is not positive definite\", GSL_EDOM);\n }\n\n ajj = sqrt(ajj);\n GSL_SET_COMPLEX(&z, ajj, 0.0);\n gsl_matrix_complex_set(A, j, j, z);\n\n if (j < N - 1)\n {\n gsl_vector_complex_view av =\n gsl_matrix_complex_subcolumn(A, j, j + 1, N - j - 1);\n\n if (j > 0)\n {\n gsl_vector_complex_view aj =\n gsl_matrix_complex_subrow(A, j, 0, j);\n gsl_matrix_complex_view am =\n gsl_matrix_complex_submatrix(A, j + 1, 0, N - j - 1, j);\n\n cholesky_complex_conj_vector(&aj.vector);\n\n gsl_blas_zgemv(CblasNoTrans,\n GSL_COMPLEX_NEGONE,\n &am.matrix,\n &aj.vector,\n GSL_COMPLEX_ONE,\n &av.vector);\n\n cholesky_complex_conj_vector(&aj.vector);\n }\n\n gsl_blas_zdscal(1.0 / ajj, &av.vector);\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ncomplex_cholesky_decomp_L3()\n Perform the Cholesky decomposition on a Hermitian positive definite\nmatrix using Level 3 BLAS.\n\nInputs: A - (input/output) complex postive definite matrix\n\nReturn: success or error\n\nNotes:\n1) The lower triangle of A is overwritten with the Cholesky decomposition\n\n2) Based on ReLAPACK recursive variant with Level 3 BLAS\n*/\n\nstatic int\ncomplex_cholesky_decomp_L3(gsl_matrix_complex * A)\n{\n const size_t N = A->size1;\n \n if (N != A->size2)\n {\n GSL_ERROR(\"Cholesky decomposition requires square matrix\", GSL_ENOTSQR);\n }\n else if (N <= CROSSOVER_CHOLESKY)\n {\n /* use unblocked Level 2 algorithm */\n return complex_cholesky_decomp_L2(A);\n }\n else\n {\n /*\n * partition matrix:\n *\n * A11 A12\n * A21 A22\n *\n * where A11 is N1-by-N1\n */\n int status;\n const size_t N1 = GSL_LINALG_SPLIT_COMPLEX(N);\n const size_t N2 = N - N1;\n gsl_matrix_complex_view A11 = gsl_matrix_complex_submatrix(A, 0, 0, N1, N1);\n gsl_matrix_complex_view A21 = gsl_matrix_complex_submatrix(A, N1, 0, N2, N1);\n gsl_matrix_complex_view A22 = gsl_matrix_complex_submatrix(A, N1, N1, N2, N2);\n\n /* recursion on A11 */\n status = complex_cholesky_decomp_L3(&A11.matrix);\n if (status)\n return status;\n\n /* A21 = A21 * A11^{-1} */\n gsl_blas_ztrsm(CblasRight, CblasLower, CblasConjTrans, CblasNonUnit, GSL_COMPLEX_ONE, &A11.matrix, &A21.matrix);\n\n /* A22 -= A21 A21^H */\n gsl_blas_zherk(CblasLower, CblasNoTrans, -1.0, &A21.matrix, 1.0, &A22.matrix);\n\n /* recursion on A22 */\n status = complex_cholesky_decomp_L3(&A22.matrix);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n }\n}\n\n", "meta": {"hexsha": "d002a6fc891fecc01a7735dac4f00d0f5e38ce65", "size": 9208, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/linalg/choleskyc.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/linalg/choleskyc.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/choleskyc.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.6898550725, "max_line_length": 118, "alphanum_fraction": 0.602410947, "num_tokens": 2466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4413984011383068}} {"text": "/*\n** 1st level statistical inference using LISA\n** GLM (general linear modeling) using precoloring\n**\n** G.Lohmann, MPI-KYB, 2018\n*/\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\nextern gsl_matrix *PseudoInv(gsl_matrix *A,gsl_matrix *B);\nextern void printmat(gsl_matrix *R,char *str);\nextern void printvec(gsl_vector *x,char *str);\n\n\n/*\n** general linear model (GLM) using pecoloring\n*/\nvoid VGLM(gsl_matrix *Data,gsl_matrix *X,gsl_matrix *XInv,gsl_vector *con,VImage map,VImage zmap)\n{\n int i;\n int m = Data->size2;\n int n = con->size;\n gsl_set_error_handler_off();\n gsl_vector *y = gsl_vector_calloc (m);\n gsl_vector *beta = gsl_vector_calloc (n);\n\n \n /* compute pseudoinverse */\n XInv = PseudoInv(X,XInv);\n\n\n /* main loop */\n VFillImage(zmap,VAllBands,0);\n size_t nvox=0;\n for (nvox=0; nvox < Data->size1; nvox++) {\n\n y->data = gsl_matrix_ptr(Data,nvox,0);\n gsl_blas_dgemv(CblasNoTrans,1.0,XInv,y,0.0,beta);\n\n /* contrast image */\n double sum=0;\n for (i=0; isize; i++) {\n sum += (beta->data[i]*con->data[i]);\n }\n if (gsl_isnan(sum) || gsl_isinf(sum)) continue;\n int b = VPixel(map,0,0,nvox,VShort);\n int r = VPixel(map,0,1,nvox,VShort);\n int c = VPixel(map,0,2,nvox,VShort);\n VPixel(zmap,b,r,c,VFloat) = sum;\n }\n\n gsl_vector_free(beta);\n gsl_vector_free(y);\n}\n\n", "meta": {"hexsha": "b478e8befafca063c9eb16bc1a13ae778709aa9b", "size": 1566, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_precoloring/GLM.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_precoloring/GLM.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_precoloring/GLM.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 22.6956521739, "max_line_length": 97, "alphanum_fraction": 0.6660280971, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.44116828588246476}} {"text": "#include \n#include \n#include \n#include \"tz_error.h\"\n#include \"tz_constant.h\"\n#include \"tz_image_lib.h\"\n#include \"tz_stack_lib.h\"\n#include \"tz_objdetect.h\"\n#include \"tz_imatrix.h\"\n#include \"tz_stack_math.h\"\n#include \"tz_stack_bwdist.h\"\n#include \"tz_stack_bwmorph.h\"\n#include \"tz_voxel_linked_list.h\"\n#include \"tz_stack_sampling.h\"\n#include \"tz_stack_attribute.h\"\n#include \"tz_dimage_lib.h\"\n#include \"tz_arrayview.h\"\n#include \"tz_dmatrix.h\"\n\nINIT_EXCEPTION_MAIN(e)\n\nint main(int argc, char* argv[]) {\n char neuron_name[100];\n if (argc == 1) {\n strcpy(neuron_name, \"fly_neuron\");\n } else {\n strcpy(neuron_name, argv[1]);\n }\n\n char file_path[100];\n\n#if 0 /* local maxima */\n sprintf(file_path, \"../data/%s/mask.tif\", neuron_name);\n Stack *stack1 = Read_Stack(file_path);\n\n sprintf(file_path, \"../data/%s/highpass_locmin.tif\", neuron_name);\n Stack *stack2 = Read_Stack(file_path);\n \n Stack_Add(stack1, stack2, stack1);\n sprintf(file_path, \"../data/%s/cell_mark.tif\", neuron_name);\n Write_Stack(file_path, stack1);\n#endif\n\n#if 0\n sprintf(file_path, \"../data/%s.tif\", neuron_name);\n Stack *stack1 = Read_Stack(file_path);\n\n DMatrix *filter = Mexihat_2D_D(2.0, NULL);\n filter->ndim = 3;\n filter->dim[2] = 1;\n\n DMatrix *out = Filter_Stack_Fast_D(stack1, filter, NULL, 0);\n\n# if 1\n int nvoxel = Stack_Voxel_Number(stack1);\n int i;\n for (i = 0; i < nvoxel; i++) {\n out->array[i] = fabs(out->array[i]);\n } \n# endif\n\n Stack *stack2 = Scale_Double_Stack(out->array, out->dim[0], out->dim[1],\n\t\t\t\t out->dim[2], GREY);\n\n\n\n sprintf(file_path, \"../data/%s/edge.tif\", neuron_name);\n Write_Stack(file_path, stack2);\n\n Kill_Stack(stack1);\n Kill_Stack(stack2);\n#endif\n\n#if 1\n sprintf(file_path, \"../data/%s/mask.tif\", neuron_name);\n Stack *stack2 = Read_Stack(file_path);\n sprintf(file_path, \"../data/%s/seeds.pa\", neuron_name);\n Pixel_Array *pa = Pixel_Array_Read(file_path);\n double *pa_array = (double *) pa->array;\n double max_dist = gsl_stats_max(pa_array, 1, pa->size);\n double mean_dist = gsl_stats_mean(pa_array, 1, pa->size);\n double std_dist = sqrt(gsl_stats_variance(pa_array, 1, pa->size));\n \n int erode_size = (int) (mean_dist + std_dist * 2 + 0.5);\n Struct_Element *se = Make_Ball_Se(erode_size);\n Stack *stack3 = Stack_Erode_Fast(stack2, NULL, se);\n int dilate_size = (int) (max_dist + 0.5);\n se = Make_Ball_Se(dilate_size);\n Stack *stack4 = Stack_Dilate(stack3, NULL, se);\n\n Stack_Sub(stack2, stack4, stack2);\n Write_Stack(\"../data/test.tif\", stack2);\n\n Kill_Stack(stack2);\n Kill_Stack(stack3);\n Kill_Stack(stack4);\n Kill_Pixel_Array(pa);\n \n#endif\n\n return 0;\n}\n", "meta": {"hexsha": "1b8eeb562d9249982eae09a7aa6c31c46a5deae3", "size": 2659, "ext": "c", "lang": "C", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_test.c", "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_test.c", "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_test.c", "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8155339806, "max_line_length": 74, "alphanum_fraction": 0.6878525762, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4411682720347861}} {"text": "/*\n * Player - One Hell of a Robot Server\n * Copyright (C) 2000 Brian Gerkey & Kasper Stoy\n * gerkey@usc.edu kaspers@robotics.usc.edu\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n/**************************************************************************\n * Desc: Useful pdf functions\n * Author: Andrew Howard\n * Date: 10 Dec 2002\n * CVS: $Id: pf_pdf.c 6348 2008-04-17 02:53:17Z gerkey $\n *************************************************************************/\n\n#include \n#include \n#include \n#include \n//#include \n//#include \n\n#include \"amcl/pf/pf_pdf.h\"\n\n// Random number generator seed value\nstatic unsigned int pf_pdf_seed;\n\n\n/**************************************************************************\n * Gaussian\n *************************************************************************/\n\n// Create a gaussian pdf\npf_pdf_gaussian_t *pf_pdf_gaussian_alloc(pf_vector_t x, pf_matrix_t cx)\n{\n pf_matrix_t cd;\n pf_pdf_gaussian_t *pdf;\n\n pdf = calloc(1, sizeof(pf_pdf_gaussian_t));\n\n pdf->x = x;\n pdf->cx = cx;\n //pdf->cxi = pf_matrix_inverse(cx, &pdf->cxdet);\n\n // Decompose the convariance matrix into a rotation\n // matrix and a diagonal matrix.\n pf_matrix_unitary(&pdf->cr, &cd, pdf->cx);\n pdf->cd.v[0] = sqrt(cd.m[0][0]);\n pdf->cd.v[1] = sqrt(cd.m[1][1]);\n pdf->cd.v[2] = sqrt(cd.m[2][2]);\n\n // Initialize the random number generator\n //pdf->rng = gsl_rng_alloc(gsl_rng_taus);\n //gsl_rng_set(pdf->rng, ++pf_pdf_seed);\n srand48(++pf_pdf_seed);\n\n return pdf;\n}\n\n\n// Destroy the pdf\nvoid pf_pdf_gaussian_free(pf_pdf_gaussian_t *pdf)\n{\n //gsl_rng_free(pdf->rng);\n free(pdf);\n return;\n}\n\n\n/*\n// Compute the value of the pdf at some point [x].\ndouble pf_pdf_gaussian_value(pf_pdf_gaussian_t *pdf, pf_vector_t x)\n{\n int i, j;\n pf_vector_t z;\n double zz, p;\n \n z = pf_vector_sub(x, pdf->x);\n\n zz = 0;\n for (i = 0; i < 3; i++)\n for (j = 0; j < 3; j++)\n zz += z.v[i] * pdf->cxi.m[i][j] * z.v[j];\n\n p = 1 / (2 * M_PI * pdf->cxdet) * exp(-zz / 2);\n \n return p;\n}\n*/\n\n\n// Generate a sample from the pdf.\npf_vector_t pf_pdf_gaussian_sample(pf_pdf_gaussian_t *pdf)\n{\n int i, j;\n pf_vector_t r;\n pf_vector_t x;\n\n // Generate a random vector\n for (i = 0; i < 3; i++)\n {\n //r.v[i] = gsl_ran_gaussian(pdf->rng, pdf->cd.v[i]);\n r.v[i] = pf_ran_gaussian(pdf->cd.v[i]);\n }\n\n for (i = 0; i < 3; i++)\n {\n x.v[i] = pdf->x.v[i];\n for (j = 0; j < 3; j++)\n x.v[i] += pdf->cr.m[i][j] * r.v[j];\n } \n \n return x;\n}\n\n// Draw randomly from a zero-mean Gaussian distribution, with standard\n// deviation sigma.\n// We use the polar form of the Box-Muller transformation, explained here:\n// http://www.taygeta.com/random/gaussian.html\ndouble pf_ran_gaussian(double sigma)\n{\n double x1, x2, w, r;\n\n do\n {\n do { r = drand48(); } while (r==0.0);\n x1 = 2.0 * r - 1.0;\n do { r = drand48(); } while (r==0.0);\n x2 = 2.0 * r - 1.0;\n w = x1*x1 + x2*x2;\n } while(w > 1.0 || w==0.0);\n\n return(sigma * x2 * sqrt(-2.0*log(w)/w));\n}\n", "meta": {"hexsha": "436a66c0f766e3f9b14d2e4dcfb1f9091de6c004", "size": 3801, "ext": "c", "lang": "C", "max_stars_repo_path": "src/navigation/amcl/src/amcl/pf/pf_pdf.c", "max_stars_repo_name": "0aqz0/SmartCar", "max_stars_repo_head_hexsha": "af9370a1a8ce3dea893fe2c2e194bee433c1b734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 59.0, "max_stars_repo_stars_event_min_datetime": "2020-08-03T04:03:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:25:23.000Z", "max_issues_repo_path": "src/navigation/amcl/src/amcl/pf/pf_pdf.c", "max_issues_repo_name": "0aqz0/SmartCar", "max_issues_repo_head_hexsha": "af9370a1a8ce3dea893fe2c2e194bee433c1b734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-09-03T06:19:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-14T02:30:55.000Z", "max_forks_repo_path": "src/navigation/amcl/src/amcl/pf/pf_pdf.c", "max_forks_repo_name": "0aqz0/SmartCar", "max_forks_repo_head_hexsha": "af9370a1a8ce3dea893fe2c2e194bee433c1b734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2020-08-13T07:16:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T03:06:29.000Z", "avg_line_length": 25.8571428571, "max_line_length": 77, "alphanum_fraction": 0.5816890292, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.44090833484722397}} {"text": "#ifndef PRIMAL_DUAL_LOOPLESS_H\r\n#define PRIMAL_DUAL_LOOPLESS_H\r\n\r\n#include \"problem_data.h\"\r\n\r\n\r\n#include \r\n#include \r\n#include \r\n#include /* printf */\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n//This class implements the loopless variance reduced type methods with arbitrary sampling\r\n\r\n/*\r\nThe optimization problem to solve is:\r\n\r\n\\sum_{i=1}^n \\lambda_i\\phi_i(A_i^{\\top} w)+ g(w)\r\nAssumption 1: For each i, \\phi_i is 1-smooth\r\nBy default, lambda_i=1/n for all i.\r\n*\r\n* The dual problem is\r\n* g*(-sum_{i=1}^n \\lambda_i \\alpha_i A_i)+\\sum_{i=1}^n \\lambda_i \\phi*_i(\\alpha_i)\r\n*/\r\n\r\ntemplate\r\nclass Primal_Dual_LOOPLESS: public problem_data\r\n{\r\n\r\n\r\nprivate:\r\n\r\n // involved variables\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n std::vector proba_vector;\r\n\r\n std::vector tilde_proba_vector;\r\n\r\n\r\n std::vector group_C;\r\n\r\n std::vector index_group_C;\r\n\r\n std::vector maxp_group_C;\r\n\r\n std::vector isolated_I;\r\n\r\n std::vector sump_group_C;\r\n vector theta_S; //theta_S in the paper\r\n\r\n\r\n\r\n\r\n std::vector Li;\r\n\r\n\r\n\r\n std::vector gk; // the vector g^k in the paper\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n // auxiliary variables\r\n std::vector deltagk;\r\n std::vector index_to_do_prox;\r\n std::vector whether_or_not_to_do_prox;\r\n\r\n L nb_of_iters_per_loop;\r\n\r\n\r\n\r\n D primal_value;\r\n\r\n D dual_value;\r\n\r\n D epsilon;\r\n\r\n L max_nb_loops;\r\n\r\n D max_p;\r\n\r\n D maxv;\r\n\r\n\r\n\r\n D lambda_1;\r\n D lambda_2;\r\n\r\n D running_time;\r\n\r\n L nb_loops;\r\n\r\n\r\n\r\n L print_every_N;\r\n\r\n D delta;\r\n\r\n\r\n vector batch_i;\r\n vector my_batch;\r\n vector batch_deltaalphai;\r\n\r\n L batch_size;\r\n\r\n L nb_groups; //number of groups in group sampling\r\n\r\n\r\n\r\n\r\nprotected:\r\n\r\n std::vector primal_x; // the x variable\r\n\r\n\r\n string uniform;\r\n\r\n D Lf;\r\n\r\n D L2;\r\n\r\n D L1;\r\n\r\n D sumLi;\r\n\r\n D p; // the probability of changing w to x as in the paper\r\n L tau; //number of threads on each node/computer\r\n\r\n D scaler;\r\n\r\n\r\n std::vector dual_alpha; // dual_alpha[i]=\\phi_i'(A_i't)\r\n\r\n std::vector lambda_f; // lambda_f[i]=lambda_i\r\n std::vector baralpha; // baralpha=sum_{i=1}^{nsamples} lambda_f[i]* dual_alpha[i]*A_i\r\n\r\n L current_nb_iters;\r\n\r\n L nb_iters;\r\n\r\n std::vector last_update_i;\r\n\r\n ofstream samp;\r\n\r\npublic:\r\n\r\n\r\n gsl_rng * rng;\r\n virtual inline D gradient_of_phi_i(D, L){return D(NULL);}\r\n virtual inline D gradient_of_gstar_j(D, L){return D(NULL);}\r\n virtual inline D value_of_phi_i(D, L) {return D(NULL);}\r\n virtual inline D value_of_g_j(D, L){return D(NULL);}\r\n virtual inline D value_of_phistar_i(D,L) {return D(NULL);}\r\n virtual inline D value_of_gstar(vector &){return D(NULL);}\r\n virtual inline D value_of_gstar_minus(vector &, D){return D(NULL);}\r\n virtual inline D feasible_dual(vector &){return D(NULL);}\r\n virtual inline D compute_delta_alpha(D,D,L){return D(NULL);}\r\n virtual inline void set_auxiliary_v(){}\r\n virtual inline D get_lambda1(){return D(NULL);}\r\n virtual inline D get_lambda2(){return D(NULL);}\r\n virtual inline D compute_current_xj_value(D , L, L , L){return D(NULL);}\r\n virtual inline D compute_current_xj_value_without_update(D , L, L , L){return D(NULL);}\r\n virtual inline void set_stepsize(){}\r\n virtual inline void update_x(D,L){}\r\n virtual inline void update_baralpha(){}\r\n\r\n Primal_Dual_LOOPLESS()\r\n : problem_data()\r\n {\r\n\r\n }\r\n\r\n Primal_Dual_LOOPLESS(const char* matrix_file, const char* vector_file)\r\n : problem_data(matrix_file, vector_file)\r\n {\r\n\r\n }\r\n\r\n Primal_Dual_LOOPLESS(const char* matrix_file)\r\n : problem_data(matrix_file)\r\n {\r\n\r\n }\r\n\r\n\r\n void set_rng()\r\n {\r\n gsl_rng_env_setup();\r\n const gsl_rng_type * T;\r\n T = gsl_rng_default;\r\n rng = gsl_rng_alloc(T);\r\n gsl_rng_set(rng,time(NULL));\r\n //gsl_rng_set(rng, 27432042);\r\n\r\n }\r\n\r\n\r\n\r\n void set_print_every_N(L i){print_every_N=i;}\r\n\r\n void set_L1(L p){\r\n if(p==0){ //batch sampling mode (stochastic process in the paper)\r\n L1=(1-1./tau)*Lf+L2;\r\n }else{ //group sampling mode\r\n L1=Lf+L2;\r\n }\r\n // alpha_l=1/(4.*L1+2*L2);\r\n }\r\n\r\n void set_Li_Lf()\r\n {\r\n sumLi=0;\r\n maxv=0;\r\n D minv=std::numeric_limits::max();\r\n Li.resize(this->nsamples,0);\r\n for(L i=0;insamples;i++)\r\n {\r\n D vi=0;\r\n for (L k = this->ptr[i]; k < this->ptr[i + 1];k++)\r\n {\r\n vi+=lambda_f[i]*this->nsamples*this->A[k]*this->A[k];\r\n }\r\n Li[i]=vi;\r\n if(maxvvi) minv=vi;\r\n }\r\n for(L i=0;insamples;i++){\r\n if(Li[i]ptr[i]; k < this->ptr[i + 1];k++)\r\n { this->A[k]=0;\r\n L j=this->row_idx[k];\r\n for (L kj = this->ptr_t[j]; kj < this->ptr_t[j + 1];\tkj++)\r\n {\r\n L i2=this->col_idx[kj];\r\n if(i2==i) this->A_t[kj]=0;\r\n }\r\n }\r\n Li[i]=maxv*1e-15;\r\n }\r\n sumLi+=Li[i];\r\n }\r\n Lf=compute_lambda_max(10);\r\n cout<<\" max of v: \"< bk(this->nfeatures);\r\n for (L j=0;jnfeatures;j++)\r\n {\r\n bk[j]=1;\r\n }\r\n std::vector yk(this->nsamples);\r\n D normk;\r\n D tmp;\r\n for(L kk=0;kknsamples;i++){\r\n tmp=0;\r\n for (L k = this->ptr[i]; k < this->ptr[i + 1];\tk++)\r\n {\r\n L j=this->row_idx[k];\r\n tmp+=this->A[k]*bk[j];\r\n }\r\n yk[i]=tmp;\r\n }\r\n normk=0;\r\n for (L j=0;jnfeatures;j++){\r\n bk[j]=0;\r\n for (L k = this->ptr_t[j]; k < this->ptr_t[j + 1];\tk++)\r\n {\r\n L i=this->col_idx[k];\r\n bk[j]+=this->A_t[k]*yk[i]*lambda_f[i];\r\n }\r\n normk+=bk[j]*bk[j];\r\n }\r\n normk=sqrt(normk);\r\n for (L j=0;jnfeatures;j++)\r\n {bk[j]=bk[j]/normk; }\r\n }\r\n cout<nsamples;i++){\r\n tmp=0;\r\n for (L k = this->ptr[i]; k < this->ptr[i + 1];\tk++)\r\n {\r\n L j=this->row_idx[k];\r\n tmp+=this->A[k]*bk[j];\r\n }\r\n yk[i]=tmp;\r\n normk+=yk[i]*yk[i];\r\n }\r\n std::vector bk2(this->nfeatures);\r\n for (L j=0;jnfeatures;j++){\r\n bk2[j]=0;\r\n for (L k = this->ptr_t[j]; k < this->ptr_t[j + 1];\tk++)\r\n {\r\n L i=this->col_idx[k];\r\n bk2[j]+=this->A_t[k]*yk[i]*lambda_f[i];\r\n }\r\n }\r\n for (L j=0;jnfeatures;j++)\r\n res+=bk2[j]*bk[j];\r\n return res;\r\n }\r\n\r\n void set_optimal_probability()\r\n {\r\n tilde_proba_vector.clear();\r\n tilde_proba_vector.resize(this->nsamples,0);\r\n proba_vector.clear();\r\n proba_vector.resize(this->nsamples,0);\r\n D sum=0;\r\n for(L i=0; insamples;i++)\r\n {\r\n tilde_proba_vector[i]=Li[i];\r\n sum+=Li[i];\r\n }\r\n max_p=0;\r\n for(L i=0; insamples;i++)\r\n {\r\n tilde_proba_vector[i]=tilde_proba_vector[i]/sum;\r\n proba_vector[i]=1-pow(1-tilde_proba_vector[i],tau);\r\n if(max_pnsamples,0);\r\n std::vector q(this->nsamples);\r\n D sumq=0;\r\n cout<<\"start setting group sampling probablity\"<nsamples;i++)\r\n {\r\n q[i]=Li[i];\r\n sumq+=q[i];\r\n }\r\n D maxq=0;\r\n L nb=0;\r\n D tmp=0;\r\n for(L i=0; insamples;i++)\r\n {\r\n q[i]=q[i]/sumq*tau;\r\n if(q[i]>maxq) maxq=q[i];\r\n if(q[i]>1) {\r\n nb++; //count the number of elements larger than 1\r\n tmp+=q[i]-1;\r\n }\r\n }\r\n cout<<\"maxq=\"<nsamples;i++)\r\n {\r\n proba_vector[i]=q[i];\r\n }\r\n }else{\r\n for(L i=0; insamples;i++)\r\n {\r\n if(q[i]>1) q[i]=1;\r\n else {\r\n D deltaq=min(1-q[i],tmp);\r\n tmp=tmp-deltaq;\r\n q[i]+=deltaq;\r\n }\r\n proba_vector[i]=q[i];\r\n }\r\n }\r\n }\r\n\r\n\r\n\r\n void set_L2(L p_mod, L u){\r\n if(p_mod==0){ //batch sampling mode\r\n D tmp=0;\r\n D st;\r\n for(L i=0;insamples;i++){\r\n st=Li[i]/tilde_proba_vector[i];\r\n if (st>tmp) tmp=st;\r\n }\r\n L2=tmp/this->nsamples/tau;\r\n cout<<\"L2=\"<nsamples;i++){\r\n st=Li[i]/proba_vector[i];\r\n if(isolated_I[i]==1) st=st-Li[i];\r\n if(st>tmp) tmp=st;\r\n }\r\n L2=tmp/this->nsamples;\r\n }\r\n cout<<\"set_L2=\"<nsamples,1./this->nsamples);\r\n proba_vector.resize(this->nsamples,1-pow(1-1.0/this->nsamples,tau));\r\n max_p=1.0/this->nsamples;\r\n cout<<\"uniform=\"<c+0.0)/this->nsamples;\r\n proba_vector.clear();\r\n proba_vector.resize(this->nsamples,pi);\r\n }\r\n }\r\n\r\n\r\n\r\n\r\n void sort_p(){\r\n vector >a;\r\n for (L i = 0 ;i < this->nsamples ; i++) {\r\n a.push_back(make_pair(proba_vector[i],i)); // k = value, i = original index\r\n }\r\n sort(a.begin(),a.end());\r\n group_C.clear();\r\n group_C.resize(this->nsamples);\r\n isolated_I.clear();\r\n isolated_I.resize(this->nsamples,0);\r\n D tmp=0;\r\n D maxpi=0;\r\n D previous_i=0;\r\n index_group_C.clear();\r\n index_group_C.push_back(0);\r\n maxp_group_C.clear();\r\n sump_group_C.clear();\r\n\r\n for (L i = 0 ;i < this->nsamples ; i++){\r\n group_C[i]=a[this->nsamples-1-i].second;\r\n D pi=a[this->nsamples-1-i].first;\r\n if(tmp+pi<=1){\r\n if(pi>maxpi) maxpi=pi;\r\n tmp+=pi;\r\n }\r\n else{\r\n index_group_C.push_back(i);\r\n maxp_group_C.push_back(maxpi);\r\n sump_group_C.push_back(tmp);\r\n tmp=pi;\r\n maxpi=pi;\r\n if(i-previous_i==1) isolated_I[group_C[previous_i]]=1;\r\n previous_i=i;\r\n }\r\n }\r\n index_group_C.push_back(this->nsamples);\r\n maxp_group_C.push_back(maxpi);\r\n sump_group_C.push_back(tmp);\r\n nb_groups=sump_group_C.size();\r\n if(previous_i==this->nsamples-1) isolated_I[group_C[previous_i]]=1;\r\n cout<<\"size of group=\"<tilde_proba_vector[i])\r\n {\r\n i=(floor)(gsl_rng_uniform(rng)*n);\r\n y=gsl_rng_uniform(rng);\r\n }\r\n return i;\r\n }\r\n\r\n\r\n\r\n\r\n\r\n\r\n void set_initial_dual(){\r\n for(L i=0;insamples;i++)\r\n {\r\n D res=0;\r\n for (L k = this->ptr[i]; k < this->ptr[i + 1];k++)\r\n {\r\n L j=this->row_idx[k];\r\n res+=this->A[k]*primal_x[j];\r\n }\r\n dual_alpha[i]=gradient_of_phi_i(res,i);\r\n }\r\n }\r\n\r\n\r\n\r\n\r\n void update_primal()\r\n {\r\n L nb_indices=0;\r\n //#pragma omp parallel for\r\n for(L i_t=0;i_tptr[i]; k < this->ptr[i + 1];k++)\r\n {\r\n L j=this->row_idx[k];\r\n if (whether_or_not_to_do_prox[j]==0) {\r\n //#pragma omp critical\r\n {\r\n whether_or_not_to_do_prox[j]=1;\r\n index_to_do_prox[nb_indices]=j;\r\n nb_indices++;\r\n deltagk[j]=0;\r\n }\r\n }\r\n deltagk[j]+=lambda_f[i]*deltaalphai*this->A[k]*theta_S[i];\r\n }\r\n }\r\n #pragma omp parallel for\r\n for(L i_d=0;i_dptr[i]; k < this->ptr[i + 1];\tk++)\r\n {\r\n L j=this->row_idx[k];\r\n baralpha[j]+=lambda_f[i]*deltaalphai*this->A[k];\r\n }\r\n }\r\n\r\n\r\n\r\n D compute_AiTxk(L i) //This function compute A_i^\\top x^k\r\n {\r\n D res=0;\r\n D xj;\r\n for (L k = this->ptr[i]; k < this->ptr[i + 1];k++)\r\n {\r\n L j=this->row_idx[k];\r\n if(current_nb_iters!=last_update_i[j])\r\n {\r\n xj=compute_current_xj_value(baralpha[j], j,last_update_i[j],current_nb_iters);\r\n //update_x(xj,j);\r\n }\r\n res+=this->A[k]*primal_x[j];\r\n last_update_i[j]=current_nb_iters;\r\n }\r\n return res;\r\n }\r\n\r\n\r\n D compute_AiTxk_without_update(L i) //This function compute A_i^\\top x^k without updating x^k\r\n {\r\n D res=0;\r\n D xj;\r\n //#pragma omp parallel for reduction(+:res)\r\n for (L k = this->ptr[i]; k < this->ptr[i + 1];k++)\r\n {\r\n L j=this->row_idx[k];\r\n if(current_nb_iters!=last_update_i[j])\r\n {\r\n xj=compute_current_xj_value_without_update(baralpha[j], j,last_update_i[j],current_nb_iters);\r\n }\r\n else {\r\n xj=primal_x[j];\r\n }\r\n res+=this->A[k]*xj;\r\n }\r\n return res;\r\n }\r\n\r\n\r\n\r\n\r\n void compute_dual_value()\r\n {\r\n D res=0;\r\n //D alphaAx= 0;\r\n std::vector alpha_tmp(this->nsamples,0);\r\n std::vector baralpha_tmp(this->nfeatures,0);\r\n //#pragma omp parallel for schedule(dynamic)\r\n for(L i=0;insamples;i++)\r\n {\r\n D aitx=compute_AiTxk_without_update(i);\r\n alpha_tmp[i]=gradient_of_phi_i(aitx,i);\r\n //alphaAx+= lambda_f[i]*alpha_tmp[i]*aitx;\r\n for (L k = this->ptr[i]; k < this->ptr[i + 1];\tk++)\r\n {\r\n L j=this->row_idx[k];\r\n baralpha_tmp[j]+=lambda_f[i]*alpha_tmp[i]*this->A[k];\r\n }\r\n }\r\n\r\n D scal=feasible_dual(baralpha_tmp);\r\n //#pragma omp parallel for reduction(-:res)\r\n for(L i=0;insamples;i++)\r\n {\r\n res-=value_of_phistar_i(scal*alpha_tmp[i],i)*lambda_f[i];\r\n }\r\n res-=value_of_gstar_minus(baralpha_tmp,scal); // should have used value_of_gstar(-baralpha)\r\n dual_value=res;\r\n }\r\n\r\n void compute_primal_value()\r\n {\r\n D res=0;\r\n //#pragma omp parallel for reduction(+:res)\r\n for(L i=0;insamples;i++)\r\n {\r\n D aitx=compute_AiTxk_without_update(i);\r\n res+=lambda_f[i]*value_of_phi_i(aitx,i);\r\n }\r\n\r\n D res2=0;\r\n //#pragma omp parallel for reduction(+:res2)\r\n for(L j=0; jnfeatures; j++)\r\n {\r\n D xj=compute_current_xj_value_without_update(baralpha[j], j,last_update_i[j],current_nb_iters);\r\n D gj=value_of_g_j(xj,j);\r\n res2+=gj;\r\n }\r\n primal_value= res+res2;\r\n }\r\n\r\n\r\n\r\n\r\n void compute_initial_dual_value()\r\n {\r\n\r\n D res=0;\r\n D scal=feasible_dual(baralpha);\r\n #pragma omp parallel for reduction(-:res)\r\n for(L i=0;insamples;i++)\r\n {\r\n res-=value_of_phistar_i(scal*dual_alpha[i],i)*lambda_f[i];\r\n }\r\n //cout<< \"d_1(x)= \"<< res<< \" d_2(x)= \"<< value_of_gstar_minus(baralpha,scal)<< endl;\r\n res-=value_of_gstar_minus(baralpha,scal); // should have used value_of_gstar(-baralpha)\r\n dual_value=res;\r\n }\r\n\r\n\r\n void compute_initial_primal_value()\r\n {\r\n D res=0;\r\n #pragma omp parallel for reduction(+:res)\r\n for(L j=0; jnfeatures; j++)\r\n {\r\n res+=value_of_g_j(primal_x[j],j);\r\n }\r\n D res2=0;\r\n #pragma omp parallel for reduction(+:res2)\r\n for(L i=0;insamples;i++)\r\n {\r\n D aitx=0;\r\n for (L k = this->ptr[i]; k < this->ptr[i + 1];\tk++)\r\n {\r\n L j=this->row_idx[k];\r\n aitx+=this->A[k]*primal_x[j];\r\n }\r\n res2+=lambda_f[i]*value_of_phi_i(aitx,i);\r\n }\r\n //cout<< \"p_1(x)= \"<< res<< \" p_2(x)= \"<< res2<< endl;\r\n primal_value= res+res2;\r\n }\r\n\r\n\r\n\r\n void set_p(D scal_p){\r\n\r\n if(scal_p==4.6){\r\n p=sqrt(this->mu/L1*tau/this->nsamples);\r\n }\r\n else if (scal_p==5.6){\r\n p=this->mu/L1;\r\n }\r\n else{\r\n p=scal_p*tau/(0.0+this->nsamples);\r\n }\r\n cout<<\"changing probablity: \"< & x0, vector & w0, vector & L_phi, D val_mu, D val_epsilon, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p)\r\n {\r\n cout<<\"start initializing\"<<\" u=\"<distributed_set_up(nb_c);\r\n if(nb_tau>this->noverc) perror(\"tau should be less than n over c\");\r\n tau=nb_tau;\r\n nb_of_iters_per_loop=floor(this->nsamples/(this->c*(tau+0.0)));\r\n batch_i.clear();\r\n batch_deltaalphai.clear();\r\n batch_i.resize(this->nsamples,0);\r\n batch_deltaalphai.resize(this->nsamples,0);\r\n\r\n deltagk.clear();\r\n deltagk.resize(this->nfeatures,0);\r\n index_to_do_prox.clear();\r\n index_to_do_prox.resize(this->nfeatures,-1);\r\n whether_or_not_to_do_prox.clear();\r\n whether_or_not_to_do_prox.resize(this->nfeatures,0);\r\n gk.clear();\r\n gk.resize(this->nfeatures,0);\r\n\r\n /**setup parameters**/\r\n epsilon=val_epsilon;\r\n max_nb_loops=max_nb;\r\n this->mu=val_mu;\r\n cout<<\"mu=\"<mu<nsamples,0); //L_phi is the Lipschitz constant of the function \\phi_i.\r\n for(int i=0;i< this->nsamples; i++){\r\n lambda_f[i]= L_phi[i]/this->nsamples;\r\n }\r\n\r\n set_rng();\r\n set_auxiliary_v();\r\n\r\n\r\n lambda_1=get_lambda1();\r\n lambda_2=get_lambda2();\r\n\r\n set_Li_Lf();\r\n\r\n running_time=0;\r\n /**setup probability**/\r\n if(p_mod==0) // batch sampling (stochastic process as defined in the paper)\r\n {\r\n if(u==0) // uniform sampling\r\n {\r\n set_uniform_probability(p_mod);\r\n this->uniform=\"uniform\";\r\n }\r\n else{\r\n set_optimal_probability();\r\n this->uniform=\"nonuniform\";\r\n }\r\n }\r\n else{ //group sampling\r\n if(u==0){\r\n set_uniform_probability(p_mod);\r\n this->uniform=\"uniform\";\r\n }else{\r\n this->set_group_sampling_probability();\r\n this->uniform=\"nonuniform\";\r\n }\r\n sort_p();\r\n cout<<\"sort p\"<nfeatures,0);\r\n last_update_i.clear();\r\n last_update_i.resize(this->nfeatures,0);\r\n for(L i=0;insamples;i++)\r\n {\r\n update_baralpha(i, dual_alpha[i]);\r\n }\r\n\r\n current_nb_iters=0;\r\n D start_time_initial=std::clock();\r\n compute_initial_primal_value();\r\n compute_initial_dual_value();\r\n D end_time_initial=std::clock();\r\n cout<<\"computation of initial primal dual value time=\"<<(end_time_initial-start_time_initial) / (double) CLOCKS_PER_SEC<nfeatures;j++){\r\n result <nsamples;i++)\r\n resulta << setprecision(20)<nfeatures;j++)\r\n {\r\n recordw0>>primal_x[j];\r\n }\r\n recordw0.close();\r\n\r\n ifstream recordalpha0(\"results/alpha0.dat\");\r\n for(L i=0;insamples;i++)\r\n {\r\n recordalpha0>>dual_alpha[i];\r\n }\r\n recordalpha0.close();\r\n }\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n void compute_and_record_result()\r\n {\r\n if(nb_loops%print_every_N==0){\r\n D start = std::clock();\r\n compute_primal_value();\r\n D endt=std::clock();\r\n cout<<\"computation of primal value time=\"<<(endt-start) / (double) CLOCKS_PER_SEC<c*tau/(this->nsamples)))<<\";;; \"<c*tau/(this->nsamples)))<<\" \"<nsamples);\r\n batch_i[batch_size]=i;\r\n batch_size++;\r\n }\r\n }\r\n\r\n\r\n void set_thetaS(L p_mod){\r\n theta_S.clear();\r\n theta_S.resize(this->nsamples,0);\r\n if(p_mod==0){\r\n for(L i=0;insamples;i++)\r\n theta_S[i]=1.0/(tau*tilde_proba_vector[i]);\r\n }\r\n else{\r\n for(L i=0;insamples;i++)\r\n theta_S[i]=1.0/proba_vector[i];\r\n }\r\n }\r\n\r\n void group_sampling(){\r\n batch_size=0;\r\n std::vector sampled_groups;\r\n for(L i=0;iproba_vector[group_C[i]])\r\n {\r\n i=s1+(floor)(gsl_rng_uniform(rng)*(s2-s1));\r\n y=gsl_rng_uniform(rng);\r\n }\r\n batch_i[t]=group_C[i];\r\n }\r\n }\r\n\r\n\r\n\r\n\r\n void loopless(vector & x0, vector & w0, string filename, vector & L_phi, D val_mu, D val_epsilon, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p)\r\n {\r\n initialize(x0, w0, L_phi, val_mu, val_epsilon, max_nb, nb_tau, nb_c, u, p_mod, scal_p);\r\n string sampname=\"results/L_\"+filename+uniform;\r\n if(p_mod==0) sampname=sampname+\"_batch\";\r\n else sampname=sampname+\"_group\";\r\n string scal_str;\r\n stringstream scal_convert;\r\n scal_convert<c*tau/(this->nsamples))<<\" \"<=epsilon && nb_loops=epsilon) {compute_primal_value();\r\n compute_dual_value();\r\n delta=primal_value-dual_value;\r\n cout<c*tau/(this->nsamples)))<<\"; \"<c*tau/(this->nsamples)))<<\" \"<c*tau/(this->nsamples)))<<\"; delta: \"< & x0, vector & w0, string filename, vector & L_phi, D val_mu, D val_epsilon, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p)\r\n {\r\n initialize(x0, w0, L_phi, val_mu, val_epsilon, max_nb, nb_tau, nb_c, u, p_mod, scal_p);\r\n string sampname=\"results/L_\"+filename+uniform;\r\n if(p_mod==0) sampname=sampname+\"_batch\";\r\n else sampname=sampname+\"_group\";\r\n string scal_str;\r\n stringstream scal_convert;\r\n scal_convert<c*tau/(this->nsamples))<<\" \"<c*tau/(this->nsamples)))<<\"; delta: \"<\n#include \n#include \n#include \"dtfi.h\"\n\n#ifdef HAVE_GSL\n#include \n#include \n\n// mu is the average value\nunsigned int randomPoisson(double mu)\n{\n static int first_call = 1;\n static const gsl_rng_type *T;\n static gsl_rng * r;\n \n if (first_call) {\n first_call=0;\n gsl_rng_env_setup();\n T = gsl_rng_default;\n r = gsl_rng_alloc(T);\n }\n \n return gsl_ran_poisson (r, mu);\n}\n\nvoid randomSimplexCoords(double **coord, int ndims, double *result, double *P)\n{\n static int first_call = 1;\n static const gsl_rng_type *T;\n static gsl_rng * r;\n int i,j,k;\n double u;\n //double P[50];\n \n if (first_call) {\n first_call=0;\n gsl_rng_env_setup();\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n }\n\n result[0]=gsl_rng_uniform (r);\n \n if (ndims==3)\n {\n u=gsl_rng_uniform (r);\n if (uresult[k])\n\t\t {\n\t\t double tmp = result[k];\n\t\t result[k]=result[j];\n\t\t result[j]=tmp;\n\t\t }\n\t\t}\n\t }\n\t}\n }\n \n P[0]=result[0];\n for (i=1;i100) printf(\"negen = %d\\n\",ngen);\n\n if (first_call) {\n first_call=0;\n gsl_rng_env_setup();\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n }\n \n if (Proba!=NULL) {\n pmax_inv=0;\n for (i=0;ipmax_inv) pmax_inv=Proba[i];\n pmax_inv=(double)1./pmax_inv;\n }\n\n for (n=0;n\n#else\n#include \n#endif\n\n#include \n#include \n\n#include \n\n/**\n\n Vector class.\n\n*/\n\nclass irtkVector : public irtkObject\n{\n\nprotected:\n\n /// Number of rows\n int _rows;\n\n /// Data\n double *_vector;\n\npublic:\n\n /// Default constructor\n irtkVector();\n\n /// Constructor for given row dimensions\n irtkVector(int);\n\n /// Copy constructor\n irtkVector(const irtkVector &);\n\n /// Destructor\n ~irtkVector();\n\n /// Intialize matrix with number of rows\n void Initialize(int);\n\n //\n // Vector access functions\n //\n\n /// Returns number of rows\n int Rows() const;\n\n /// Puts vector value\n void Put(int, double);\n\n /// Gets vector value\n double Get(int) const;\n\n //\n // Operators for vector access\n //\n\n /// Puts vector value\n double &operator()(int);\n\n /// Gets vector value\n double operator()(int) const;\n\n //\n // Vector operators for doubles\n //\n\n /// Subtraction of a double\n irtkVector& operator-=(double);\n\n /// Addition of a double\n irtkVector& operator+=(double);\n\n /// Multiplication with a double\n irtkVector& operator*=(double);\n\n /// Division by a double\n irtkVector& operator/=(double);\n\n /// Return result of subtraction of a double\n irtkVector operator- (double);\n\n /// Return result of addition of a double\n irtkVector operator+ (double);\n\n /// Return result of multiplication with a double\n irtkVector operator* (double);\n\n /// Return result of division by a double\n irtkVector operator/ (double);\n\n //\n // Vector operators for vectors\n //\n\n /// Vector copy operator\n irtkVector& operator =(const irtkVector&);\n\n /// Vector subtraction operator\n irtkVector& operator-=(const irtkVector&);\n\n /// Vector addition operator\n irtkVector& operator+=(const irtkVector&);\n\n /// Vector componentwise multiplication operator (no scalar nor cross product)\n irtkVector& operator*=(const irtkVector&);\n\n /// Vector componentwise division operator\n irtkVector& operator/=(const irtkVector&);\n\n /// Return result for vector subtraction\n irtkVector operator- (const irtkVector&);\n\n /// Return result for vector addition\n irtkVector operator+ (const irtkVector&);\n\n /// Return result for componentwise vector multiplication (no scalar nor cross product)\n irtkVector operator* (const irtkVector&);\n\n /// Return result for componentwise vector division\n irtkVector operator/ (const irtkVector&);\n\n /// Comparison operator ==\n bool operator==(const irtkVector &);\n\n#ifndef USE_STL\n /// Comparison operator != (if USE_STL is defined, negate == operator)\n bool operator!=(const irtkVector &);\n#endif\n\n /// Comparison operator <\n bool operator<(const irtkVector &);\n\n /// Scalar/dot product\n double ScalarProduct(const irtkVector&);\n\n /// Vector/cross product\n irtkVector CrossProduct(const irtkVector&);\n\n /// Returns norm of a vector\n double Norm(void) const;\n\n /// Vector normalization\n void Normalize(void);\n\n //\n // Vector in- and output\n //\n\n /// Interface to output stream\n friend std::ostream& operator<< (std::ostream&, const irtkVector&);\n\n /// Interface to input stream\n friend std::istream& operator>> (std::istream&, irtkVector&);\n\n /// Print vector\n void Print();\n\n /// Read vector from file\n void Read (char *);\n\n /// Write vector to file\n void Write(char *);\n\n\n#ifdef USE_VXL\n template void Vector2Vnl(vnl_diag_matrix*) const;\n\n template void Vnl2Vector(vnl_diag_matrix*);\n\n#else\n /// Conversion to GSL vector (memory must be allocated)\n void Vector2GSL(gsl_vector *) const;\n\n /// Conversion from GSL vector\n void GSL2Vector(gsl_vector *);\n#endif\n\n};\n\n//\n// Access operators\n//\n\ninline int irtkVector::Rows() const\n{\n return _rows;\n}\n\ninline void irtkVector::Put(int rows, double vector)\n{\n _vector[rows] = vector;\n}\n\ninline double irtkVector::Get(int rows) const\n{\n return _vector[rows];\n}\n\ninline double& irtkVector::operator()(int rows)\n{\n return _vector[rows];\n}\n\ninline double irtkVector::operator()(int rows) const\n{\n return _vector[rows];\n}\n\n//\n// Vector operators for doubles\n//\n\ninline irtkVector& irtkVector::operator-=(double x)\n{\n int i;\n\n for (i = 0; i < _rows; i++) {\n _vector[i] -= x;\n }\n\n return *this;\n}\n\ninline irtkVector& irtkVector::operator+=(double x)\n{\n int i;\n\n for (i = 0; i < _rows; i++) {\n _vector[i] += x;\n }\n\n return *this;\n}\n\ninline irtkVector& irtkVector::operator*=(double x)\n{\n int i;\n\n for (i = 0; i < _rows; i++) {\n _vector[i] *= x;\n }\n\n return *this;\n}\n\ninline irtkVector& irtkVector::operator/=(double x)\n{\n int i;\n\n for (i = 0; i < _rows; i++) {\n _vector[i] /= x;\n }\n\n return *this;\n}\n\ninline irtkVector irtkVector::operator- (double x)\n{\n int i;\n\n irtkVector m(_rows);\n for (i = 0; i < _rows; i++) {\n m._vector[i] = _vector[i] - x;\n }\n return m;\n}\n\ninline irtkVector irtkVector::operator+ (double x)\n{\n int i;\n\n irtkVector m(_rows);\n for (i = 0; i < _rows; i++) {\n m._vector[i] = _vector[i] + x;\n }\n return m;\n}\n\ninline irtkVector irtkVector::operator* (double x)\n{\n int i;\n\n irtkVector m(_rows);\n for (i = 0; i < _rows; i++) {\n m._vector[i] = _vector[i] * x;\n }\n return m;\n}\n\ninline irtkVector irtkVector::operator/ (double x)\n{\n int i;\n\n irtkVector m(_rows);\n for (i = 0; i < _rows; i++) {\n m._vector[i] = _vector[i] / x;\n }\n return m;\n}\n\n//\n// Vector operators for vectors\n//\n\ninline irtkVector& irtkVector::operator =(const irtkVector& v)\n{\n int i;\n\n // Copy size\n this->Initialize(v._rows);\n\n // Copy vector\n for (i = 0; i < _rows; i++) {\n _vector[i] = v._vector[i];\n }\n return *this;\n}\n\ninline irtkVector& irtkVector::operator-=(const irtkVector& v)\n{\n int i;\n\n if (_rows != v._rows) {\n std::cerr << \"irtkVector::operator-=: Size mismatch\" << std::endl;\n exit(1);\n }\n for (i = 0; i < _rows; i++) {\n _vector[i] -= v._vector[i];\n }\n\n return *this;\n}\n\ninline irtkVector& irtkVector::operator+=(const irtkVector& v)\n{\n int i;\n\n if (_rows != v._rows) {\n std::cerr << \"irtkVector::operator+=: Size mismatch\" << std::endl;\n exit(1);\n }\n for (i = 0; i < _rows; i++) {\n _vector[i] += v._vector[i];\n }\n\n return *this;\n}\n\ninline irtkVector& irtkVector::operator*=(const irtkVector& v)\n{\n int i;\n\n if (_rows != v._rows) {\n std::cerr << \"irtkVector::operator*=: Size mismatch\" << std::endl;\n exit(1);\n }\n for (i = 0; i < _rows; i++) {\n _vector[i] *= v._vector[i];\n }\n\n return *this;\n}\n\ninline irtkVector& irtkVector::operator/=(const irtkVector& v)\n{\n int i;\n\n if (_rows != v._rows) {\n std::cerr << \"irtkVector::operator/=: Size mismatch\" << std::endl;\n exit(1);\n }\n for (i = 0; i < _rows; i++) {\n _vector[i] /= v._vector[i];\n }\n\n return *this;\n}\n\ninline irtkVector irtkVector::operator- (const irtkVector& v)\n{\n int i;\n\n if (_rows != v._rows) {\n std::cerr << \"irtkVector::operator-: Size mismatch\" << std::endl;\n exit(1);\n }\n irtkVector m(_rows);\n for (i = 0; i < _rows; i++) {\n m._vector[i] = _vector[i] - v._vector[i];\n }\n return m;\n}\n\ninline irtkVector irtkVector::operator+ (const irtkVector& v)\n{\n int i;\n\n if (_rows != v._rows) {\n std::cerr << \"irtkVector::operator+: Size mismatch\" << std::endl;\n exit(1);\n }\n irtkVector m(_rows);\n for (i = 0; i < _rows; i++) {\n m._vector[i] = _vector[i] + v._vector[i];\n }\n return m;\n}\n\ninline irtkVector irtkVector::operator* (const irtkVector& v)\n{\n int i;\n\n if (_rows != v._rows) {\n std::cerr << \"irtkVector::operator*: Size mismatch\" << std::endl;\n exit(1);\n }\n irtkVector m(_rows);\n for (i = 0; i < _rows; i++) {\n m._vector[i] = _vector[i] * v._vector[i];\n }\n return m;\n}\n\ninline irtkVector irtkVector::operator/ (const irtkVector& v)\n{\n int i;\n\n if (_rows != v._rows) {\n std::cerr << \"irtkVector::operator/: Size mismatch\" << std::endl;\n exit(1);\n }\n irtkVector m(_rows);\n for (i = 0; i < _rows; i++) {\n m._vector[i] = _vector[i] / v._vector[i];\n }\n return m;\n}\n\n//\n// Comparison\n//\n\ninline bool irtkVector::operator==(const irtkVector &v)\n{\n if (_rows != v._rows) {\n return false;\n }\n for (int i = 0; i < _rows; i++) {\n if (_vector[i] != v._vector[i]) return false;\n }\n return true;\n\n}\n\n#ifndef USE_STL\ninline bool irtkVector::operator!=(const irtkVector &v)\n{\n if (_rows != v._rows) {\n return true;\n }\n for (int i = 0; i < _rows; i++) {\n if (_vector[i] != v._vector[i]) return true;\n }\n return false;\n}\n#endif\n\ninline bool irtkVector::operator<(const irtkVector &v)\n{\n if (_rows > v._rows) {\n return false;\n }\n for (int i = 0; i < _rows; i++) {\n if (_vector[i] >= v._vector[i]) return false;\n }\n return true;\n\n}\n\n//\n// Vector products\n//\n\ninline double irtkVector::ScalarProduct(const irtkVector &v)\n{\n int i;\n double scalar_product=0;\n\n if (_rows != v._rows) {\n std::cerr << \"irtkVector::ScalarProduct: Size mismatch\" << std::endl;\n exit(1);\n }\n\n for (i = 0; i < _rows; i++) {\n scalar_product += _vector[i]*v._vector[i];\n }\n return scalar_product;\n}\n\ninline irtkVector irtkVector::CrossProduct(const irtkVector &v)\n{\n int i;\n\n if (_rows != v._rows) {\n std::cerr << \"irtkVector::CrossProduct: Size mismatch\" << std::endl;\n exit(1);\n }\n\n irtkVector m(_rows);\n for (i = 0; i < _rows; i++) {\n m._vector[i] = (_vector[(i+1)%_rows]*v._vector[(i+2)%_rows]-\n _vector[(i+2)%_rows]*v._vector[(i+1)%_rows]);\n }\n return m;\n}\n\n\n//\n// Functions\n//\n\ninline double irtkVector::Norm(void) const\n{\n double norm = 0;\n\n for (int i = 0; i < _rows; i++) {\n norm += _vector[i]*_vector[i];\n }\n return std::sqrt(norm);\n}\n\ninline void irtkVector::Normalize(void)\n{\n double norm = Norm();\n\n if (norm != 0) {\n *this /= norm;\n }\n}\n\n#ifdef USE_VXL\n\ntemplate \ninline void irtkVector::Vector2Vnl(vnl_diag_matrix* m) const\n{\n unsigned i;\n\n for (i = 0; i < (unsigned) _rows; i++) {\n (*m)(i) = (T) _vector[i];\n }\n}\n\ntemplate \ninline void irtkVector::Vnl2Vector(vnl_diag_matrix* m)\n{\n unsigned i;\n\n for (i = 0; i < (unsigned) _rows; i++) {\n _vector[i] = (float) (*m)(i);\n }\n}\n\n#endif\n\n#endif\n\n\n", "meta": {"hexsha": "1b58babdd7e7219c1a17763b3ebffa27ac462357", "size": 10717, "ext": "h", "lang": "C", "max_stars_repo_path": "source/IRTKSimple2/geometry++/include/irtkVector.h", "max_stars_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_stars_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_stars_repo_licenses": ["Zlib", "Unlicense", "Intel", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/IRTKSimple2/geometry++/include/irtkVector.h", "max_issues_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_issues_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_issues_repo_licenses": ["Zlib", "Unlicense", "Intel", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/IRTKSimple2/geometry++/include/irtkVector.h", "max_forks_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_forks_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_forks_repo_licenses": ["Zlib", "Unlicense", "Intel", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0117647059, "max_line_length": 89, "alphanum_fraction": 0.6132313147, "num_tokens": 3347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.4404024734171551}} {"text": "/**\n * A metropolis hasting sampler for bremsstrahlung and pair production cross sections \n *\n * copyright (C) 2007\n * the icecube collaboration\n *\n * $Id: I3MetropolisHastings.h 143040 2016-03-11 17:35:25Z nega $\n *\n * @version $Revision: 143040 $\n * @date $LastChangedDate: 2016-03-11 10:35:25 -0700 (Fri, 11 Mar 2016) $\n * @author Bernhard Voigt $LastChangedBy$\n */\n\n#ifndef I3METROPOLISHASTINGS_h_\n#define I3METROPOLISHASTINGS_h_\n\n// icetray includes\n#include \"icetray/I3Logging.h\"\n#include \"cmc/I3CascadeMCCommon.h\"\n\n// gsl includes\n#include \n\n// c++ includes\n#include \n\n/**\n * @brief This class implements a Metropolis Hastings sampler\n *\n * It uses a pdf and a proposal distribution to efficiently\n * produce random samples from the pdf\n *\n * The proposal distribution used is a beta distribution, which\n * matches almost the shape of the bremsstrahlung and pair production\n * cross sections, using the right parameters. See I3CascadeSimulation\n * for the usage.\n *\n * For details on the algorithm, take a look at :\n * http://en.wikipedia.org/wiki/Metropolis-Hastings_algorithm\n */\nclass I3MetropolisHastings : public I3CascadeMCCommon::Sampler {\n\n // set logging name for icetray\n SET_LOGGER(\"I3MetropolisHastings\");\n\n public:\n\n /**\n * Default Constructor\n */\n I3MetropolisHastings() {}\n\n /**\n * Constructor\n *\n * @param rng a gsl_random instance\n * @param pdf a function with two parameters, ie. the energy and\n * fractional energy of the cross section\n * @param proposal a gsl random instance sampling from the proposal\n * distribution which is a beta distribution\n * @param proposalDistribution a beta function in x\n * @param name name of this instance for logging purposes\n *\n * The proposal gsl random instance as well as the proposalDistribution are implemented \n * in a struct beta_dist in the header file I3CascadeSimulation.h\n */\n I3MetropolisHastings(I3RandomServicePtr rng,\n double (*pdf)(const double&, const double&), \n double (*proposal)(const gsl_rng*),\n double (*proposalDistribution)(const double&),\n std::string name);\n\n /**\n * Get the total sample loop count \n */\n unsigned long GetCounter() {\n return counter_;\n }\n\n /**\n * Reset the total sample loop count\n */\n void ResetCounter() {\n counter_ = 0;\n }\n\n /**\n * Get the number of returned samples\n */\n unsigned long GetYield() {\n return yield_;\n }\n\n /**\n * Reset the number of returned samples\n */\n void ResetYield() {\n yield_ = 0;\n }\n\n\n /**\n * Samples n times starting at start position\n *\n * Used to forget the initial state\n *\n * @param energy parameter of underlying pdf\n * @param start starting position\n * @param n number of samples\n */\n void BurnIn(double energy, double start, unsigned int n=100);\n\n /**\n * Samples the underlying pdf in the given range\n *\n * @param energy parameter to the underlying pdf\n * @param lower edge of sample range\n * @param higher edge of sample range\n * @return random number\n */\n double Sample(double energy, double lower=0, double higher=1);\n\n private:\n\n /**\n * @brief pdf, ie a cross section with energy and fractional energy parameters\n */\n double (*pdf_)(const double&, const double&);\n\n /**\n * @brief a gls random instance drawing samples from the proposal distribution\n */\n double (*proposal_)(const gsl_rng*);\n\n /**\n * @brief a proposal distribution, in this case a beta distribution in x\n */\n double (*proposalDistribution_)(const double&);\n\n /**\n * @brief loop counter\n */\n unsigned long counter_;\n\n /**\n * @brief counts how many successful attemps have been made to draw a new random number\n */\n unsigned long yield_;\n\n /**\n * @brief name of this instance, for logging purpose\n */\n std::string name_;\n\n /**\n * @brief last drawn sample\n */\n double x_;\n\n /**\n * @brief last value of pdf(x)\n */\n double y_;\n\n /**\n * @brief last value of proposalDist(x)\n */\n double propDistY_;\n\n};\n\n#endif\n\n\n\n", "meta": {"hexsha": "018c2d87b37ce34c03e13ebeb3bbca5d6648acf8", "size": 4163, "ext": "h", "lang": "C", "max_stars_repo_path": "cmc/private/cmc/I3MetropolisHastings.h", "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_issues_repo_path": "cmc/private/cmc/I3MetropolisHastings.h", "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmc/private/cmc/I3MetropolisHastings.h", "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "avg_line_length": 23.6534090909, "max_line_length": 90, "alphanum_fraction": 0.6613019457, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.43975383093891296}} {"text": "/* sum/levin_utrunc.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n\nint\ngsl_sum_levin_utrunc_accel (const double *array,\n const size_t array_size,\n gsl_sum_levin_utrunc_workspace * w,\n double *sum_accel, double *abserr_trunc)\n{\n return gsl_sum_levin_utrunc_minmax (array, array_size,\n 0, array_size - 1,\n w, sum_accel, abserr_trunc);\n}\n\n\nint\ngsl_sum_levin_utrunc_minmax (const double *array,\n const size_t array_size,\n const size_t min_terms,\n const size_t max_terms,\n gsl_sum_levin_utrunc_workspace * w,\n double *sum_accel, double *abserr_trunc)\n{\n if (array_size == 0)\n {\n *sum_accel = 0.0;\n *abserr_trunc = 0.0;\n w->sum_plain = 0.0;\n w->terms_used = 0;\n return GSL_SUCCESS;\n }\n else if (array_size == 1)\n {\n *sum_accel = array[0];\n *abserr_trunc = GSL_POSINF;\n w->sum_plain = array[0];\n w->terms_used = 1;\n return GSL_SUCCESS;\n }\n else\n {\n const double SMALL = 0.01;\n const size_t nmax = GSL_MAX (max_terms, array_size) - 1;\n double trunc_n = 0.0, trunc_nm1 = 0.0;\n double actual_trunc_n = 0.0, actual_trunc_nm1 = 0.0;\n double result_n = 0.0, result_nm1 = 0.0;\n size_t n;\n int better = 0;\n int before = 0;\n int converging = 0;\n double least_trunc = GSL_DBL_MAX;\n double result_least_trunc;\n\n /* Calculate specified minimum number of terms. No convergence\n tests are made, and no truncation information is stored. */\n\n for (n = 0; n < min_terms; n++)\n {\n const double t = array[n];\n\n result_nm1 = result_n;\n gsl_sum_levin_utrunc_step (t, n, w, &result_n);\n }\n\n /* Assume the result after the minimum calculation is the best. */\n\n result_least_trunc = result_n;\n\n /* Calculate up to maximum number of terms. Check truncation\n condition. */\n\n for (; n <= nmax; n++)\n {\n const double t = array[n];\n\n result_nm1 = result_n;\n gsl_sum_levin_utrunc_step (t, n, w, &result_n);\n\n /* Compute the truncation error directly */\n\n actual_trunc_nm1 = actual_trunc_n;\n actual_trunc_n = fabs (result_n - result_nm1);\n\n /* Average results to make a more reliable estimate of the\n real truncation error */\n\n trunc_nm1 = trunc_n;\n trunc_n = 0.5 * (actual_trunc_n + actual_trunc_nm1);\n\n /* Determine if we are in the convergence region. */\n\n better = (trunc_n < trunc_nm1 || trunc_n < SMALL * fabs (result_n));\n converging = converging || (better && before);\n before = better;\n\n if (converging)\n {\n if (trunc_n < least_trunc)\n {\n /* Found a low truncation point in the convergence\n region. Save it. */\n\n least_trunc = trunc_n;\n result_least_trunc = result_n;\n }\n\n if (fabs (trunc_n / result_n) < 10.0 * GSL_MACH_EPS)\n break;\n }\n }\n\n if (converging)\n {\n /* Stopped in the convergence region. Return result and\n error estimate. */\n\n *sum_accel = result_least_trunc;\n *abserr_trunc = least_trunc;\n w->terms_used = n;\n return GSL_SUCCESS;\n }\n else\n {\n /* Never reached the convergence region. Use the last\n calculated values. */\n\n *sum_accel = result_n;\n *abserr_trunc = trunc_n;\n w->terms_used = n;\n return GSL_SUCCESS;\n }\n }\n}\n\nint\ngsl_sum_levin_utrunc_step (const double term,\n const size_t n,\n gsl_sum_levin_utrunc_workspace * w, double *sum_accel)\n{\n if (term == 0.0)\n {\n /* This is actually harmless when treated in this way. A term\n which is exactly zero is simply ignored; the state is not\n changed. We return GSL_EZERODIV as an indicator that this\n occured. */\n\n return GSL_EZERODIV;\n }\n else if (n == 0)\n {\n *sum_accel = term;\n w->sum_plain = term;\n w->q_den[0] = 1.0 / term;\n w->q_num[0] = 1.0;\n return GSL_SUCCESS;\n }\n else\n {\n double factor = 1.0;\n double ratio = (double) n / (n + 1.0);\n int j;\n\n w->sum_plain += term;\n w->q_den[n] = 1.0 / (term * (n + 1.0) * (n + 1.0));\n w->q_num[n] = w->sum_plain * w->q_den[n];\n\n for (j = n - 1; j >= 0; j--)\n {\n double c = factor * (j + 1) / (n + 1);\n factor *= ratio;\n w->q_den[j] = w->q_den[j + 1] - c * w->q_den[j];\n w->q_num[j] = w->q_num[j + 1] - c * w->q_num[j];\n }\n\n *sum_accel = w->q_num[0] / w->q_den[0];\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "03bf8bc041006b4262f3b52c61bf4a8d8e5a8f55", "size": 5992, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/sum/levin_utrunc.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/sum/levin_utrunc.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/sum/levin_utrunc.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 29.5172413793, "max_line_length": 81, "alphanum_fraction": 0.5498998665, "num_tokens": 1599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4397311460614448}} {"text": "#include \n#include \n#include \"../problems/neo-hookean.h\"\n\n// Build libCEED context object\nPetscErrorCode PhysicsContext_NH(MPI_Comm comm, Ceed ceed, Units *units,\n CeedQFunctionContext *ctx) {\n PetscErrorCode ierr;\n Physics_NH phys;\n\n PetscFunctionBegin;\n\n ierr = PetscMalloc1(1, units); CHKERRQ(ierr);\n ierr = PetscMalloc1(1, &phys); CHKERRQ(ierr);\n ierr = ProcessPhysics_NH(comm, phys, *units); CHKERRQ(ierr);\n CeedQFunctionContextCreate(ceed, ctx);\n CeedQFunctionContextSetData(*ctx, CEED_MEM_HOST, CEED_COPY_VALUES,\n sizeof(*phys), phys);\n ierr = PetscFree(phys); CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n\n// Build libCEED smoother context object\nPetscErrorCode PhysicsSmootherContext_NH(MPI_Comm comm, Ceed ceed,\n CeedQFunctionContext ctx, CeedQFunctionContext *ctx_smoother) {\n PetscErrorCode ierr;\n PetscScalar nu_smoother = 0;\n PetscBool nu_flag = PETSC_FALSE;\n Physics_NH phys, phys_smoother;\n\n PetscFunctionBegin;\n\n ierr = PetscOptionsBegin(comm, NULL,\n \"Neo-Hookean physical parameters for smoother\", NULL);\n CHKERRQ(ierr);\n\n ierr = PetscOptionsScalar(\"-nu_smoother\", \"Poisson's ratio for smoother\",\n NULL, nu_smoother, &nu_smoother, &nu_flag);\n CHKERRQ(ierr);\n\n ierr = PetscOptionsEnd(); CHKERRQ(ierr); // End of setting Physics\n\n if (nu_flag) {\n // Copy context\n CeedQFunctionContextGetData(ctx, CEED_MEM_HOST, &phys);\n ierr = PetscMalloc1(1, &phys_smoother); CHKERRQ(ierr);\n ierr = PetscMemcpy(phys_smoother, phys, sizeof(*phys)); CHKERRQ(ierr);\n CeedQFunctionContextRestoreData(ctx, &phys);\n // Create smoother context\n CeedQFunctionContextCreate(ceed, ctx_smoother);\n phys_smoother->nu = nu_smoother;\n CeedQFunctionContextSetData(*ctx_smoother, CEED_MEM_HOST, CEED_COPY_VALUES,\n sizeof(*phys_smoother), phys_smoother);\n ierr = PetscFree(phys_smoother); CHKERRQ(ierr);\n } else {\n *ctx_smoother = NULL;\n }\n\n PetscFunctionReturn(0);\n}\n\n// Process physics options - Neo-Hookean\nPetscErrorCode ProcessPhysics_NH(MPI_Comm comm, Physics_NH phys, Units units) {\n PetscErrorCode ierr;\n PetscBool nu_flag = PETSC_FALSE;\n PetscBool Young_flag = PETSC_FALSE;\n phys->nu = 0;\n phys->E = 0;\n units->meter = 1; // 1 meter in scaled length units\n units->second = 1; // 1 second in scaled time units\n units->kilogram = 1; // 1 kilogram in scaled mass units\n\n PetscFunctionBeginUser;\n\n ierr = PetscOptionsBegin(comm, NULL, \"Neo-Hookean physical parameters\", NULL);\n CHKERRQ(ierr);\n\n ierr = PetscOptionsScalar(\"-nu\", \"Poisson's ratio\", NULL, phys->nu, &phys->nu,\n &nu_flag); CHKERRQ(ierr);\n\n ierr = PetscOptionsScalar(\"-E\", \"Young's Modulus\", NULL, phys->E, &phys->E,\n &Young_flag); CHKERRQ(ierr);\n\n ierr = PetscOptionsScalar(\"-units_meter\", \"1 meter in scaled length units\",\n NULL, units->meter, &units->meter, NULL);\n CHKERRQ(ierr);\n units->meter = fabs(units->meter);\n\n ierr = PetscOptionsScalar(\"-units_second\", \"1 second in scaled time units\",\n NULL, units->second, &units->second, NULL);\n CHKERRQ(ierr);\n units->second = fabs(units->second);\n\n ierr = PetscOptionsScalar(\"-units_kilogram\", \"1 kilogram in scaled mass units\",\n NULL, units->kilogram, &units->kilogram, NULL);\n CHKERRQ(ierr);\n units->kilogram = fabs(units->kilogram);\n\n ierr = PetscOptionsEnd(); CHKERRQ(ierr); // End of setting Physics\n\n // Check for all required options to be set\n if (!nu_flag) {\n SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, \"-nu option needed\");\n }\n if (!Young_flag) {\n SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, \"-E option needed\");\n }\n\n // Define derived units\n units->Pascal = units->kilogram / (units->meter * PetscSqr(units->second));\n\n // Scale E to Pa\n phys->E *= units->Pascal;\n\n PetscFunctionReturn(0);\n};", "meta": {"hexsha": "f0b8af460785299d157503ab9b251e97b182846a", "size": 4020, "ext": "c", "lang": "C", "max_stars_repo_path": "examples/solids/problems/neo-hookean.c", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/solids/problems/neo-hookean.c", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/solids/problems/neo-hookean.c", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 34.358974359, "max_line_length": 81, "alphanum_fraction": 0.6631840796, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.6859494421679928, "lm_q1q2_score": 0.43944381667302945}} {"text": "/** \n * \\file gps_single.c Implements GPS single point solution using Least Squares\n * \\author Duncan Greer\n * $Id: gps_single.c 3579 2010-06-26 10:57:31Z greerd $\n */\n\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../../novatelstore/src/novatel.h\"\n#include \"gps.h\"\n#include \"../../novatelstore/src/shmdef.h\"\n\n#include \"matrix.h\"\n\n/** Controls whether or not the program should keep running. */\nint iShutdown = 0;\n\n#define MODULE_NAME \"[GPS_SINGLE]\"\n\n#define log(string) \tfprintf(stdout,\"%s %s\\n\", MODULE_NAME, string)\n#define err(string)\tfprintf(stderr,\"%s ERROR: %s\\n\", MODULE_NAME, string)\n\n#define ELEVATION_CUTOFF_RAD (10.0 * DEG2RAD)\n\n\n/** \n\t\\function CalculateDOP\n\tCalculates the Dilution of Precision based on the provided G Matrix.\n\t\\author Duncan Greer and Troy Bruggemann\n\t\n\tNote that the G-Matrix must be provided already transformed to \n\tthe horizontal plane.\n*/\nvoid CalculateDOP(gsl_matrix *G, double *DOP);\n\n\n/**\n *\t\\fn HandleSignal\n *\t\\brief Handle caught signals\n *\t\n * \tThis function sets a flag (iShutdown) to shut the program down.\n */\nvoid HandleSignal(int signal) \n{ \n\tfprintf(stdout,\"Got Signal: %d\\n\",signal);\n\tiShutdown = 1; \n}\n\n/**\n * \t\\fn Usage\n *\t\\brief Print Usage Information\n */\nvoid Usage(char *arg)\n{\n\n\t/* options */\n\t/*\n\t b = baudrate\n\t p = port\n\t l = logging \n\t f = log filename\n\t t = enable tcp server\n\t*/\n\tfprintf(stdout,\"Usage: %s \\n\",arg);\n\tfprintf(stdout,\" -l Log results to file (OFF)\\n\");\n\tfprintf(stdout,\" -f log filename\\n\");\n\tfprintf(stdout,\" -L Use specified log file path (/data/gps)\\n\");\n\n}\n\nint main (int argc, char **argv)\n{\n\tgsl_matrix *G;\n\tgsl_matrix *G_LTP;\n//\tgsl_matrix *GT;\n//\tgsl_matrix *tempNN;\n//\tgsl_matrix *V;\n//\tgsl_vector *S;\n//\tgsl_matrix *U;\n\tgsl_vector *W;\n\tgsl_vector *y;\n\tgsl_vector *delta_y;\n\tgsl_vector *x;\n\tgsl_vector *delta_x;\n\tgsl_vector *x_error;\n\tgsl_vector *x_true;\n\tgsl_vector *temp1;\n\t\n\tgsl_multifit_linear_workspace *gsl_workspace;\n\tgsl_vector *SVPos[MAX_SV];\n\tdouble SVPos_calc[4];\n\tdouble dSSE;\n\tgsl_matrix *SolutionCovariance;\n\tint iReturnValue = 0;\n\n\tint iNumberStates = 4;\n\tint iNumberMeasurements = 9;\n\tint iNumberValidEphemeris = 0;\n\tint iNumberValidObservations = 0;\n\tint iIndex;\n\tGPSTime gtObservationTime;\n\tunsigned short usPRN;\n\tint iIteration;\n\n\tint iUseSV[NOVATEL_MAXPRNS];\n\n\tdouble user_x,user_y,user_z,user_t = 0.0;\n\tdouble sat_x,sat_y,sat_z,sat_t;\n//\tdouble sat_x_calc,sat_y_calc,sat_z_calc,sat_t_calc;\n\tdouble dTemp;\n\t\n\tdouble range;\n\tdouble delta_pr_omegaedot;\n\n\tdouble ecef[3];\n\tdouble llh[3];\n\tdouble TECEF2ENU[3][3];\n\tgsl_matrix *T_ECEF2NED_44;\n\tdouble NEDError[3];\n\tdouble ECEFError[3];\n\tdouble UserPos[4];\n\tdouble ION_Alpha[4];\n\tdouble ION_Beta[4];\n\tdouble IonoDelay[NOVATEL_MAXCHANNELS];\n\tdouble TropoDelay[NOVATEL_MAXCHANNELS];\n\tdouble SV_Azimuth[NOVATEL_MAXCHANNELS];\n\tdouble SV_Elevation[NOVATEL_MAXCHANNELS];\n\n\tdouble dTransmissionTime;\n\t\n\tGPSEPHEM GPSEphemData[NOVATEL_MAXPRNS];\n\tRANGE GPSRangeData;\n\n\tdouble GDOP,PDOP;\n\tdouble DOPS[5];\n\tdouble limit;\n\n\tint iUseSHM = 1;\n\tint iSHM_FID;\n\n\tint iRow,iCol;\n\t\n\tshm_struct *shm = NULL;\n\t\n\tunsigned long ulSignalType = 0;\t\n\t\n\tchar copt;\n\n\t/* log files */\n\tFILE *fpLogFile = NULL; /* pointer to log file stream */\n\tchar azcLogFileName[256]; /* log file name */\n\tchar azcLogFilePath[255];\n\tchar azcLogFileNameWithPath[1024];\n\n\tstruct tm *timestruct;\n\ttime_t tCurrentTime = 0;\n\ttime_t tLogFileStart = 0;\n\n\t/* options flags */\n\tstruct\n\t{\n\t\tint iLogResults;\n\t\tint iCustomLogFile;\n\t} options;\n\n\t// default options\n\toptions.iLogResults = 0;\n\toptions.iCustomLogFile = 0;\n\n\t\n\t\n\t/* setup signal handlers */\n\tsignal(SIGHUP, HandleSignal);\n\tsignal(SIGTERM, HandleSignal);\n\tsignal(SIGKILL, HandleSignal);\n\tsignal(SIGALRM, HandleSignal);\n\tsignal(SIGINT, HandleSignal);\n\t\n\t/* get the current time to use as a timestamp in the log file name */\n\ttCurrentTime = time(NULL);\n\ttimestruct = gmtime(&tCurrentTime);\n\n\t/* setting default log file path */\n\tsprintf(azcLogFilePath,\"%s\",\"/data/gps\");\n\n\t/* read input parameters */\n\twhile((copt = getopt(argc,argv,\"lf:L:\")) && copt != -1)\n\t{\n\t switch(copt)\n\t {\n\t case 'l':\n\t\t/* log results to file */\n\t\toptions.iLogResults = 1;\n\t\tlog(\"Logging enabled\");\n\t\tstrftime(azcLogFileName,sizeof(azcLogFileName),\"gps_single_%g%m%d%H%M%S.csv\",timestruct);\n\t\tbreak;\n\n\t case 'f':\n\t\t/* set the log file name */\n\t\tsprintf(azcLogFileName,\"%s\",optarg);\n\t\toptions.iCustomLogFile = 1; /* since we're using a user specified log file name, we dont want to recycle it every hour */\n\t\tbreak;\n\n\t case 'L':\n\t \t/* setting log file path */\n\t \tsprintf(azcLogFilePath,\"%s\",optarg);\n\n\t \tfprintf(stdout,\"%s Setting log file path to %s\",MODULE_NAME,azcLogFilePath);\n\t \tbreak;\n\t case '?':\n\t\tUsage(argv[0]);\n\t\treturn 0;\n\t\tbreak;\n\t }\n\t}\n\n\n\n\t\n\tfor(iIndex=0;iIndex 1 hour, start a new one */\n\tif(options.iLogResults == 1 && options.iCustomLogFile == 0)\n\t{\n\t\ttCurrentTime = time(NULL);\n\t\tif(difftime(tCurrentTime,tLogFileStart) > 3600.0)\n\t\t{\n\t\t\t/* start a new log file */\n\t\t\tfclose(fpLogFile);\n\t\t\t\t\t\n\t\t\ttimestruct = gmtime(&tCurrentTime);\n\t\t\tstrftime(azcLogFileName,sizeof(azcLogFileName),\"gps_single_%g%m%d%H%M%S.csv\",timestruct);\n\t\t\n\t\t\tsprintf(azcLogFileNameWithPath,\"%s/%s\",azcLogFilePath,azcLogFileName);\n\n\t\t\tif((fpLogFile = fopen(azcLogFileNameWithPath,\"a\")) == NULL)\n\t\t\t{\t\n\t\t\t\tfprintf(stderr,\"Error opening %s for writing: %s\\n\",azcLogFileNameWithPath,strerror(errno));\n\t\t\t\toptions.iLogResults = 0;\n\t\t\t} else\n\t\t\t{\n\t\t\t\ttLogFileStart = tCurrentTime;\n\t\t\t\tfprintf(stdout,\"%s Started New Logfile: %s\\n\",MODULE_NAME,azcLogFileNameWithPath);\n\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t}\n\n\t/* TODO: replace this sleep with a semaphore to wait for new data */\n \tsleep(1);\n\t\n\tfprintf(stdout,\"====== Single-Point Solution ======\\n\");\n\t/* retrive the current data from shm */\n\tif(iUseSHM == 1)\n\t{\n\t memcpy(&GPSEphemData,&shm->CurrentGPSEPHEM,sizeof(GPSEPHEM)*NOVATEL_MAXPRNS);\n\t \n\t \n\t // get the current observation time to compare with ephemeris\n\t memcpy(>ObservationTime,&shm->CurrentRANGE.gtTimeStamp,sizeof(GPSTime));\n\n\n\t /* ensure we have ephemeris for all measurements, otherwise exclude */\n\t iNumberValidEphemeris = 0;\n\t for(iIndex=0;iIndex (gtObservationTime.fGPSSecondOfWeek-7500.0))\n\t \t)\n\t \t{\n\t \t iUseSV[iIndex] = 1;\n\t \t iNumberValidEphemeris++;\n//\t \t fprintf(stdout,\"SV%d \",iIndex);\n\t \t} else\n\t \t{\n\t \t iUseSV[iIndex] = 0;\n\t \t}\n\t }\n\t \n\t /* loop through measurements and see \n\t if we have valid ephem for each */\n\t \n\t memcpy(&GPSRangeData.gtTimeStamp,&shm->CurrentRANGE.gtTimeStamp,sizeof(GPSTime));\n\t iNumberValidObservations = 0;\n\t \n\t for(iIndex=0;iIndexCurrentRANGE.lNumberObservations;iIndex++)\n\t {\n\t \tif(iUseSV[shm->CurrentRANGE.usPRN[iIndex]] == 1)\n\t \t{\n\t \t\tulSignalType = shm->CurrentRANGE.ulTrackingStatus[iIndex] & 0x3E00000;\n\t \t\t\n\t \t\t// check that we're only getting hte L1 signal\n\t \t\tif (ulSignalType == 0)\n\t \t\t{\n\t \t\t\t// use current range data for now\n\t \t\t\tmemcpy(&GPSRangeData.usPRN[iNumberValidObservations],\n\t\t\t\t &shm->CurrentRANGE.usPRN[iIndex],sizeof(unsigned short));\n\t\t\t\tmemcpy(&GPSRangeData.dPseudorange[iNumberValidObservations],\n\t\t\t\t\t&shm->CurrentRANGE.dPseudorange[iIndex], sizeof(double));\n\t\t\t\n\t\t\t\n\t\t\t\t\tiNumberValidObservations++;\n\t \t\t\n\t \t\t} else\n\t \t\t{\n\t \t\t\t\n\n\t\t\t\t// not an L1 obs\n\t\t\t\t//fprintf(stdout,\"Value of Signal Type for PRN%02d was 0x%0x\\n\",\n\t\t\t\t//\tshm->CurrentRANGE.usPRN[iIndex], \n\t\t\t\t//\tulSignalType);\n\t \t\t}\n\t \t} else\n\t \t{\n\t \t fprintf(stdout,\"NE: %d; \",shm->CurrentRANGE.usPRN[iIndex]);\n\t \t}\n\t }\n\n\t fprintf(stdout,\"Obs: %d; \\n\",iNumberValidObservations);\t \n\t GPSRangeData.lNumberObservations = iNumberValidObservations;\n\t \n\t iNumberMeasurements = GPSRangeData.lNumberObservations;\n\t \n\t if(iNumberMeasurements < 4)\n\t {\n\t\tfprintf(stdout,\"Less than 4 measurements\\n\");\n\t\tcontinue;\n\t }\n\n\t/*\n\t\t if(iNumberMeasurements > 9)\n\t\t {\n\t\t\t iNumberMeasurements = 9; \n\t\t }\n\t\t \n\t\t if(iNumberMeasurements < 9)\n\t\t {\n\t\t\terr(\"Less than 9 measurements!\");\n\t\t }\n\t*/\n\t\tG = gsl_matrix_alloc(iNumberMeasurements,iNumberStates);\n\t\tG_LTP = gsl_matrix_alloc(iNumberMeasurements,iNumberStates);\n\t\ty = gsl_vector_alloc(iNumberMeasurements);\n\t\tdelta_y = gsl_vector_alloc(iNumberMeasurements);\n\t\tW = gsl_vector_alloc(iNumberMeasurements);\n\t\tgsl_workspace = gsl_multifit_linear_alloc (iNumberMeasurements,iNumberStates);\n\n\t\t/* calculate G-matrix */\n\t\tgsl_matrix_set_zero (G);\n\t\t//gsl_matrix_fprintf(stdout,G,\"%5.3f\");\n\n\t\t/* calculate W-matrix */\n\t\tgsl_vector_set_all(W,1.0);\n\n\n\n\n\t} else\n\t{\n\t\tlog(\"No Shared Memory\");\n\n\n\n\t}\n\n\t\tfor(iIteration=0;iIteration<20;iIteration++)\n\t\t{\n\t\t//\tfprintf(stdout,\"\\n===== ITERATION %d =====\\n\",iIteration+1);\n\n\t\t\tuser_x = gsl_vector_get(x,0);\n\t\t\tuser_y = gsl_vector_get(x,1);\n\t\t\tuser_z = gsl_vector_get(x,2);\n\t\t\tuser_t = gsl_vector_get(x,3);\n\t\t\t\n\t\t\tUserPos[0] = user_x;\n\t\t\tUserPos[1] = user_y;\n\t\t\tUserPos[2] = user_z;\n\t\t\tUserPos[3] = user_t;\n\n\t\t\tION_Alpha[0] = shm->CurrentIONUTC.a0;\n\t\t\tION_Alpha[1] = shm->CurrentIONUTC.a1;\n\t\t\tION_Alpha[2] = shm->CurrentIONUTC.a2;\n\t\t\tION_Alpha[3] = shm->CurrentIONUTC.a3;\n\t\t\t\n\t\t\tION_Beta[0] = shm->CurrentIONUTC.b0;\n\t\t\tION_Beta[1] = shm->CurrentIONUTC.b1;\n\t\t\tION_Beta[2] = shm->CurrentIONUTC.b2;\n\t\t\tION_Beta[3] = shm->CurrentIONUTC.b3;\n\t\t\t\n\t\t\t\n\t\t\n\t//\t\tfprintf(stdout,\"User: [%+10.3f\\t%+10.3f\\t%+10.3f\\t%+10.3f]\\n\",user_x,user_y,user_z,user_t);\n\t\t\t\n\t\t\tfor (iIndex=0;iIndexdDOPS[0],&DOPS[0],sizeof(double));\n//\t\t\t\tmemcpy(shm->dLLH_LSQ,llh,sizeof(double)*3);\n//\t\t\t\tmemcpy(shm->dECEF_LSQ,ecef,sizeof(double)*3);\n//\t\t\t\tshm->dRxClock_LSQ = gsl_vector_get(x,3);\n\t\t\t\t\n\n\t\t\t\tfprintf(stdout,\"Lat: %f, Long: %f, Height: %f\\n\",\n\t\t\t\t\tllh[0]*RAD2DEG,llh[1]*RAD2DEG,llh[2]);\n\t\t\t\tfprintf(stdout,\"GDOP=%f, PDOP=%f, HDOP=%f, VDOP=%f, TDOP=%f\\n\",\n\t\t\t\t\tGDOP,PDOP,DOPS[2],DOPS[3],DOPS[4]);\n\t\t\t\tfprintf(stdout,\"NED Error: %fm %fm %fm\\n\",NEDError[0],\n\t\t\t\t\tNEDError[1],\n\t\t\t\t\tNEDError[2]);\n\n\t\t\t\tfprintf(stdout,\"SV: \");\n\t\t\t\tfor(iIndex=0;iIndexsize1;\n\tiNumberStates = G->size2;\n\n\tGT = gsl_matrix_alloc(iNumberStates,iNumberMeasurements);\n\ttempNN = gsl_matrix_alloc(iNumberStates,iNumberStates);\n\tV = gsl_matrix_alloc(iNumberStates,iNumberStates);\n\tS = gsl_vector_alloc(iNumberStates);\n\tSinv = gsl_vector_alloc(iNumberStates);\n\tSinvMat = gsl_matrix_alloc(iNumberStates,iNumberStates);\n\tA = gsl_matrix_alloc(iNumberStates,iNumberStates);\n\tSVDWork = gsl_vector_alloc(iNumberStates);\n\tU = gsl_matrix_alloc(iNumberStates,iNumberStates);\n\t\n\t\n\t// calculate DOP\n\tgsl_matrix_transpose_memcpy(GT,G);\n\tgsl_matrix_set_zero(tempNN);\n\tgsl_blas_dgemm (CblasNoTrans,CblasNoTrans, 1.0, GT, G, 1.0, tempNN);\n\t\n\t// take the SVD of GT*T (stored in TempNN) to find inverse - tempNN now contains 'U'\n\tiReturnValue = gsl_linalg_SV_decomp (tempNN,V,S,SVDWork);\n\t\t\n\t// get element wise inverse of S\n\tgsl_vector_set_all(Sinv,1.0);\n\tgsl_vector_div(Sinv, S);\n\n\tgsl_matrix_set_zero (SinvMat);\n\tfor(iIndex=0;iIndex\n#include \n#include \n#include \n#include \"compearth.h\"\n#include \"cmopad.h\"\n#ifdef COMPEARTH_USE_MKL\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#pragma clang diagnostic ignored \"-Wstrict-prototypes\"\n#endif\n#include \n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include \n#endif\n\nstruct mt_struct\n{\n double mt[6];\n double tax[3];\n double bax[3];\n double pax[3];\n double sdr1[3]; //strike dip rake; fault plane 2\n double sdr2[3]; //strike dip rake; fault plane 1\n double mag;\n double exp;\n};\n\n/*\nint compearth_standardDecomposition(const int nmt,\n const double *__restrict__ M,\n enum compearthCoordSystem_enum basis,\n double *__restrict__ M0,\n double *__restrict__ Mw,\n double *__restrict__ fp1,\n double *__restrict__ fp2,\n double *__restrict__ pAxis,\n double *__restrict__ bAxis,\n double *__restrict__ tAxis,\n double *__restrict__ isoPct,\n double *__restrict__ devPct,\n double *__restrict__ dcPct,\n double *__restrict__ clvdPct);\n*/\nint decompose(const int nmt, const double mtUSE[6]);\n\nint decompose(const int nmt, const double mtUSE[6])\n{\n //double K[3], N[3], S[3], lam[3], U[9], Uuse[9], b[3], p[3], t[3], \n //double gamma, delta, M0, kappa, theta, sigma, thetadc,\n // k2, d2, s2;\n struct cmopad_struct src;\n const char *fcnm = \"decompose\\0\";\n enum cmopad_basis_enum cin, cloc;\n double M[3][3], pax[3], bax[3], tax[3];\n int i, ierr;\n const int iverb = 0;\n/*\n //------------------------------------------------------------------------//\n // Do the cMoPaD decomposition //\n //------------------------------------------------------------------------//\n // Copy moment tensor\n M[0][0] = mtUSE[0]; //Mrr\n M[1][1] = mtUSE[1]; //Mtt\n M[2][2] = mtUSE[2]; //Mpp\n M[0][1] = M[1][0] = mtUSE[3]; //Mrt\n M[0][2] = M[2][0] = mtUSE[4]; //Mrp\n M[1][2] = M[2][1] = mtUSE[5]; //Mtp\n // Mopad works in North, East, Down frame but inversion is Up, South, East\n cin = USE;\n cloc = NED;\n cmopad_basis_transformMatrixM33(M, cin, cloc); //USE -> NED\n // Compute the isotropic, CLVD, DC decomposition \n ierr = cmopad_standardDecomposition(M, &src);\n if (ierr != 0)\n {\n printf(\"%s: Error in decomposition!\\n\", fcnm);\n return EXIT_FAILURE;\n }\n // Compute the princple axes with corresponding strikes, dips, and rakes \n ierr = cmopad_MT2PrincipalAxisSystem(iverb, &src);\n if (ierr != 0)\n {\n printf(\"%s: Error computing principal axis\\n\",fcnm);\n return EXIT_FAILURE;\n }\n // Compute the pressure, null, and, tension principal axes as len,az,plunge\n cin = NED; //MoPaD is in north, east, down \n ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[0],\n src.p_axis, pax);\n if (ierr != 0)\n {\n printf(\"%s: Error converting pax\\n\",fcnm);\n return EXIT_FAILURE;\n }\n ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[1],\n src.null_axis, bax);\n if (ierr != 0){\n printf(\"%s: Error converting bax\\n\",fcnm);\n return EXIT_FAILURE;\n }\n ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[2],\n src.t_axis, tax);\n if (ierr != 0)\n {\n printf(\"%s: Error converting tax\\n\",fcnm);\n return EXIT_FAILURE;\n }\n*/\n //printf(\"%f %f %f %f %f %f\\n\",\n // mtUSE[0], mtUSE[1], mtUSE[2], mtUSE[3], mtUSE[4], mtUSE[5]);\n //ierr = compearth_CMT2TT(1, mtUSE, false,\n // &gamma, &delta, &M0,\n // &kappa, &theta, &sigma,\n // K, N, S, &thetadc, \n // lam, U);\n //if (ierr != 0)\n //{\n // fprintf(stderr, \"%s: CMT2TT failed\\n\", __func__);\n // return EXIT_FAILURE;\n //}\n /*\n // Need to switch from SEU to USE. This requires computing\n // R U inv(R) where:\n // R = [0 0 1\n // 1 0 0\n // 0 1 0]\n // Carrying through the multiplication yields the permutation\n // U_{use} = [U_{33} U_{31} U_{32}\n // U_{13} U_{11} U_{12}\n // U_{23} U_{21} U_{22}]\n //\n // Permute the column major matrix\n Uuse[0] = U[8];\n Uuse[1] = U[6];\n Uuse[2] = U[7];\n\n Uuse[3] = U[2];\n Uuse[4] = U[0];\n Uuse[5] = U[1];\n\n Uuse[6] = U[5];\n Uuse[7] = U[3];\n Uuse[8] = U[4];\nprintf(\"%f %f %f\\n%f %f %f\\n%f %f %f\\n\",\n U[0], U[3], U[6],\n U[1], U[4], U[7],\n U[2], U[5], U[8]);\n*/\n //ierr = compearth_U2pa(1, U,\n // &p[2], &p[1], &b[2], &b[1], &t[2], &t[1]);\n //if (ierr != 0)\n //{\n // fprintf(stderr, \"%s: Error converting u to plunge/azimuth\\n\", \n // __func__);\n // return EXIT_FAILURE;\n //}\n //// Fill in the eigenvalues\n //p[0] = lam[0];\n //b[0] = lam[1];\n //t[0] = lam[2];\n //printf(\"p: %e %f %f\\n\", p[0], p[1], p[2]);\n //printf(\"b: %e %f %f\\n\", b[0], b[1], b[2]);\n //printf(\"t: %e %f %f\\n\", t[0] ,t[1], t[2]); \n // Compute the auxiliary fault plane\n //ierr = compearth_auxiliaryPlane(1, &kappa, &theta, &sigma,\n // &k2, &d2, &s2);\n // Just define some convention where smaller strike goes first\n //printf(\"%e %f %f %f\\n\", M0, kappa, theta, sigma);\n //printf(\"%f %f %f\\n\", k2, d2, s2);\n //------------------------------------------------------------------------//\n // do the standard decomposition //\n //------------------------------------------------------------------------//\n //double pAxis[3], bAxis[3], tAxis[3], fp1[3], fp2[3], isoPct, dcPct, devPct, clvdPct, Mw;\n double *pAxis, *bAxis, *tAxis, *fp1, *fp2, *isoPct, *dcPct, *devPct, *clvdPct, *Mw, *M0;\n M0 = (double *) calloc((size_t) nmt, sizeof(double));\n Mw = (double *) calloc((size_t) nmt, sizeof(double));\n fp1 = (double *) calloc((size_t) (3*nmt), sizeof(double));\n fp2 = (double *) calloc((size_t) (3*nmt), sizeof(double));\n pAxis = (double *) calloc((size_t) (3*nmt), sizeof(double));\n bAxis = (double *) calloc((size_t) (3*nmt), sizeof(double));\n tAxis = (double *) calloc((size_t) (3*nmt), sizeof(double));\n isoPct = (double *) calloc((size_t) nmt, sizeof(double));\n devPct = (double *) calloc((size_t) nmt, sizeof(double));\n dcPct = (double *) calloc((size_t) nmt, sizeof(double));\n clvdPct = (double *) calloc((size_t) nmt, sizeof(double));\n ierr = compearth_standardDecomposition(nmt, mtUSE, CE_USE, \n M0, Mw, fp1, fp2,\n pAxis, bAxis, tAxis,\n isoPct, devPct, dcPct, clvdPct);\n if (ierr != 0)\n {\n fprintf(stderr, \"Failed to compute standard decomposition\\n\");\n return EXIT_FAILURE;\n }\n for (i=0; i NED\n // Compute the isotropic, CLVD, DC decomposition \n ierr = cmopad_standardDecomposition(M, &src);\n if (ierr != 0)\n { \n printf(\"%s: Error in decomposition!\\n\", fcnm);\n return EXIT_FAILURE; \n } \n // Compute the princple axes and strikes, dips, and rakes \n ierr = cmopad_MT2PrincipalAxisSystem(iverb, &src);\n if (ierr != 0)\n { \n printf(\"%s: Error computing principal axis\\n\",fcnm);\n return EXIT_FAILURE; \n } \n // Compute the pressure, null, and, tension principal axes as\n // len,az,plunge\n cin = NED; //MoPaD is in north, east, down \n ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[0],\n src.p_axis, pax);\n if (ierr != 0)\n { \n printf(\"%s: Error converting pax\\n\",fcnm);\n return EXIT_FAILURE; \n } \n ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[1],\n src.null_axis, bax);\n if (ierr != 0)\n { \n printf(\"%s: Error converting bax\\n\",fcnm);\n return EXIT_FAILURE; \n } \n ierr = cmopad_Eigenvector2PrincipalAxis(cin, src.eig_pnt[2],\n src.t_axis, tax);\n if (ierr != 0)\n { \n printf(\"%s: Error converting tax\\n\",fcnm);\n return EXIT_FAILURE; \n }\n // Check it\n //printf(\"%d %d %e\\n\", i, i%9, Mw[i]);\n if (fabs(M0[i] - src.seismic_moment)/src.seismic_moment > 1.e-10)\n {\n fprintf(stderr, \"failed M0 %f %f %e %d\\n\", M0[i], src.seismic_moment,\n fabs(M0[i] - src.seismic_moment)/src.seismic_moment, i);\n return EXIT_FAILURE;\n }\n if (fabs(Mw[i] - src.moment_magnitude) > 1.e-10)\n {\n fprintf(stderr, \"failed Mw %f %f %d\\n\", Mw[i], src.moment_magnitude, i);\n return EXIT_FAILURE;\n }\n if (fabs(isoPct[i] - src.ISO_percentage) > 1.e-10)\n { \n fprintf(stderr, \"Failed iso pct %f %f\\n\",\n isoPct[i], src.ISO_percentage);\n return EXIT_FAILURE;\n }\n if (fabs(dcPct[i] - src.DC_percentage) > 1.e-10)\n {\n fprintf(stderr, \"Failed DC pct %f %f %d\\n\",\n dcPct[i], src.DC_percentage, i);\n return EXIT_FAILURE;\n }\n if (fabs(devPct[i] - src.DEV_percentage) > 1.e-10)\n {\n fprintf(stderr, \"Failed dev pct %f %f\\n\",\n devPct[i], src.DEV_percentage);\n return EXIT_FAILURE;\n }\n if (fabs(clvdPct[i] - src.CLVD_percentage) > 1.e-10)\n {\n fprintf(stderr, \"Failed clvd pct %f %f\\n\",\n devPct[i], src.CLVD_percentage);\n return EXIT_FAILURE;\n }\n // Swap fault planes\n if (fabs(fp1[3*i+0] - src.fp1[0]) > 1.e-10)\n {\n if (fabs(fp1[3*i+0] - src.fp2[0]) > 1.e-10)\n {\n fprintf(stderr, \"Failed strike 1 %f %f\\n\", fp1[3*i+0], src.fp2[0]);\n return EXIT_FAILURE;\n }\n if (fabs(fp1[3*i+1] - src.fp2[1]) > 1.e-10)\n {\n fprintf(stderr, \"Failed dip 1 %f %f\\n\", fp1[3*i+1], src.fp2[1]);\n return EXIT_FAILURE;\n }\n if (fabs(fp1[3*i+2] - src.fp2[2]) > 1.e-10)\n {\n fprintf(stderr, \"Failed rake 1 %f %f\\n\", fp1[3*i+2], src.fp2[2]);\n return EXIT_FAILURE;\n }\n if (fabs(fp2[3*i+0] - src.fp1[0]) > 1.e-10)\n {\n fprintf(stderr, \"Failed strike 2 %f %f\\n\", fp2[3*i+0], src.fp1[0]);\n return EXIT_FAILURE;\n }\n if (fabs(fp2[3*i+1] - src.fp1[1]) > 1.e-10)\n {\n fprintf(stderr, \"Failed dip 2 %f %f\\n\", fp2[3*i+1], src.fp1[1]);\n return EXIT_FAILURE;\n }\n if (fabs(fp2[3*i+2] - src.fp1[2]) > 1.e-10)\n {\n fprintf(stderr, \"Failed rake 2 %f %f\\n\", fp2[3*i+2], src.fp1[2]);\n return EXIT_FAILURE;\n }\n }\n else\n {\n if (fabs(fp1[3*i+0] - src.fp1[0]) > 1.e-10)\n {\n fprintf(stderr, \"Failed strike 1 %f %f\\n\",\n fp1[3*i+0], src.fp1[0]);\n return EXIT_FAILURE;\n }\n if (fabs(fp1[3*i+1] - src.fp1[1]) > 1.e-10)\n {\n fprintf(stderr, \"Failed dip 1 %f %f\\n\",\n fp1[3*i+1], src.fp1[1]);\n return EXIT_FAILURE;\n }\n if (fabs(fp1[3*i+2] - src.fp1[2]) > 1.e-10)\n {\n fprintf(stderr, \"Failed rake 1 %f %f\\n\",\n fp1[3*i+2], src.fp1[2]);\n return EXIT_FAILURE;\n }\n if (fabs(fp2[3*i+0] - src.fp2[0]) > 1.e-10)\n {\n fprintf(stderr, \"Failed strike 2 %f %f\\n\",\n fp2[3*i+0], src.fp2[0]);\n return EXIT_FAILURE;\n }\n if (fabs(fp2[3*i+1] - src.fp2[1]) > 1.e-10)\n {\n fprintf(stderr, \"Failed dip 2 %f %f\\n\",\n fp2[3*i+1], src.fp2[1]);\n return EXIT_FAILURE;\n }\n if (fabs(fp2[3*i+2] - src.fp2[2]) > 1.e-10)\n {\n fprintf(stderr, \"Failed rake 2 %f %f\\n\",\n fp2[3*i+2], src.fp2[2]);\n return EXIT_FAILURE;\n }\n }\n if (fabs(pAxis[3*i+0] - pax[0]) > 1.e-10 ||\n fabs(pAxis[3*i+1] - pax[1]) > 1.e-10 ||\n fabs((pAxis[3*i+2] - pax[2])/pax[2]) > 1.e-10)\n {\n fprintf(stderr, \"failed pressure axix: %f %f %f %f %f %f\\n\",\n pAxis[0], pAxis[1], pAxis[2], pax[0], pax[1], pax[2]);\n return EXIT_FAILURE;\n }\n if (fabs(bAxis[3*i+0] - bax[0]) > 1.e-10 ||\n fabs(bAxis[3*i+1] - bax[1]) > 1.e-10 ||\n fabs((bAxis[3*i+2] - bax[2])/bax[2]) > 1.e-10)\n {\n fprintf(stderr, \"Failed null axis: %f %f %f %f %f %f\\n\",\n bAxis[0], bAxis[1], bAxis[2], bax[0], bax[1], bax[2]);\n return EXIT_FAILURE;\n }\n if (fabs(tAxis[3*i+0] - tax[0]) > 1.e-10 ||\n fabs(tAxis[3*i+1] - tax[1]) > 1.e-10 ||\n fabs((tAxis[3*i+2] - tax[2])/tax[2]) > 1.e-10)\n {\n fprintf(stderr, \"Failed tension axis %f %f %f %f %f %f\\n\",\n tAxis[0], tAxis[1], tAxis[2], tax[0], tax[1], tax[2]);\n return EXIT_FAILURE;\n }\n if (nmt == 1)\n {\n printf(\"Summary:\\n\");\n printf(\"Mw: %f\\n\", Mw[i]);\n printf(\"(strike,dip,rake): (%f,%f,%f)\\n\",\n fp1[3*i+0], fp1[3*i+1], fp1[3*i+2]);\n printf(\"(strike,dip,rake): (%f,%f,%f)\\n\",\n fp2[3*i+0], fp2[3*i+1], fp2[3*i+2]);\n printf(\"iso pct: %f\\n\", isoPct[i]);\n printf(\"dc pct: %f\\n\", dcPct[i]);\n printf(\"dev pct: %f\\n\", devPct[i]); \n printf(\"clvd pct: %f\\n\", clvdPct[i]);\n printf(\"\\n\");\n }\n }\n free(M0);\n free(Mw);\n free(fp1);\n free(fp2);\n free(pAxis);\n free(bAxis);\n free(tAxis);\n free(isoPct);\n free(devPct);\n free(dcPct);\n free(clvdPct);\n return EXIT_SUCCESS;\n} \n\nint main()\n{\n struct mt_struct mt;\n const int nmt = 21*CE_CHUNKSIZE - 1;\n double *mtTest = (double *) calloc((size_t) (6*nmt), sizeof(double));\n //mtTest[2*6*CE_CHUNKSIZE];\n double xscal;\n int ierr, jmt;\n const int n6 = 6;\n const int incx = 1;\n //-----------------------------------1------------------------------------//\n mt.exp = 23.0 - 7.0;\n mt.mag = 5.1;\n mt.mt[0] =-4.360;\n mt.mt[1] = 3.200;\n mt.mt[2] = 1.170;\n mt.mt[3] =-0.794;\n mt.mt[4] = 1.650;\n mt.mt[5] = 2.060;\n mt.sdr1[0] = 77.0;\n mt.sdr1[1] = 47.0;\n mt.sdr1[2] =-62.0;\n mt.sdr2[0] = 219.0;\n mt.sdr2[1] = 50.0;\n mt.sdr2[2] =-117.0;\n mt.tax[0] = 4.49;\n mt.tax[1] = 1.0;\n mt.tax[2] = 328.0;\n mt.bax[0] = 0.56;\n mt.bax[1] = 20.0;\n mt.bax[2] = 237.0;\n mt.pax[0] =-5.04;\n mt.pax[1] = 70.0;\n mt.pax[2] = 61.0;\n xscal = pow(10.0, mt.exp);\n cblas_dscal(n6, xscal, mt.mt, incx);\n cblas_dcopy(n6, mt.mt, 1, &mtTest[0], 1);\n // Perform decomposition\n ierr = decompose(1, mt.mt);\n if (ierr != EXIT_SUCCESS)\n {\n fprintf(stderr, \"Error decomposiing 1\\n\");\n return EXIT_FAILURE;\n }\n //--------------------------------------2----------------------------------//\n mt.exp = 23.0 - 7.0;\n mt.mag = 5.0;\n mt.mt[0] =-4.480;\n mt.mt[1] = 1.440; \n mt.mt[2] = 3.040;\n mt.mt[3] = 0.603; \n mt.mt[4] = 0.722;\n mt.mt[5] =-1.870;\n mt.sdr1[0] =316.0; \n mt.sdr1[1] = 44.0;\n mt.sdr1[2] =-105.0; \n mt.sdr2[0] = 157.0;\n mt.sdr2[1] = 48.0;\n mt.sdr2[2] =-76.0;\n mt.tax[0] = 4.28;\n mt.tax[1] = 2.0;\n mt.tax[2] = 237.0;\n mt.bax[0] = 0.37;\n mt.bax[1] = 10.0;\n mt.bax[2] = 327.0;\n mt.pax[0] =-4.66;\n mt.pax[1] = 79.0;\n mt.pax[2] =137.0;\n xscal = pow(10.0,mt.exp);\n cblas_dscal(n6, xscal, mt.mt, incx);\n cblas_dcopy(n6, mt.mt, 1, &mtTest[6], 1);\n // Perform decomposition\n ierr = decompose(1, mt.mt);\n if (ierr != EXIT_SUCCESS)\n { \n fprintf(stderr, \"Error decomposiing 1\\n\");\n return EXIT_FAILURE;\n }\n //------------------------------------3-----------------------------------//\n mt.exp = 23.0 - 7.0;\n mt.mag = 4.9;\n mt.mt[0] =-2.460;\n mt.mt[1] = 0.207; \n mt.mt[2] = 2.250;\n mt.mt[3] = 0.793;\n mt.mt[4] = 0.267;\n mt.mt[5] =-0.363;\n mt.sdr1[0] =335.0;\n mt.sdr1[1] = 46.0;\n mt.sdr1[2] =-113.0;\n mt.sdr2[0] = 186.0;\n mt.sdr2[1] = 49.0;\n mt.sdr2[2] =-68.0;\n mt.tax[0] = 2.32;\n mt.tax[1] = 2.0;\n mt.tax[2] = 261.0;\n mt.bax[0] = 0.38;\n mt.bax[1] = 16.0;\n mt.bax[2] = 351.0;\n mt.pax[0] =-2.70;\n mt.pax[1] = 74.0;\n mt.pax[2] =165.0;\n xscal = pow(10.0,mt.exp);\n cblas_dscal(n6, xscal, mt.mt, incx);\n cblas_dcopy(n6, mt.mt, 1, &mtTest[12], 1);\n ierr = decompose(1, mt.mt);\n if (ierr != EXIT_SUCCESS)\n {\n fprintf(stderr, \"Error decomposing 3\\n\");\n return EXIT_FAILURE;\n }\n //-----------------------------------4------------------------------------//\n mt.exp = 23.0 - 7.0;\n mt.mag = 4.9;\n mt.mt[0] =-2.270;\n mt.mt[1] = 0.058;\n mt.mt[2] = 2.210;\n mt.mt[3] = 0.079;\n mt.mt[4] =-0.737;\n mt.mt[5] = 0.246;\n mt.sdr1[0] =190.0;\n mt.sdr1[1] = 36.0;\n mt.sdr1[2] =-84.0;\n mt.sdr2[0] = 3.0;\n mt.sdr2[1] = 54.0;\n mt.sdr2[2] =-94.0;\n mt.tax[0] = 2.35;\n mt.tax[1] = 9.0;\n mt.tax[2] = 96.0;\n mt.bax[0] = 0.04;\n mt.bax[1] = 4.0;\n mt.bax[2] = 5.0;\n mt.pax[0] =-2.39;\n mt.pax[1] = 80.0;\n mt.pax[2] =253.0;\n xscal = pow(10.0,mt.exp);\n cblas_dscal(n6, xscal, mt.mt, incx);\n cblas_dcopy(n6, mt.mt, 1, &mtTest[18], 1);\n ierr = decompose(1, mt.mt);\n if (ierr != EXIT_SUCCESS)\n {\n fprintf(stderr, \"Error dcomposing 4\\n\");\n return EXIT_FAILURE;\n }\n //-----------------------------------5------------------------------------//\n mt.exp = 26.0 - 7.0;\n mt.mag = 6.5;\n mt.mt[0] = 0.745;\n mt.mt[1] =-0.036;\n mt.mt[2] =-0.709;\n mt.mt[3] =-0.242;\n mt.mt[4] =-0.048;\n mt.mt[5] = 0.208;\n mt.sdr1[0] =181.0;\n mt.sdr1[1] = 47.0;\n mt.sdr1[2] =114.0;\n mt.sdr2[0] = 328.0;\n mt.sdr2[1] = 48.0;\n mt.sdr2[2] = 67.0;\n mt.tax[0] = 0.82;\n mt.tax[1] = 73.0;\n mt.tax[2] = 166.0;\n mt.bax[0] =-0.05;\n mt.bax[1] = 17.0;\n mt.bax[2] = 344.0;\n mt.pax[0] =-0.77;\n mt.pax[1] = 1.0;\n mt.pax[2] = 74.0;\n xscal = pow(10.0,mt.exp);\n cblas_dscal(n6, xscal, mt.mt, incx);\n cblas_dcopy(n6, mt.mt, 1, &mtTest[24], 1);\n ierr = decompose(1, mt.mt);\n if (ierr != EXIT_SUCCESS)\n {\n fprintf(stderr, \"Error decomposing 5\\n\");\n return EXIT_FAILURE;\n }\n //-----------------------------------6------------------------------------//\n mt.exp = 24.0 - 7.0;\n mt.mag = 5.3;\n mt.mt[0] = 0.700;\n mt.mt[1] =-0.883;\n mt.mt[2] = 0.183;\n mt.mt[3] = 0.260;\n mt.mt[4] = 0.289;\n mt.mt[5] = 0.712;\n mt.sdr1[0] =329.0;\n mt.sdr1[1] = 54.0;\n mt.sdr1[2] =141.0;\n mt.sdr2[0] = 85.0;\n mt.sdr2[1] = 59.0;\n mt.sdr2[2] = 43.0;\n mt.tax[0] = 1.01;\n mt.tax[1] = 51.0;\n mt.tax[2] = 300.0;\n mt.bax[0] = 0.24;\n mt.bax[1] = 39.0;\n mt.bax[2] = 113.0;\n mt.pax[0] =-1.25;\n mt.pax[1] = 3.0;\n mt.pax[2] = 206.;\n xscal = pow(10.0,mt.exp);\n cblas_dscal(n6, xscal, mt.mt, incx);\n cblas_dcopy(n6, mt.mt, 1, &mtTest[30], 1);\n ierr = decompose(1, mt.mt);\n if (ierr != EXIT_SUCCESS)\n {\n fprintf(stderr, \"Error decomposing 6\\n\");\n return EXIT_FAILURE;\n }\n //-----------------------------------7------------------------------------//\n mt.exp = 23.0 - 7.0;\n mt.mag = 5.0;\n mt.mt[0] = 3.150;\n mt.mt[1] =-2.470;\n mt.mt[2] =-0.676;\n mt.mt[3] = 1.650;\n mt.mt[4] = 1.880;\n mt.mt[5] =-1.470;\n mt.sdr1[0] =252.0;\n mt.sdr1[1] = 28.0;\n mt.sdr1[2] =111.0;\n mt.sdr2[0] = 49.0;\n mt.sdr2[1] = 64.0;\n mt.sdr2[2] = 79.0;\n mt.tax[0] = 4.08;\n mt.tax[1] = 69.0;\n mt.tax[2] = 297.0;\n mt.bax[0] = 0.01;\n mt.bax[1] = 10.0;\n mt.bax[2] = 54.0;\n mt.pax[0] =-4.08;\n mt.pax[1] = 18.0;\n mt.pax[2] = 147.0;\n xscal = pow(10.0,mt.exp);\n cblas_dscal(n6, xscal, mt.mt, incx);\n cblas_dcopy(n6, mt.mt, 1, &mtTest[36], 1);\n ierr = decompose(1, mt.mt);\n if (ierr != EXIT_SUCCESS)\n {\n fprintf(stderr, \"Error decomposing 7\\n\");\n return EXIT_FAILURE;\n }\n //-----------------------------------8------------------------------------//\n mt.exp = 23.0 - 7.0;\n mt.mag = 4.8;\n mt.mt[0] =-1.870;\n mt.mt[1] = 0.488;\n mt.mt[2] = 1.380;\n mt.mt[3] =-0.057;\n mt.mt[4] = 0.600;\n mt.mt[5] = 0.664;\n mt.sdr1[0] = 36.0;\n mt.sdr1[1] = 38.0;\n mt.sdr1[2] =-76.0;\n mt.sdr2[0] = 199.0;\n mt.sdr2[1] = 53.0;\n mt.sdr2[2] =-101.0;\n mt.tax[0] = 1.80;\n mt.tax[1] = 8.0;\n mt.tax[2] = 296.0;\n mt.bax[0] = 0.18;\n mt.bax[1] = 9.0;\n mt.bax[2] = 205.0;\n mt.pax[0] =-1.99;\n mt.pax[1] = 78.0;\n mt.pax[2] = 69.0;\n xscal = pow(10.0,mt.exp);\n cblas_dscal(n6, xscal, mt.mt, incx);\n cblas_dcopy(n6, mt.mt, 1, &mtTest[42], 1);\n ierr = decompose(1, mt.mt);\n if (ierr != EXIT_SUCCESS)\n {\n fprintf(stderr, \"Error decomposing 8\\n\");\n return EXIT_FAILURE;\n }\n //-----------------------------------9------------------------------------//\n mt.exp = 23.0 - 7.0;\n mt.mag = 5.0;\n mt.mt[0] =-3.540;\n mt.mt[1] = 1.040;\n mt.mt[2] = 2.510;\n mt.mt[3] =-0.474;\n mt.mt[4] = 1.640;\n mt.mt[5] = 1.530;\n mt.sdr1[0] = 47.0;\n mt.sdr1[1] = 38.0;\n mt.sdr1[2] =-63.0;\n mt.sdr2[0] = 195.0;\n mt.sdr2[1] = 56.0;\n mt.sdr2[2] =-109.0;\n mt.tax[0] = 3.66;\n mt.tax[1] = 10.0;\n mt.tax[2] = 299.0;\n mt.bax[0] = 0.45;\n mt.bax[1] = 16.0;\n mt.bax[2] =206.0;\n mt.pax[0] =-4.10;\n mt.pax[1] = 71.0;\n mt.pax[2] = 58.0;\n xscal = pow(10.0,mt.exp);\n cblas_dscal(n6, xscal, mt.mt, incx);\n cblas_dcopy(n6, mt.mt, 1, &mtTest[48], 1);\n // now copy this\n for (jmt=9; jmt\n\n#include \n#include \n\n#define test_m 2\n#define test_k 3\n#define test_n 4\n#define test_m_extra 5\n#define test_k_extra 7\n#define test_n_extra 8\n\n#define test_row_major 1\n#define test_col_major 0\n\n\ndouble getRealTime();\n\n\n//! prints a matrix in either row major or column major order\nstatic void printMatrix (double *data, int rows, int cols, int row_major)\n{\n int i,j;\n\n // column header\n printf (\" \");\n for(j=0; j= m\n // if TRANSA = 'T' then >= k\n B, // B source matrix\n test_k_extra, // true lenght of a column in B\n // if TRANSB = 'N' then >= k\n // if TRANSB = 'T' then >= n\n 0.0, // beta = 0.0\n C, // C destination matrix\n test_n_extra); // true lenght of a row in C\n // must be >= m\n printMatrix (C, test_n_extra, test_n, test_col_major);\n}\n\n//! blas expects column major order\nstatic void testMulColMajor()\n{\n printf (\"==========================================================\\n\");\n printf (\"Test BLAS multiply - column major order\\n\");\n printf (\"==========================================================\\n\\n\");\n\n /* MATRIX A[2x3]\n\n Col 1 Col 2 Col 3\n Row 1: 1.0000 2.0000 3.0000\n Row 2: 4.0000 5.0000 6.0000\n\n */\n\n printf (\"A\\n\\n\");\n double A[test_m*test_k] = {\n 1, 4,\n 2, 5,\n 3, 6\n };\n printMatrix (A, test_m, test_k, test_col_major);\n\n /* MATRIX B[3x4]\n\n Col 1 Col 2 Col 3 Col 4\n Row 1: 1.0000 2.0000 3.0000 4.0000\n Row 2: 0.1000 0.2000 0.3000 0.4000\n Row 3: 0.0100 0.0200 0.0300 0.0400\n\n */\n printf (\"B\\n\\n\");\n double B[test_k*test_n] = {\n 1.0, 0.1, 0.01,\n 2.0, 0.2, 0.02,\n 3.0, 0.3, 0.03,\n 4.0, 0.4, 0.04\n };\n printMatrix (B, test_k, test_n, test_col_major);\n\n /* MATRIX C[2x4]\n\n Col 1 Col 2 Col 3 Col 4\n Row 1: 1.2300 2.4600 3.6900 4.9200\n Row 2: 4.5600 9.1200 13.6800 18.2400\n */\n double C[test_m*test_n] = {0};\n\n printf (\"C\\n\\n\");\n // http://www.math.utah.edu/software/lapack/lapack-blas/dgemm.html\n /*\n cblas_dgemm(\n 'N', // TRANSA: N - do not transpose A, T - transpose A\n 'N', // TRANSB: N - do not transpose A, T - transpose A\n test_m, // A matrix: m rows, k columns\n test_n, // B matrix: k rows, n columns\n test_k, // C matrix: m rows, n columns\n 1.0, // alpha = 1.0\n A, // A source matrix\n test_m, // true lenght of a column in A\n // if TRANSA = 'N' then >= m\n // if TRANSA = 'T' then >= k\n B, // B source matrix\n test_k, // true lenght of a column in B\n // if TRANSB = 'N' then >= k\n // if TRANSB = 'T' then >= n\n 0.0, // beta = 0.0\n C, // C destination matrix\n test_m); // true lenght of a row in C\n // must be >= m\n */\n // C = alpha*A*B+beta*C\n cblas_dgemm(\n CblasColMajor,\n CblasNoTrans, // TRANSA:\n CblasNoTrans, // TRANSB:\n test_m, // A matrix: m rows, k columns\n test_n, // B matrix: k rows, n columns\n test_k, // C matrix: m rows, n columns\n 1.0, // alpha = 1.0\n A, // A source matrix\n test_m, // true lenght of a column in A\n // if TRANSA = 'N' then >= m\n // if TRANSA = 'T' then >= k\n B, // B source matrix\n test_k, // true lenght of a column in B\n // if TRANSB = 'N' then >= k\n // if TRANSB = 'T' then >= n\n 0.0, // beta = 0.0\n C, // C destination matrix\n test_m); // true lenght of a row in C\n // must be >= m\n printMatrix (C, test_m, test_n, test_col_major);\n}\n\n//! attempt the trickery\nstatic void testMulRowMajor_trickery()\n{\n printf (\"==========================================================\\n\");\n printf (\"Test BLAS multiply - row major order with trickery\\n\");\n printf (\"==========================================================\\n\\n\");\n\n /* MATRIX A[2x3]\n\n Col 1 Col 2 Col 3\n Row 1: 1.0000 2.0000 3.0000\n Row 2: 4.0000 5.0000 6.0000\n\n */\n\n printf (\"A\\n\\n\");\n double A[test_m*test_k] = {\n 1, 2, 3,\n 4, 5, 6\n };\n printMatrix (A, test_m, test_k, test_row_major);\n\n /* MATRIX B[3x4]\n\n Col 1 Col 2 Col 3 Col 4\n Row 1: 1.0000 2.0000 3.0000 4.0000\n Row 2: 0.1000 0.2000 0.3000 0.4000\n Row 3: 0.0100 0.0200 0.0300 0.0400\n\n */\n printf (\"B\\n\\n\");\n double B[test_k*test_n] = {\n 1.00, 2.00, 3.00, 4.00,\n 0.10, 0.20, 0.30, 0.40,\n 0.01, 0.02, 0.03, 0.04\n };\n printMatrix (B, test_k, test_n, test_row_major);\n\n /* MATRIX C[2x4]\n\n Col 1 Col 2 Col 3 Col 4\n Row 1: 1.2300 2.4600 3.6900 4.9200\n Row 2: 4.5600 9.1200 13.6800 18.2400\n */\n double C[test_m*test_n] = {0};\n\n printf (\"C\\n\\n\");\n\n // C = alpha*A*B+beta*C\n cblas_dgemm(\n CblasColMajor,\n CblasNoTrans, // TRANSA:\n CblasNoTrans, // TRANSB:\n test_n, // B matrix: k rows, n columns\n test_m, // A matrix: m rows, k columns\n test_k, // C matrix: m rows, n columns\n 1.0, // alpha = 1.0\n B, // B source matrix\n test_n, // true lenght of a column in B\n // if TRANSB = 'N' then >= k\n // if TRANSB = 'T' then >= n\n A, // A source matrix\n test_k, // true lenght of a column in A\n // if TRANSA = 'N' then >= m\n // if TRANSA = 'T' then >= k\n 0.0, // beta = 0.0\n C, // C destination matrix\n test_n); // true lenght of a row in C\n // must be >= m\n printMatrix (C, test_m, test_n, test_row_major);\n}\n\n//! build in version\nstatic void testMulRowMajor()\n{\n printf (\"==========================================================\\n\");\n printf (\"Test BLAS multiply - row major order without trickery\\n\");\n printf (\"==========================================================\\n\\n\");\n\n /* MATRIX A[2x3]\n\n Col 1 Col 2 Col 3\n Row 1: 1.0000 2.0000 3.0000\n Row 2: 4.0000 5.0000 6.0000\n\n */\n\n printf (\"A\\n\\n\");\n double A[test_m*test_k] = {\n 1, 2, 3,\n 4, 5, 6\n };\n printMatrix (A, test_m, test_k, test_row_major);\n\n /* MATRIX B[3x4]\n\n Col 1 Col 2 Col 3 Col 4\n Row 1: 1.0000 2.0000 3.0000 4.0000\n Row 2: 0.1000 0.2000 0.3000 0.4000\n Row 3: 0.0100 0.0200 0.0300 0.0400\n\n */\n printf (\"B\\n\\n\");\n double B[test_k*test_n] = {\n 1.00, 2.00, 3.00, 4.00,\n 0.10, 0.20, 0.30, 0.40,\n 0.01, 0.02, 0.03, 0.04\n };\n printMatrix (B, test_k, test_n, test_row_major);\n\n /* MATRIX C[2x4]\n\n Col 1 Col 2 Col 3 Col 4\n Row 1: 1.2300 2.4600 3.6900 4.9200\n Row 2: 4.5600 9.1200 13.6800 18.2400\n */\n double C[test_m*test_n] = {0};\n\n printf (\"C\\n\\n\");\n\n // C = alpha*A*B+beta*C\n cblas_dgemm(\n CblasRowMajor,\n CblasNoTrans, // TRANSA:\n CblasNoTrans, // TRANSB:\n test_m, // A matrix: m rows, k columns\n test_n, // B matrix: k rows, n columns\n test_k, // C matrix: m rows, n columns\n 1.0, // alpha = 1.0\n A, // A source matrix\n test_k, // true lenght of a column in A\n // if TRANSA = 'N' then >= m\n // if TRANSA = 'T' then >= k\n B, // B source matrix\n test_n, // true lenght of a column in B\n // if TRANSB = 'N' then >= k\n // if TRANSB = 'T' then >= n\n 0.0, // beta = 0.0\n C, // C destination matrix\n test_n); // true lenght of a row in C\n // must be >= m\n printMatrix (C, test_m, test_n, test_col_major);\n}\n\n#undef test_m\n#undef test_n\n#undef test_k\n\n#define test_m 500\n#define test_k 600\n#define test_n 700\n\n#define test_spins 5\n\n// ---------------------------------------------------------------------\n#define IMPLEMENTATION_ROW_MAJOR \\\n cblas_dgemm( \\\n CblasRowMajor, CblasNoTrans, CblasNoTrans, test_m, test_n, \\\n test_k, 1.0, A, test_k, B, test_n, 0.0, C, test_n); \\\n startTime = getRealTime (); \\\n for(i=0; i\n\n#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))\n#include \t/* POSIX flags */\n#include \t/* clock_gettime(), time() */\n#include \t/* gethrtime(), gettimeofday() */\n\n#if defined(__MACH__) && defined(__APPLE__)\n#include \n#include \n#endif\n\n#else\n#error \"Unable to define getRealTime( ) for an unknown OS.\"\n#endif\n\n\n\n\n\n/**\n * Returns the real time, in seconds, or -1.0 if an error occurred.\n *\n * Time is measured since an arbitrary and OS-dependent start time.\n * The returned real time is only useful for computing an elapsed time\n * between two calls to this function.\n */\ndouble getRealTime( )\n{\n#if defined(_WIN32)\n FILETIME tm;\n ULONGLONG t;\n#if defined(NTDDI_WIN8) && NTDDI_VERSION >= NTDDI_WIN8\n /* Windows 8, Windows Server 2012 and later. ---------------- */\n GetSystemTimePreciseAsFileTime( &tm );\n#else\n /* Windows 2000 and later. ---------------------------------- */\n GetSystemTimeAsFileTime( &tm );\n#endif\n t = ((ULONGLONG)tm.dwHighDateTime << 32) | (ULONGLONG)tm.dwLowDateTime;\n return (double)t / 10000000.0;\n\n#elif (defined(__hpux) || defined(hpux)) || ((defined(__sun__) || defined(__sun) || defined(sun)) && (defined(__SVR4) || defined(__svr4__)))\n /* HP-UX, Solaris. ------------------------------------------ */\n return (double)gethrtime( ) / 1000000000.0;\n\n#elif defined(__MACH__) && defined(__APPLE__)\n /* OSX. ----------------------------------------------------- */\n static double timeConvert = 0.0;\n if ( timeConvert == 0.0 )\n {\n mach_timebase_info_data_t timeBase;\n (void)mach_timebase_info( &timeBase );\n timeConvert = (double)timeBase.numer /\n (double)timeBase.denom /\n 1000000000.0;\n }\n return (double)mach_absolute_time( ) * timeConvert;\n\n#elif defined(_POSIX_VERSION)\n /* POSIX. --------------------------------------------------- */\n#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)\n {\n struct timespec ts;\n#if defined(CLOCK_MONOTONIC_PRECISE)\n /* BSD. --------------------------------------------- */\n const clockid_t id = CLOCK_MONOTONIC_PRECISE;\n#elif defined(CLOCK_MONOTONIC_RAW)\n /* Linux. ------------------------------------------- */\n const clockid_t id = CLOCK_MONOTONIC_RAW;\n#elif defined(CLOCK_HIGHRES)\n /* Solaris. ----------------------------------------- */\n const clockid_t id = CLOCK_HIGHRES;\n#elif defined(CLOCK_MONOTONIC)\n /* AIX, BSD, Linux, POSIX, Solaris. ----------------- */\n const clockid_t id = CLOCK_MONOTONIC;\n#elif defined(CLOCK_REALTIME)\n /* AIX, BSD, HP-UX, Linux, POSIX. ------------------- */\n const clockid_t id = CLOCK_REALTIME;\n#else\n const clockid_t id = (clockid_t)-1;\t/* Unknown. */\n#endif /* CLOCK_* */\n if ( id != (clockid_t)-1 && clock_gettime( id, &ts ) != -1 )\n return (double)ts.tv_sec +\n (double)ts.tv_nsec / 1000000000.0;\n /* Fall thru. */\n }\n#endif /* _POSIX_TIMERS */\n\n /* AIX, BSD, Cygwin, HP-UX, Linux, OSX, POSIX, Solaris. ----- */\n struct timeval tm;\n gettimeofday( &tm, NULL );\n return (double)tm.tv_sec + (double)tm.tv_usec / 1000000.0;\n#else\n return -1.0;\t\t/* Failed. */\n#endif\n}\n\n", "meta": {"hexsha": "55d6f4817f331696acb7f539b6d720f2e7fedabb", "size": 19261, "ext": "c", "lang": "C", "max_stars_repo_path": "cblas_test.c", "max_stars_repo_name": "elsuizo/C_work", "max_stars_repo_head_hexsha": "a2752c37c68a073cc1144eb8742303316281fb60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cblas_test.c", "max_issues_repo_name": "elsuizo/C_work", "max_issues_repo_head_hexsha": "a2752c37c68a073cc1144eb8742303316281fb60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cblas_test.c", "max_forks_repo_name": "elsuizo/C_work", "max_forks_repo_head_hexsha": "a2752c37c68a073cc1144eb8742303316281fb60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5245641838, "max_line_length": 140, "alphanum_fraction": 0.4827890556, "num_tokens": 6018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.43857677181812277}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef GSL_FOUND\n#include \n#endif\n\n#include \"core_allvars.h\"\n#include \"core_init.h\"\n#include \"core_mymalloc.h\"\n#include \"core_cool_func.h\"\n\n\n/* These functions do not need to be exposed externally */\ndouble integrand_time_to_present(const double a, void *param);\nvoid set_units(struct params *run_params);\nvoid read_snap_list(const int ThisTask, struct params *run_params);\ndouble time_to_present(const double z, struct params *run_params);\n\n#ifdef HDF5\n#include \"io/io_save_hdf5.h\"\n#endif\n\nvoid init(const int ThisTask, struct params *run_params)\n{\n run_params->Age = mymalloc(ABSOLUTEMAXSNAPS*sizeof(run_params->Age[0]));\n \n set_units(run_params);\n\n read_snap_list(ThisTask, run_params);\n\n //Hack to fix deltaT for snapshot 0\n //This way, galsnapnum = -1 will not segfault.\n run_params->Age[0] = time_to_present(1000.0, run_params);//lookback time from z=1000\n run_params->Age++;\n \n for(int i = 0; i < run_params->Snaplistlen; i++) {\n run_params->ZZ[i] = 1 / run_params->AA[i] - 1;\n run_params->Age[i] = time_to_present(run_params->ZZ[i], run_params);\n }\n\n run_params->a0 = 1.0 / (1.0 + run_params->Reionization_z0);\n run_params->ar = 1.0 / (1.0 + run_params->Reionization_zr);\n\n read_cooling_functions();\n if(ThisTask == 0) {\n printf(\"cooling functions read\\n\\n\");\n }\n\n#if 0 \n#ifdef HDF5\n if(HDF5Output) {\n calc_hdf5_props();\n }\n#endif\n#endif\n\n}\n\n\n\nvoid set_units(struct params *run_params)\n{\n\n run_params->UnitTime_in_s = run_params->UnitLength_in_cm / run_params->UnitVelocity_in_cm_per_s;\n run_params->UnitTime_in_Megayears = run_params->UnitTime_in_s / SEC_PER_MEGAYEAR;\n run_params->G = GRAVITY / pow(run_params->UnitLength_in_cm, 3) * run_params->UnitMass_in_g * pow(run_params->UnitTime_in_s, 2);\n run_params->UnitDensity_in_cgs = run_params->UnitMass_in_g / pow(run_params->UnitLength_in_cm, 3);\n run_params->UnitPressure_in_cgs = run_params->UnitMass_in_g / run_params->UnitLength_in_cm / pow(run_params->UnitTime_in_s, 2);\n run_params->UnitCoolingRate_in_cgs = run_params->UnitPressure_in_cgs / run_params->UnitTime_in_s;\n run_params->UnitEnergy_in_cgs = run_params->UnitMass_in_g * pow(run_params->UnitLength_in_cm, 2) / pow(run_params->UnitTime_in_s, 2);\n\n run_params->EnergySNcode = run_params->EnergySN / run_params->UnitEnergy_in_cgs * run_params->Hubble_h;\n run_params->EtaSNcode = run_params->EtaSN * (run_params->UnitMass_in_g / SOLAR_MASS) / run_params->Hubble_h;\n\n // convert some physical input parameters to internal units \n run_params->Hubble = HUBBLE * run_params->UnitTime_in_s;\n\n // compute a few quantitites \n run_params->RhoCrit = 3.0 * run_params->Hubble * run_params->Hubble / (8 * M_PI * run_params->G);\n}\n\n\n\nvoid read_snap_list(const int ThisTask, struct params *run_params)\n{\n char fname[MAX_STRING_LEN+1];\n\n snprintf(fname, MAX_STRING_LEN, \"%s\", run_params->FileWithSnapList);\n FILE *fd = fopen(fname, \"r\"); \n if(fd == NULL) {\n printf(\"can't read output list in file '%s'\\n\", fname);\n ABORT(0);\n }\n\n run_params->Snaplistlen = 0;\n do {\n if(fscanf(fd, \" %lg \", &(run_params->AA[run_params->Snaplistlen])) == 1) {\n run_params->Snaplistlen++;\n } else {\n break;\n }\n } while(run_params->Snaplistlen < run_params->MAXSNAPS);\n fclose(fd);\n\n if(ThisTask == 0) {\n printf(\"found %d defined times in snaplist\\n\", run_params->Snaplistlen);\n }\n}\n\n\n\ndouble time_to_present(const double z, struct params *run_params)\n{\n const double end_limit = 1.0;\n const double start_limit = 1.0/(1 + z);\n double result=0.0;\n#ifdef GSL_FOUND\n#define WORKSIZE 1000\n gsl_function F;\n gsl_integration_workspace *workspace;\n double abserr;\n\n workspace = gsl_integration_workspace_alloc(WORKSIZE);\n F.function = &integrand_time_to_present;\n F.params = run_params;\n\n gsl_integration_qag(&F, start_limit, end_limit, 1.0 / run_params->Hubble,\n 1.0e-9, WORKSIZE, GSL_INTEG_GAUSS21, workspace, &result, &abserr);\n\n gsl_integration_workspace_free(workspace);\n\n#undef WORKSIZE \n#else\n /* Do not have GSL - let's integrate numerically ourselves */\n const double step = 1e-7;\n const int64_t nsteps = (end_limit - start_limit)/step;\n result = 0.0;\n const double y0 = integrand_time_to_present(start_limit + 0*step, run_params);\n const double yn = integrand_time_to_present(start_limit + nsteps*step, run_params);\n for(int64_t i=1; i MS 23/6/2018) */\n const double time = 1.0 / run_params->Hubble * result;\n\n // return time to present as a function of redshift \n return time;\n}\n\n\n\ndouble integrand_time_to_present(const double a, void *param)\n{\n const struct params *run_params = (struct params *) param;\n return 1.0 / sqrt(run_params->Omega / a + (1.0 - run_params->Omega - run_params->OmegaLambda) + run_params->OmegaLambda * a * a);\n}\n\n\n\n", "meta": {"hexsha": "c12b90728245858026c266c7cddd3ef1905a4120", "size": 5329, "ext": "c", "lang": "C", "max_stars_repo_path": "src/core_init.c", "max_stars_repo_name": "manodeep/lfs_sage", "max_stars_repo_head_hexsha": "de7040b9eee3c437fc129828bb64bd835be64ae2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-22T03:19:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-22T03:19:14.000Z", "max_issues_repo_path": "src/core_init.c", "max_issues_repo_name": "manodeep/lfs_sage", "max_issues_repo_head_hexsha": "de7040b9eee3c437fc129828bb64bd835be64ae2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-13T10:57:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T02:16:53.000Z", "max_forks_repo_path": "src/core_init.c", "max_forks_repo_name": "manodeep/lfs_sage", "max_forks_repo_head_hexsha": "de7040b9eee3c437fc129828bb64bd835be64ae2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1637426901, "max_line_length": 137, "alphanum_fraction": 0.689810471, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.43842855838294115}} {"text": "/*\n * BRAINS\n * (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling\n * Yan-Rong Li, liyanrong@ihep.ac.cn\n * Thu, Aug 4, 2016\n */\n\n/*!\n * \\file smooth.c\n * \\brief smoothing functions using FFT provided by GSL.\n *\n * References: Press et al., Numerical Recipes, Chapter 13.1.\n * GSL documents\n */\n\n///////////////THIS FILE IS DEPRECATED///////////////////////////\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"brains.h\"\n\nint nd_fft;\n\ndouble *resp, *data_fft;\ndouble *resp_cmp, *data_fft_cmp, *data_fft_inverse;\n\ngsl_fft_real_wavetable * real_data, *real_resp;\ngsl_fft_complex_wavetable * cmp_data;\ngsl_fft_real_workspace * work_data, *work_resp;\ngsl_fft_complex_workspace * work_cmp;\n\n\n/*!\n * This function initiates workspace for FFT.\n */\nvoid smooth_init(int nv, const double *transv)\n{\n //nd_fft = parset.n_vel_recon>=n_vel_data? parset.n_vel_recon : n_vel_data;\n nd_fft = nv;\n //printf(\"%d\\n\", nd_fft);\n real_data = gsl_fft_real_wavetable_alloc (nd_fft);\n real_resp = gsl_fft_real_wavetable_alloc (nd_fft);\n cmp_data = gsl_fft_complex_wavetable_alloc (nd_fft);\n\n work_data = gsl_fft_real_workspace_alloc (nd_fft);\n work_resp = gsl_fft_real_workspace_alloc (nd_fft);\n work_cmp = gsl_fft_complex_workspace_alloc (nd_fft);\n\n resp = malloc(nd_fft * sizeof(double));\n data_fft = malloc(nd_fft * sizeof(double));\n\n resp_cmp = malloc(nd_fft * 2 * sizeof(double));\n data_fft_cmp = malloc(nd_fft *2 * sizeof(double));\n data_fft_inverse = malloc(nd_fft *2 * sizeof(double));\n\n // initialize response and its fft.\n int i;\n double sigV, dV, tot;\n\n sigV = parset.InstRes / VelUnit;\n dV = transv[1] - transv[0];\n\n /* setup response, whose negective-time part is wrapped around and stored at the right hand*/\n tot = 0.0;\n for (i = 0; i= nd_fft/2; i--)\n {\n resp[i] = 1.0/sqrt(2.0*M_PI)/sigV * exp(-0.5*((i-nd_fft)*dV)*((i-nd_fft)*dV)/sigV/sigV);\n tot += resp[i];\n } \n \n /* normalize response */\n for(i=0; i= nd_fft/2; i--)\n {\n resp[i] = 1.0/sqrt(2.0*M_PI)/sigV * exp(-0.5*((i-nd_fft)*dV)*((i-nd_fft)*dV)/sigV/sigV);\n tot += resp[i];\n } \n \n for(i=0; i= n/2; i--)\n {\n resp[i] = 1.0/sqrt(2.0*M_PI)/10.0 * exp(-0.5*(i-n)*(i-n)/10.0/10.0);\n } \n\n for (i = 0; i < n; i++)\n {\n printf (\"%d: %e\\n\", i, data[i]);\n }\n printf (\"\\n\");\n\n work = gsl_fft_real_workspace_alloc (n);\n real = gsl_fft_real_wavetable_alloc (n);\n \n work_resp = gsl_fft_real_workspace_alloc (n);\n real_resp = gsl_fft_real_wavetable_alloc (n);\n\n work_cmp = gsl_fft_complex_workspace_alloc(n);\n hc = gsl_fft_complex_wavetable_alloc (n);\n\n gsl_fft_real_transform (data, 1, n, real, work);\n gsl_fft_real_transform (resp, 1, n, real_resp, work_resp);\n \n gsl_fft_halfcomplex_unpack(data, data_cmp, 1, n);\n gsl_fft_halfcomplex_unpack(resp, resp_cmp, 1, n);\n \n for(i=0; i\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#ifndef _HEART_H\r\n#define _HEART_H\r\n\r\n\r\n\r\n\r\nclass heart\r\n{\r\n\tprivate:\r\n\t\tint L; //sytem size length for now square\r\n\r\n\t\tstd::vector> state; //value indicates whether in excited state refactory or resting\r\n\t\tstd::vector> new_state; //using new_state and state to distinguish newly excited cells from previously excited\r\n\t\tstd::vector> functional; //1 if functional 0 if disfunctional\r\n\t\tstd::vector> bond; //1 if bond to site above current cell, 0 if no bond above site\r\n\t\tstd::vector> unablated; // Defaults to zero initial value\r\n\t\tint heart_time; //internal clock\r\n\t\t//model parameters \r\n\t\tint tau; //refactory period\r\n\t\tint T; // pacemaker rate\r\n\t\tdouble nu, epsilom, delta; //probability vertical connection exists, probability of misfire given faulty and probability cell faulty \r\n\t\t\r\n\t\t//random number generator \r\n\t\tconst gsl_rng_type*Type;\r\n\t\tgsl_rng*r; \r\n\r\n\t\tint total_bonds;\r\n\t\tint total_functional;\r\n\t\tint total_excited;\r\n\t\t\r\n\r\n\tpublic:\r\n\r\n\t\theart()\r\n\t\t{\r\n\r\n\t\t}\r\n\t\theart(const int _L, int _T, int _tau ,double _nu, double _epsilom, double _delta)\r\n\t\t{\r\n\t\t\tL=_L;\r\n\t\t\tnu= _nu;\r\n\t\t\ttau=_tau;\r\n\t\t\tT=_T;\r\n\t\t\tepsilom=_epsilom;\r\n\t\t\tdelta=_delta;\r\n\t\t\theart_time = T;\r\n\t\t\t\r\n\t\t\tstate.resize(L);\r\n\t\t\tnew_state.resize(L);\r\n\t\t\tfunctional.resize(L);\r\n\t\t\tbond.resize(L);\r\n\t\t\tunablated.resize(L);\r\n\t\t\t//pacemaker action\r\n\t\t\tfor(unsigned i=0; idelta);// inequality reversed\r\n\t\t\t\t\t//double x = gsl_rng_uniform(r);\r\n\t\t\t\t//\tstd::cout <0)+(L-1)*(i<1)][j]+=(state[(i-1)*(i>0)+(L-1)*(i<1)][j]<1)*bond[(i-1)*(i>0)+(L-1)*(i<1)][j]*(1-(1-functional[(i-1)*(i>0)+(L-1)*(i<1)][j])*(gsl_rng_uniform(r)0)+(L-1)*(i<1)][j];\r\n\t\t\t\t\t\r\n\t\t\t\t\t\tnew_state[i][(j+1)*(j0)]+= (j>0)*(state[i][(j-1)*(j>0)]<1)*(1-(1-functional[i][(j-1)*(j>0)])*(gsl_rng_uniform(r)0)];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\t//end relaxing\r\n\r\n\r\n\t\t\t//evolving cells that were not excited previously or now (some subtlty to those possibly excited now)\r\n\t\t\tfor(int i=0;i0);\r\n\t\t\t\t\t//if state was excited or refactory before +1 states that were resting may have been newly excited or not but this ignores them\r\n\t\t\t\t\tnew_state[i][j] *= (state[i][j]T-1)*(1-(1-functional[i][0])*(gsl_rng_uniform(r)1);\r\n\t\t\t//return state[i][j]/(1.0*T);\r\n\t\t\t\r\n\t\t}\r\n\t\tvoid interact(sf::RenderWindow & renderWindow, int length) \r\n\t\t{\r\n\t\t\tsf::Event event;\r\n\t\t\tfloat x;\r\n\t\t\tfloat y;\r\n\t\t\t\r\n\t\t\tfloat Mx = sf::Mouse::getPosition(renderWindow).x;\r\n\t\t\tfloat My = sf::Mouse::getPosition(renderWindow).y;\r\n\t\t\t//std::cout << Mx << \" \" << My << std::endl;\r\n\t\t\twhile (renderWindow.pollEvent(event))\r\n\t\t\t{\r\n\t\t\tswitch(event.type)\r\n\t\t\t{\r\n\t\t\tcase sf::Event::KeyPressed:\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\tstate[My/length][Mx/length] = 0;\r\n\t\t\t\tnew_state[My/length][Mx/length] = 0;\r\n\t\t\t\tunablated[My/length][Mx/length] = 0;\r\n\r\n\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n};\r\n#endif", "meta": {"hexsha": "08bb4524deef8e7bb852774575bfb33c37bf33c5", "size": 6142, "ext": "h", "lang": "C", "max_stars_repo_path": "ablation 1/heart.h", "max_stars_repo_name": "pm2111/Heart-Defibrillation-Project", "max_stars_repo_head_hexsha": "48ea3570c360aac7c3ff46354891998f4f364fab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ablation 1/heart.h", "max_issues_repo_name": "pm2111/Heart-Defibrillation-Project", "max_issues_repo_head_hexsha": "48ea3570c360aac7c3ff46354891998f4f364fab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ablation 1/heart.h", "max_forks_repo_name": "pm2111/Heart-Defibrillation-Project", "max_forks_repo_head_hexsha": "48ea3570c360aac7c3ff46354891998f4f364fab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9385964912, "max_line_length": 231, "alphanum_fraction": 0.5906870726, "num_tokens": 1985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4382917995472113}} {"text": "// The first test on 25/3/80 contains no information about\n// infection because ewes had not been exposed to the donors at this time\n// The first test date is end of March which we consider start of April\n\n// Time is counted in months at the start of each month, so month 0 is 1 April 1980\n// A seroconversion observed at the start of month m means the seroconversion \n// occurred before the start of month m, eg in month m-1 or before\n\n// Sheep are assumed to be born on the 1st April of each year, ie months 0, 12 and 24\n// A sheep's last month is the last month it was tested. We assume that it is immediately removed\n// This means that a +ve sheep is not infectious on its last_month\n// We assume, however, that a sheep is potentially infected and infectious at most one month prior to\n// its first positive month\n\n// Donor sheep 72 is assumed infectious at the start, because its dam tests positive within 3 months of birth\n// Donor 22 is assumed to be latent at the start due to it being removed after 3.5 years,\n// so it may have just been infected at the start\n\n#include \n#include \n#include \n#include \n#include \"sheep_data.h\"\n\n#define P_inv_gamma gsl_cdf_gamma_Pinv // invverse cumulative gamma dist\n#define P_inc_gamma gsl_sf_gamma_inc_P // regularised incomplete Gamma function\n#define lngamma gsl_sf_lngamma // ln Gamma function\n#define NUMBER_DONORS 2\n#define NUMBER_SHEEP 45\n#define INTRO_MONTHS 3\n#define V0 11\n\nconst uint intro_months[] = {0, 12, 24};\n\ntypedef struct {\n double a;\n double *lambda;\n double *Lambda;\n double *b;\n double *B;\n double **W4;\n double *W2;\n} parameters_t;\n\ndouble u(int, int, double*);\ndouble lngexpan(double, double, int*);\ndouble ln_inc_gamma_star(double, double);\ndouble w(int, int, int, int, parameters_t*);\ndouble Prob_seroconvert(int, int, parameters_t*);\nextern double R0(double, double, double, int, double*);\n\nvoid Variables(struct variables *V) \n{\n int i;\n Var(V, 0, \"month\");\n Var(V, 1, \"expected number infected\");\n Var(V, 2, \"expected number infectious\");\n Var(V, 3, \"cumulative seroconversions\");\n Var(V, 4, \"seroconversion rate\");\n Var(V, 5, \"expected number seroconverted\");\n Var(V, 6, \"cumulative field infected\");\n Var(V, 7, \"cumulative housed infected\");\n Var(V, 8, \"cumulative poor condition infected\");\n Var(V, 9, \"cumulative total infected\");\n Var(V, 10, \"infections\");\n for (i = 0; i < INTRO_MONTHS+1; i++)\n Var(V, V0+i, \"P_seropos\"); \n}\n\nvoid Parameters(int trt, int ind, double *p, struct parameterset *Q) \n{\n Par(Q, 0, Real, \"beta_{field}\", Exponential, 0.02);\n Par(Q, 1, Real, \"beta_{housed}\", Gamma, 2.0, 0.1);\n Par(Q, 2, Real, \"a\", Uniform, 1.e-3, 100.);\n Par(Q, 3, Real, \"k1\", Exponential, 24.0);\n Par(Q, 5, Real, \"L\", Uniform, 0., 60.);\n Par(Q, 7, Int, \"tau\", Uniform, 1, 4);\n Par(Q, 8, Real, \"beta_{pc}\", Gamma, 2.0, 1.0);\n\n Par(Q, 10, Real, \"beta_{housed}/beta_{field}\", Der);\n Par(Q, 12, Real, \"E[inf_{field}]\", Der);\n Par(Q, 13, Real, \"E[inf_{housed}]\", Der);\n Par(Q, 14, Real, \"E[inf]\", Der);\n Par(Q, 16, Real, \"s_{median,1}\", Der);\n Par(Q, 17, Real, \"s_{median,2}\", Der);\n Par(Q, 18, Real, \"s_{95,1}\", Der);\n Par(Q, 19, Real, \"s_{95,2}\", Der);\n}\n\nint Model(const uint trt, const uint ind, const uint nmonths, double *p, double **V, TimePoints *Data) \n{\n int i, j, n, m;\n double *Einf_field, *Einf_housed;\n double **p_seropos = V, pinf;\n \n double beta_field = p[0];\n double beta_housed = p[1];\n double beta_pc = p[8];\n double S_a = p[2];\n double S_b1 = S_a/p[3];\n double S_b2 = S_a/p[3];\n double L = p[5];\n int tau = lrint(p[7]);\n\n double *num_infectious = doublevector(nmonths);\n double *num_infected = doublevector(nmonths);\n // double *num_seroconverted = doublevector(nmonths);\n double *L_cdf = doublevector(nmonths);\n // double *S_cdf = doublevector(nmonths);\n\n parameters_t pars;\n pars.Lambda = doublevector(nmonths);\n pars.lambda = doublevector(nmonths);\n pars.B = doublevector(nmonths);\n pars.b = doublevector(nmonths);\n pars.W4 = doublematrix(nmonths, nmonths);\n pars.W2 = doublevector(nmonths);\n pars.a = S_a;\n\n // cumulative distribution of latent period\n for (m = 0; m < nmonths; m++) {\n // L_cdf[m] = gsl_cdf_gamma_P((double)m, L_a, 1./L_b);\n L_cdf[m] = (m < L? 0: 1);\n // S_cdf[m] = gsl_cdf_gamma_P((double)m, pars.a, 1./pars.b);\n }\n\n // calculate expected number of infectious ewes and force of infection, lambda\n // the two donor ewes and the lamb are infected at start of experiment\n int donors_lamb[] = {0, 1, 44};\n for (i = 0; i < NUMBER_DONORS+1; i++) {\n j = donors_lamb[i];\n for (m = sheep_intro_month[j]; m < sheep_last_month[j]; m++) {\n num_infected[m]++;\n if (j == 0)\n num_infectious[m]++;\n else\n num_infectious[m] += L_cdf[m-sheep_intro_month[j]];\n }\n }\n\n for (m = 0; m < nmonths; m++) {\n // calculate force of infection\n // ewes are housed for tau months (1 to 4) ending in March\n if (21 <= m && m < 24)\n // transmission rate for poor conditioned housed ewes in winter 1982\n pars.lambda[m] = num_infectious[m]*beta_pc;\n else if (4-tau <= (m+4)%12 && (m+4)%12 <= 3)\n // transmission rate for housed ewes in winter\n pars.lambda[m] = num_infectious[m]*beta_housed;\n else\n // field transmission rate\n pars.lambda[m] = num_infectious[m]*beta_field;\n\n // cumulative lambda used for prob of uninfected\n if (m > 1)\n pars.Lambda[m] = pars.Lambda[m-1]+pars.lambda[m-1];\n\n for (j = NUMBER_DONORS; j < NUMBER_SHEEP; j++)\n if (use_sheep[j] && negatives[j] > ind && sheep_intro_month[j] <= m && m < sheep_last_month[j]) {\n // probability this sheep is infected during this month m\n pinf = (1.-exp(-pars.lambda[m]))*u(sheep_intro_month[j], m, pars.Lambda);\n for (n = m+1; n < sheep_last_month[j]; n++) {\n num_infected[n] += pinf;\n num_infectious[n] += pinf*L_cdf[n-1-m];\n // num_seroconverted[i] += pinf*S_cdf[n-1-m];\n }\n }\n }\n\n // monthly seroconversion rates\n for (m = 0; m < nmonths; m++)\n if (m == 22)\n // increased seroconversion rate in winter 1982 due to poor condition and \n pars.b[m] = S_b2;\n else\n pars.b[m] = S_b1;\n // cumulative seroconversion rate\n for (m = 1; m < nmonths; m++)\n pars.B[m] = pars.B[m-1] + pars.b[m-1];\n \n // W4 and W2 per month\n for (m = 0; m < nmonths; m++) {\n for (n = 0; n < m; n++)\n pars.W4[n][m] = w(n, m, n+1, m+1, &pars) \n - w(n, m, n+1, m, &pars) \n - w(n, m, n, m+1, &pars) \n + w(n, m, n, m, &pars);\n pars.W2[m] = w(m, m, m, m+1, &pars);\n }\n \n // calculate the probability that a randomly selected sheep seroconverts in month m\n for (j = 0; j < INTRO_MONTHS; j++)\n for (m = intro_months[j]; m < nmonths; m++)\n p_seropos[m][V0+j] = Prob_seroconvert(intro_months[j], m, &pars);\n\n // 3 sheep were born in month 12, were removed in month 20 and retested in month 36, all were negative\n j = 13;\n // save lambda\n double *lambda_s = doublevector(nmonths);\n double *Lambda_s = doublevector(nmonths);\n for (m = sheep_last_month[j]; m < sheep_last_test_month[j]; m++) {\n lambda_s[m] = pars.lambda[m];\n Lambda_s[m] = pars.Lambda[m];\n }\n\n // set lambda=0 for the months from removal (last_month) until testing and recalculate Lambda\n for (m = sheep_last_month[j]; m < sheep_last_test_month[j]; m++) \n pars.lambda[m] = 0;\n for (m = sheep_last_month[j]+1; m < sheep_last_test_month[j]; m++)\n pars.Lambda[m] = pars.Lambda[m-1];\n\n // recalculate prob of seroconverting for these 3 sheep\n for (m = sheep_last_month[j]; m < sheep_last_test_month[j]; m++) {\n for (n = sheep_last_month[j]; n < m; n++)\n pars.W4[n][m] = w(n, m, n+1, m+1, &pars) \n - w(n, m, n+1, m, &pars) \n - w(n, m, n, m+1, &pars) \n + w(n, m, n, m, &pars);\n pars.W2[m] = w(m, m, m, m+1, &pars);\n }\n for (m = sheep_intro_month[j]; m < sheep_last_test_month[j]; m++)\n p_seropos[m][V0+sheep_var[j]] = Prob_seroconvert(sheep_intro_month[j], m, &pars);\n\n // restore lambda\n for (m = sheep_last_month[j]; m < sheep_last_test_month[j]; m++) {\n pars.lambda[m] = lambda_s[m];\n pars.Lambda[m] = Lambda_s[m];\n }\n free(lambda_s);\n free(Lambda_s);\n\n /******************** OUTPUT ***********************/\n if (Data->mode == OUTPUT) {\n for (m = 0; m < nmonths; m++)\n V[m][0] = m;\n\n // expected number of infected sheep in month m\n for (m = 0; m < nmonths-1; m++)\n V[m][1] = num_infected[m];\n V[nmonths-1][1] = V[nmonths-2][1];\n\n // expected number of infectious sheep in month m\n for (m = 0; m < nmonths-1; m++)\n V[m][2] = num_infectious[m];\n V[nmonths-1][2] = V[nmonths-2][2];\n\n // expected number of seroconverted sheep in month m\n // for (m = 0; m < nmonths-1; m++)\n // V[m][5] = num_seroconverted[m];\n // V[nmonths-1][5] = V[nmonths-2][5];\n\n // expected number of seroconversions by the end of each month m\n // (which is the start of month m+1)\n // done this way because earlier observed seroconversions are recorded at start of month\n V[0][4] = 0;\n for (j = NUMBER_DONORS; j < NUMBER_SHEEP; j++)\n if (use_sheep[j] && negatives[j] > ind)\n for (m = sheep_intro_month[j]; m < sheep_last_month[j]; m++)\n V[m+1][4] += p_seropos[m][V0+sheep_var[j]];\n\n // cumulative expected number of seroconversions by end of month m\n // (which is the start of month m+1)\n V[0][3] = 0;\n for (m = 0; m ind) {\n for (m = sheep_intro_month[j]; m < sheep_last_month[j]; m++)\n if (4-tau <= (m+4)%12 && (m+4)%12 <= 3)\n Einf_housed[m] += (1.-exp(-pars.lambda[m]))*u(sheep_intro_month[j], m , pars.Lambda);\n else\n Einf_field[m] += (1.-exp(-pars.lambda[m]))*u(sheep_intro_month[j], m, pars.Lambda);\n }\n for (m = 0; m < nmonths; m++) \n V[m][10] = Einf_field[m]+Einf_housed[m];\n\n for (m = 1; m < nmonths; m++) {\n Einf_field[m] += Einf_field[m-1];\n Einf_housed[m] += Einf_housed[m-1];\n }\n for (m = 0; m < nmonths; m++) {\n V[m][6] = Einf_field[m];\n V[m][7] = Einf_housed[m];\n V[m][9] = V[m][6]+V[m][7];\n }\n free(Einf_field);\n free(Einf_housed);\n }\n\n free(L_cdf);\n // free(S_cdf);\n free(num_infected);\n free(num_infectious);\n // free(num_seroconverted);\n free(pars.lambda);\n free(pars.Lambda);\n free(pars.b);\n free(pars.B);\n free(pars.W4[0]); \n free(pars.W4);\n free(pars.W2);\n return SUCCESS;\n}\n\ndouble P_pos(int j, int s1, int s2, double **V)\n{\n int m;\n double sum = 0;\n for (m = s1; m < s2; m++)\n sum += V[m][V0+sheep_var[j]];\n return sum;\n}\n\ndouble logLikelihood(const uint trt, const uint ind, const double *p, double **V, const TimePoints *Data)\n{\n int j, pos_idx;\n double lnL = 0;\n\n for (j = NUMBER_DONORS; j < NUMBER_SHEEP; j++)\n if (use_sheep[j] && negatives[j] > ind) {\n pos_idx = sheep_pos_index[j];\n if (pos_idx > 0)\n // ewe is first seropositive at start of month m, therefore it seroconverted\n // sometime in the months from the last test to the month prior to seroconverting\n lnL += log(P_pos(j, lrint(Data->t[pos_idx-1][0]), sheep_pos_month[j], V));\n else\n // ewe never seroconverted\n lnL += log(1. - P_pos(j, sheep_intro_month[j], sheep_last_test_month[j], V));\n }\n return lnL;\n}\n\nvoid OutputModel(int trt, int ind, double *Output, double *V)\n{\n int i;\n for (i = 1; i < V0+INTRO_MONTHS+1; i++)\n Output[i] = V[i];\n}\n\nvoid OutputData(int trt, int ind, double *Output, double *Var, double *Data, uint *value, int index)\n{\n Output[3] = Data[47];\n Output[4] = Data[48];\n Output[5] = Data[49];\n // remove dam to lamb infection from data to match model output\n if (lrint(Data[0]) == 3)\n Output[4] = 0;\n if (lrint(Data[0]) >= 3)\n Output[3] -= 1;\n}\n\nint f0(int trt, int ind, double *x, double *y, double *p, TimePoints *TP)\n{\n // R0 2 month housed\n int i, n = 2;\n if (x == NULL) return n;\n for (i = 0; i < n; i++) {\n x[i] = 100*i+1;\n y[i] = R0(x[i], 2., 0.1, 5, p);\n }\n return n;\n}\n\nint f1(int trt, int ind, double *x, double *y, double *p, TimePoints *TP)\n{\n // R0 0 months housed\n int i, n = 2;\n if (x == NULL) return n;\n for (i = 0; i < n; i++) {\n x[i] = 100*i+1;\n y[i] = R0(x[i], 0., 0.1, 5, p);\n }\n return n;\n}\n\nint f2(int trt, int ind, double *x, double *y, double *p, TimePoints *TP)\n{\n // R0 for 25 sheep housed for different durations\n int i, n = 14;\n if (x == NULL) return n;\n for (i = 0; i < n; i++) {\n x[i] = i;\n y[i] = R0(25., x[i]*12./365., 0.1, 5, p);\n }\n return n;\n}\n\nint f3(int trt, int ind, double *x, double *y, double *p, TimePoints *TP) \n{\n // CDF of normal seroconversion period\n int i, n = 1000;\n if (x == NULL) return n;\n double S_a = p[2];\n double S_k1 = p[3];\n\n for (i = 0; i < n; i++) {\n x[i] = (double)i/20.;\n // y[i] = gsl_ran_gamma_pdf(x[i], a, 1./b);\n y[i] = gsl_cdf_gamma_P(x[i], S_a, S_k1);\n }\n return n;\n}\n\nvoid function_list(functions_t *F)\n{\n F->n_func = 3;\n F->function_list = (function_ptr*) malloc(F->n_func*sizeof(function_ptr));\n F->function_list[0] = f0;\n F->function_list[1] = f1;\n F->function_list[2] = f2;\n // F->function_list[3] = f3;\n}\n\ndouble u(int m0, int m, double *Lambda)\n{\n // The probability a sheep is uninfected at the start of month m \n // given it was introduced into the flock in month m0\n if (m == m0)\n return 1;\n else\n return exp(-Lambda[m]+Lambda[m0]);\n}\n\ndouble lngseries(double a, double x, int *ierr)\n{\n double giant = HUGE_VAL/1000., eps = 1e-15;\n double t = 1./a, v = t;\n double p, q, lnigam;\n int k = 0;\n *ierr = 0;\n\n while ((fabs(t/v) > eps) && *ierr == 0) {\n p = (a+k)/(a+k+1);\n q = k+1;\n t *= -x*p/q;\n v += t;\n k += 1;\n if (t > giant)\n *ierr = 1;\n }\n if (*ierr == 0)\n if (lngamma(a) < log(giant))\n lnigam = log(v)-lngamma(a);\n else {\n lnigam = 0;\n *ierr = 1;\n }\n else {\n lnigam = 0;\n *ierr = 1;\n }\n return lnigam;\n}\n\ndouble lngexpan(double a, double x, int *ierr)\n{\n double giant = HUGE_VAL/1000., eps = 1e-15;\n double t = 1, v = t;\n double p, lnigam;\n int k = 0;\n *ierr = 0;\n\n if (x > log(giant)) {\n *ierr = 1;\n return 0;\n }\n while ((fabs(t/v) > eps) && *ierr == 0) {\n p = 1-a+k;\n t *= p/x;\n v += t;\n k += 1;\n if (t > giant)\n *ierr = 1;\n }\n if (*ierr == 0)\n if (lngamma(a) < log(giant))\n lnigam = log(v)+x-log(x)-lngamma(a);\n else {\n lnigam = 0;\n *ierr = 1;\n }\n else {\n lnigam = 0;\n *ierr = 1;\n }\n return lnigam;\n}\n\ndouble ln_inc_gamma_star(double a, double z)\n{\n int ierr;\n double lnigam;\n\n if (z < -50) {\n lnigam = lngexpan(a, -z, &ierr);\n if (ierr != 0)\n printf(\"error1\\n\");\n } \n else {\n lnigam = lngseries(a, z, &ierr);\n if (ierr != 0)\n printf(\"error2\\n\");\n }\n return lnigam;\n}\n\ndouble w(int n, int m, int t, int s, parameters_t *p)\n{\n double a = p->a;\n double l = p->lambda[n];\n double b = p->b[n];\n double r = (b-l)/b;\n double Z, z, v;\n\n if (m-n <= 1 && t == m && s == m)\n return 0;\n\n Z = p->B[m] - p->B[n] + b*(n-t) + p->b[m]*(s-m);\n if (Z == 0)\n return 0;\n\n z = r*Z;\n if (z <= 0)\n v = exp(a*log(Z) - l*Z/b + ln_inc_gamma_star(a, z));\n else\n v = exp(-a*log(r) - l*Z/b + log(P_inc_gamma(a, z)));\n\n return exp(-l*(t-n))*(v - P_inc_gamma(a, Z));\n}\n\ndouble Prob_seroconvert(int m0, int m, parameters_t *p)\n{\n int n;\n double P_m = 0;\n\n for (n = m0; n < m; n++)\n P_m += u(m0, n, p->Lambda)*p->W4[n][m];\n P_m -= u(m0, m, p->Lambda)*p->W2[m];\n\n return min(max(0, P_m), 1);\n}\n\nvoid Residual(int trt, int ind, double *R, double *V, double *p, double *Data, uint *value) \n{\n R[3] = V[3]-Data[47];\n R[4] = V[4]-Data[48];\n}\n\nvoid DerivedParameters(int trt, int ind, int nmonths, double *p, double **V, TimePoints *Data) \n{\n // int i, j, m;\n // double pinf;\n double beta_field = p[0];\n double beta_housed = p[1];\n double S_a = p[2];\n double S_b1 = S_a/p[3];\n double S_b2 = S_a/p[3];\n // double L_mu = p[5];\n // double L_sd = p[6];\n // double *num_infectious = doublevector(nmonths);\n // double *Lambda = doublevector(nmonths);\n // double *lambda = doublevector(nmonths);\n // double *B = doublevector(nmonths);\n // double *b = doublevector(nmonths);\n // double *L_cdf = doublevector(nmonths);\n\n p[10] = beta_housed/beta_field;\n p[16] = P_inv_gamma(0.5, S_a, 1./S_b1);\n p[17] = P_inv_gamma(0.5, S_a, 1./S_b2);\n p[18] = P_inv_gamma(0.95, S_a, 1./S_b1);\n p[19] = P_inv_gamma(0.95, S_a, 1./S_b2);\n return;\n\n // p[6] = gsl_cdf_exponential_Pinv(0.5, mu);\n // p[22] = gsl_cdf_exponential_Pinv(0.5, mu2);\n // p[15] = gsl_cdf_exponential_Pinv(0.025, mu);\n // p[16] = gsl_cdf_exponential_Pinv(0.975, mu);\n // p[20] = 6./16.*(1.-exp(-(0.75*beta_field)*(fmax(0, 4*12-L_mu))));\n // p[23] = 6./16.*(1.-exp(-(0.25*beta_housed)*(fmax(0, 4*12-L_mu))));\n\n // for (m = 0; m < nmonths; m++)\n // L_cdf[m] = (m < L_mu? 0: 1);\n\n // // calculate expected number of infectious ewes and force of infection, lambda\n // // the two donor sheep are infectious at start of experiment\n // for (j = 0; j < 2; j++)\n // for (m = 0; m < sheep_last_month[j]; m++)\n // num_infectious[m]++;\n // // ewe 44 - infected by dam\n // for (m = sheep_intro_month[44]; m < sheep_last_month[44]; m++)\n // num_infectious[m] += L_cdf[m-sheep_intro_month[44]];\n\n // for (m = 0; m < nmonths; m++) {\n // // calculate force of infection\n // if ((m+3)%12 < 3)\n // // transmission rate for housed ewes (in winter Jan-Mar)\n // lambda[m] = num_infectious[m]*beta_housed;\n // else\n // // field transmission rate\n // lambda[m] = num_infectious[m]*beta_field;\n\n // // cumulative lambda for prob of uninfected\n // if (m > 1)\n // Lambda[m] = Lambda[m-1]+lambda[m-1];\n\n // for (j = NUMBER_DONORS; j < NUMBER_SHEEP; j++)\n // if (use_sheep[j] && sheep_intro_month[j] <= m && m < sheep_last_month[j]) {\n // pinf = (1.-exp(-lambda[m]))*u(sheep_intro_month[j], m, Lambda);\n // for (i = m; i < sheep_last_month[j]; i++)\n // num_infectious[i] += pinf*L_cdf[i-m];\n // }\n // }\n\n // p[12] = 0;\n // p[13] = 0;\n // for (j = NUMBER_DONORS; j < NUMBER_SHEEP; j++)\n // if (use_sheep[j]) {\n // for (m = sheep_intro_month[j]; m < sheep_last_month[j]; m++)\n // if ((m+3)%12 < 3)\n // p[13] += (1.-exp(-lambda[m]))*u(sheep_intro_month[j], m, Lambda);\n // else\n // p[12] += (1.-exp(-lambda[m]))*u(sheep_intro_month[j], m, Lambda);\n // }\n // p[14] = p[12]+p[13];\n \n // free(lambda);\n // free(Lambda);\n // free(B);\n // free(b);\n // free(num_infectious);\n // free(L_cdf);\n}\n\nvoid WAIC(int trt, int ind, double **lnL, double **V, double *p, const TimePoints *Data) {}\nvoid PredictData(int trt, int ind, double *Output, double *V, double *p, gsl_rng *stream) {}\nvoid SimulateData(int trt, int ind, double *Output, double *V, double *p, double *Data, uint *value, gsl_rng *stream) {}\ndouble timestep(void) {return 1;}\nvoid GlobalParameters() {}\ndouble UserPDF(double x) {return 0;}\nvoid HyperParameters(Treatments T, Hyperparameters *H) {}\nvoid SaturatedModel(int trt, int ind, double **V, double *p, const TimePoints *Data) {}\n\n", "meta": {"hexsha": "307e9a825775ac076ece3327506799cd627d9639", "size": 19672, "ext": "c", "lang": "C", "max_stars_repo_path": "Houwers/model136.c", "max_stars_repo_name": "nicksavill/maedi-visna-epidemiology", "max_stars_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Houwers/model136.c", "max_issues_repo_name": "nicksavill/maedi-visna-epidemiology", "max_issues_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Houwers/model136.c", "max_forks_repo_name": "nicksavill/maedi-visna-epidemiology", "max_forks_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4049459042, "max_line_length": 120, "alphanum_fraction": 0.5844347296, "num_tokens": 6894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4382624122449829}} {"text": "#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"ccl.h\"\n\n/*\n * We use the remapping procedure in https://arxiv.org/pdf/1601.07230.pdf\n * to map w0-wa models onto wa == 0 models.\n * The functions below implement this procedure.\n*/\n\n// I snuck a private function from background.c into here. :P\n// The default routines create a full spline but we just need one value.\n// This may seem like over optimizing, but in testing initializing halofit\n// is an order of magnitude or more slower if we don't do this.\nvoid compute_chi(double a, ccl_cosmology *cosmo, double * chi, int * stat);\n\nstatic double zdrag_eh(ccl_parameters *params) {\n // eqn 4 of Eisenstein & Hu 1998\n double OMh2 = (params->Omega_c + params->Omega_b) * params->h * params->h;\n double OBh2 = params->Omega_b * params->h * params->h;\n double b1 = 0.313 * pow(OMh2, -0.419) * (1 + 0.607*pow(OMh2, 0.674));\n double b2 = 0.238 * pow(OMh2, 0.223);\n return 1291 * pow(OMh2, 0.251) * (1 + b1*pow(OBh2, b2)) / (1 + 0.659*pow(OMh2, 0.828));\n}\n\nstruct hf_model_match_data {\n double chi_drag;\n double a;\n ccl_cosmology *cosmo;\n int *status;\n};\n\nstatic ccl_cosmology *create_w0eff_cosmo(double w0eff, ccl_cosmology *cosmo, int *status) {\n // create a cosmology with the same parameters as the input except w0-wa. Instead\n // the cosmology is created with w0 = w0eff.\n ccl_parameters params_w0eff;\n double norm_pk;\n double mnu[3];\n int i;\n\n for(i=0; i<3; ++i)\n mnu[i] = 0;\n for(i=0; iparams.N_nu_mass; ++i)\n mnu[i] = cosmo->params.m_nu[i];\n\n if (isnan(cosmo->params.A_s))\n norm_pk = cosmo->params.sigma8;\n else\n norm_pk = cosmo->params.A_s;\n\n params_w0eff = ccl_parameters_create(\n cosmo->params.Omega_c, cosmo->params.Omega_b, cosmo->params.Omega_k,\n cosmo->params.Neff, mnu, cosmo->params.N_nu_mass,\n w0eff, 0, cosmo->params.h, norm_pk,\n cosmo->params.n_s, cosmo->params.bcm_log10Mc, cosmo->params.bcm_etab,\n cosmo->params.bcm_ks, cosmo->params.mu_0, cosmo->params.sigma_0, \n cosmo->params.c1_mg, cosmo->params.c2_mg, cosmo->params.lambda_mg, \n cosmo->params.nz_mgrowth,\n cosmo->params.z_mgrowth, cosmo->params.df_mgrowth, status);\n\n if(*status != 0)\n return NULL;\n\n return ccl_cosmology_create(params_w0eff, cosmo->config);\n}\n\nstatic double w0eff_func(double w0eff, void *p) {\n // function used to compare the distance to the CMB in a test cosmology to\n // to the value in the original cosmology\n // returns chi_eff - chi\n struct hf_model_match_data *hfd = (struct hf_model_match_data*)p;\n ccl_cosmology *cosmo_w0eff = NULL;\n double chi_drag_w0eff, tmp, zdrag_w0eff;\n\n // make the equivalent cosmology\n cosmo_w0eff = create_w0eff_cosmo(w0eff, hfd->cosmo, hfd->status);\n if (cosmo_w0eff == NULL) {\n *(hfd->status) = CCL_ERROR_MEMORY;\n return NAN;\n }\n\n // get the comoving distance to zdrag\n zdrag_w0eff = zdrag_eh(&(cosmo_w0eff->params));\n compute_chi(1.0 / (1.0 + zdrag_w0eff), cosmo_w0eff, &tmp, hfd->status);\n chi_drag_w0eff = tmp;\n compute_chi(hfd->a, cosmo_w0eff, &tmp, hfd->status);\n chi_drag_w0eff -= tmp;\n if (*(hfd->status) != 0) {\n return NAN;\n }\n\n ccl_parameters_free(&(cosmo_w0eff->params));\n ccl_cosmology_free(cosmo_w0eff);\n return chi_drag_w0eff - hfd->chi_drag;\n}\n\nstatic double get_w0eff(double a, struct hf_model_match_data data) {\n // For a given input w0-wa cosmology, this function solves for the value of\n // w0eff such that the comoving distance from a to the CMB in a cosmology\n // with the same parameters, but with w0, wa = w0eff, 0, is the same as the\n // original cosmology.\n double w0eff, w0eff_low = -2.0, w0eff_high = -0.35;\n double flow, fhigh;\n int itr, max_itr = 1000, gsl_status;\n const gsl_root_fsolver_type *T;\n gsl_root_fsolver *s;\n gsl_function F;\n\n data.a = a;\n data.chi_drag = ccl_comoving_radial_distance(data.cosmo, 1.0 / (1.0 + zdrag_eh(&(data.cosmo->params))), data.status);\n data.chi_drag -= ccl_comoving_radial_distance(data.cosmo, a, data.status);\n if(*(data.status) != 0) {\n ccl_cosmology_set_status_message(\n data.cosmo,\n \"ccl_halofit.c: get_w0eff(): \"\n \"could not compute chi_drag for cosmology\\n\");\n return NAN;\n }\n\n F.function = &w0eff_func;\n F.params = &data;\n\n // we have to bound the root, otherwise return -1\n // we will fiil in any -1's in the calling routine\n flow = w0eff_func(w0eff_low, &data);\n fhigh = w0eff_func(w0eff_high, &data);\n if (flow * fhigh > 0) {\n return -1;\n }\n\n T = gsl_root_fsolver_brent;\n s = gsl_root_fsolver_alloc(T);\n if (s == NULL) {\n *(data.status) = CCL_ERROR_MEMORY;\n }\n else {\n gsl_root_fsolver_set(s, &F, w0eff_low, w0eff_high);\n\n itr = 0;\n do {\n itr++;\n gsl_status = gsl_root_fsolver_iterate(s);\n if (gsl_status == GSL_EBADFUNC)\n break;\n\n w0eff = gsl_root_fsolver_root(s);\n w0eff_low = gsl_root_fsolver_x_lower(s);\n w0eff_high = gsl_root_fsolver_x_upper(s);\n\n gsl_status = gsl_root_test_interval(\n w0eff_low, w0eff_high,\n 1e-6,\n 1e-6);\n } while (gsl_status == GSL_CONTINUE && itr < max_itr);\n\n gsl_root_fsolver_free(s);\n\n if (gsl_status != GSL_SUCCESS || itr >= max_itr) {\n ccl_raise_gsl_warning(\n gsl_status, \"ccl_halofit.c: get_w0eff(): error in root finding for the halofit matching cosmology\\n\");\n *(data.status) |= gsl_status;\n }\n }\n\n return w0eff;\n}\n\n/* helper data and functions for integrals\n\n the integral is\n\n \\int dlnk \\Delta^{2}(k) \\exp(-k^{2}R^{2})\n\n for halofit, we also need the first and second derivatives of this\n integral\n*/\nstruct hf_int_data {\n double r;\n double r2;\n double a;\n ccl_cosmology *cosmo;\n ccl_f2d_t *plin;\n int *status;\n gsl_integration_cquad_workspace *workspace;\n};\n\nstatic double gauss_norm_int_func(double lnk, void *p) {\n struct hf_int_data *hfd = (struct hf_int_data*)p;\n double k = exp(lnk);\n double k2 = k*k;\n\n return (\n ccl_f2d_t_eval(hfd->plin, lnk, hfd->a, hfd->cosmo, hfd->status) *\n k*k2/2.0/M_PI/M_PI *\n exp(-k2 * (hfd->r2)));\n}\n\nstatic double onederiv_gauss_norm_int_func(double lnk, void *p) {\n struct hf_int_data *hfd = (struct hf_int_data*)p;\n double k = exp(lnk);\n double k2 = k*k;\n\n return (\n ccl_f2d_t_eval(hfd->plin, lnk, hfd->a, hfd->cosmo, hfd->status) *\n k*k2/2.0/M_PI/M_PI *\n exp(-k2 * (hfd->r2)) *\n (-k2 * 2.0 * (hfd->r)));\n}\n\nstatic double twoderiv_gauss_norm_int_func(double lnk, void *p) {\n struct hf_int_data *hfd = (struct hf_int_data*)p;\n double k = exp(lnk);\n double k2 = k*k;\n\n return (\n ccl_f2d_t_eval(hfd->plin, lnk, hfd->a, hfd->cosmo, hfd->status) *\n k*k2/2.0/M_PI/M_PI *\n exp(-k2 * (hfd->r2)) *\n (-2.0*k2 + 4.0*k2*k2 * (hfd->r2)));\n}\n\n// function whose root is \\sigma^2{rsigma, a} = 1\nstatic double rsigma_func(double rsigma, void *p) {\n struct hf_int_data *hfd = (struct hf_int_data*)p;\n double result, lnkmin, lnkmax;\n gsl_function F;\n int gsl_status;\n\n lnkmin = hfd->plin->lkmin;\n lnkmax = hfd->plin->lkmax;\n hfd->r = rsigma;\n hfd->r2 = rsigma * rsigma;\n F.function = &gauss_norm_int_func;\n F.params = (void *)hfd;\n gsl_status = gsl_integration_cquad(\n &F, lnkmin, lnkmax,\n 0.0, hfd->cosmo->gsl_params.INTEGRATION_SIGMAR_EPSREL,\n hfd->workspace, &result, NULL, NULL);\n\n if (gsl_status != GSL_SUCCESS) {\n ccl_raise_gsl_warning(\n gsl_status,\n \"ccl_halofit.c: rsigma_func(): error in integration \"\n \"for finding the halofit non-linear scale\\n\");\n *(hfd->status) |= gsl_status;\n }\n\n return result - 1.0;\n}\n\nstatic double get_rsigma(double a, struct hf_int_data data) {\n double rsigma, rlow = 1e-2, rhigh = 1e2;\n double flow, fhigh;\n int itr, max_itr = 1000, gsl_status;\n const gsl_root_fsolver_type *T;\n gsl_root_fsolver *s;\n gsl_function F;\n\n data.a = a;\n F.function = &rsigma_func;\n F.params = &data;\n\n // we have to bound the root, otherwise return -1\n // we will fiil in any -1's in the calling routine\n flow = rsigma_func(rlow, &data);\n fhigh = rsigma_func(rhigh, &data);\n if (flow * fhigh > 0) {\n return -1;\n }\n\n T = gsl_root_fsolver_brent;\n s = gsl_root_fsolver_alloc(T);\n if (s == NULL) {\n *(data.status) = CCL_ERROR_MEMORY;\n }\n else {\n gsl_root_fsolver_set(s, &F, rlow, rhigh);\n\n itr = 0;\n do {\n itr++;\n gsl_status = gsl_root_fsolver_iterate(s);\n if (gsl_status == GSL_EBADFUNC)\n break;\n\n rsigma = gsl_root_fsolver_root(s);\n rlow = gsl_root_fsolver_x_lower(s);\n rhigh = gsl_root_fsolver_x_upper(s);\n\n gsl_status = gsl_root_test_interval(\n rlow, rhigh,\n data.cosmo->gsl_params.INTEGRATION_SIGMAR_EPSREL,\n data.cosmo->gsl_params.INTEGRATION_SIGMAR_EPSREL);\n } while (gsl_status == GSL_CONTINUE && itr < max_itr);\n\n gsl_root_fsolver_free(s);\n\n if (gsl_status != GSL_SUCCESS || itr >= max_itr) {\n ccl_raise_gsl_warning(\n gsl_status, \"ccl_halofit.c: get_rsigma(): error in root finding for the halofit non-linear scale\\n\");\n *(data.status) |= gsl_status;\n }\n }\n\n return rsigma;\n}\n\n/*\n * Allocate a new struct for storing halofit data\n * @param cosmo Cosmological data\n * @param int, status of computations\n */\nhalofit_struct* ccl_halofit_struct_new(ccl_cosmology *cosmo,\n ccl_f2d_t *plin, int *status) {\n size_t n_a;\n int i, gsl_status;\n double lnkmin, lnkmax;\n double *a_vec = NULL;\n double *vals = NULL;\n double *vals_om = NULL;\n double *vals_de = NULL;\n halofit_struct *hf = NULL;\n struct hf_int_data data;\n gsl_function F;\n gsl_integration_cquad_workspace *workspace = NULL;\n double result;\n double sigma2, rsigma, dsigma2drsigma;\n struct hf_model_match_data data_w0eff;\n ccl_cosmology *cosmo_w0eff = NULL;\n\n // compute spline point locations and integral bounds\n // note that the spline point locations in `a` determine a radius by\n // solving sigma2(R, a) = 1\n // it is this radius that is needed for the subsequent splines of\n // the derivatives.\n lnkmin = plin->lkmin;\n lnkmax = plin->lkmax;\n if(plin->fa != NULL) {\n n_a = plin->fa->size;\n a_vec = plin->fa->x;\n }\n else if(plin->fka != NULL) {\n n_a = plin->fka->interp_object.ysize;\n a_vec = plin->fka->yarr;\n }\n else {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"input pk2d has no splines.\\n\");\n }\n\n if(*status == 0) {\n ///////////////////////////////////////////////////////\n // memory allocation\n hf = (halofit_struct*)malloc(sizeof(halofit_struct));\n if (hf == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for halofit_struct\\n\");\n } else {\n hf->rsigma = NULL;\n hf->sigma2 = NULL;\n hf->n_eff = NULL;\n hf->C = NULL;\n hf->weff = NULL;\n hf->omeff = NULL;\n hf->deeff = NULL;\n }\n }\n\n if (*status == 0) {\n workspace = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n if (workspace == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for cquad workspace\\n\");\n }\n }\n\n if (*status == 0) {\n vals = (double*)malloc(sizeof(double) * n_a);\n if (vals == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for results vector\\n\");\n }\n }\n\n if (*status == 0) {\n vals_om = (double*)malloc(sizeof(double) * n_a);\n if (vals_om == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for OmegaM results vector\\n\");\n }\n }\n\n if (*status == 0) {\n vals_de = (double*)malloc(sizeof(double) * n_a);\n if (vals_de == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for OmegaDE results vector\\n\");\n }\n }\n\n ////////////////////////////////////////////////////////\n // if wa != 0, then we need to find an equivalent\n // cosmology with wa = 0\n data_w0eff.cosmo = cosmo;\n data_w0eff.status = status;\n\n if (*status == 0) {\n if (cosmo->params.wa != 0) {\n for(i=0; iparams));\n ccl_cosmology_free(cosmo_w0eff);\n cosmo_w0eff = NULL;\n\n if (*status != 0) {\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"could not compute OmegaM and OmegaDE for cosmology\\n\");\n break;\n }\n }\n } else {\n for(i=0; iparams.w0;\n vals_om[i] = ccl_omega_x(cosmo, a_vec[i], ccl_species_m_label, status) +\n ccl_omega_x(cosmo, a_vec[i], ccl_species_nu_label, status);\n vals_de[i] = ccl_omega_x(cosmo, a_vec[i], ccl_species_l_label, status);\n if (*status != 0) {\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"could not compute OmegaM and OmegaDE for cosmology\\n\");\n break;\n }\n }\n }\n }\n\n // spline the weff values\n if (*status == 0) {\n hf->weff = gsl_spline_alloc(gsl_interp_akima, n_a);\n if (hf->weff == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for weff spline\\n\");\n }\n }\n\n if (*status == 0) {\n gsl_status = gsl_spline_init(hf->weff, a_vec, vals, n_a);\n if (gsl_status != GSL_SUCCESS) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): could not build weff spline\\n\");\n }\n }\n\n // spline the omeff values\n if (*status == 0) {\n hf->omeff = gsl_spline_alloc(gsl_interp_akima, n_a);\n if (hf->omeff == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for omeff spline\\n\");\n }\n }\n\n if (*status == 0) {\n gsl_status = gsl_spline_init(hf->omeff, a_vec, vals_om, n_a);\n if (gsl_status != GSL_SUCCESS) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): could not build omeff spline\\n\");\n }\n }\n\n // spline the deeff values\n if (*status == 0) {\n hf->deeff = gsl_spline_alloc(gsl_interp_akima, n_a);\n if (hf->deeff == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for deeff spline\\n\");\n }\n }\n\n if (*status == 0) {\n gsl_status = gsl_spline_init(hf->deeff, a_vec, vals_de, n_a);\n if (gsl_status != GSL_SUCCESS) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): could not build deeff spline\\n\");\n }\n }\n\n ///////////////////////////////////////////////////////\n // find the nonlinear scale at each scale factor\n if (*status == 0) {\n // setup for integrations\n data.status = status;\n data.cosmo = cosmo;\n data.plin = plin;\n data.workspace = workspace;\n\n for (i=0; irsigma = gsl_spline_alloc(gsl_interp_akima, n_a);\n if (hf->rsigma == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for Rsigma spline\\n\");\n }\n }\n\n if (*status == 0) {\n gsl_status = gsl_spline_init(hf->rsigma, a_vec, vals, n_a);\n if (gsl_status != GSL_SUCCESS) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): could not build Rsigma spline\\n\");\n }\n }\n\n ///////////////////////////////////////////////////////\n // now compute sigma2(R) at each spline point\n // and spline that\n // this should be close to 1 OFC, but better to use the exact value\n if (*status == 0) {\n for (i=0; irsigma, a_vec[i], NULL), &data) + 1;\n if (*status != 0) {\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): could not eval \"\n \"points for sigma2(R) spline\\n\");\n break;\n }\n }\n }\n\n if (*status == 0) {\n hf->sigma2 = gsl_spline_alloc(gsl_interp_akima, n_a);\n if (hf->sigma2 == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for sigma2(R) spline\\n\");\n }\n }\n\n if (*status == 0) {\n gsl_status = gsl_spline_init(hf->sigma2, a_vec, vals, n_a);\n if (gsl_status != GSL_SUCCESS) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): could not build sigma2(R) spline\\n\");\n }\n }\n\n ///////////////////////////////////////////////////////\n // now compute the effective spectral index\n if (*status == 0) {\n F.function = &onederiv_gauss_norm_int_func;\n F.params = &data;\n\n for (i=0; irsigma, a_vec[i], NULL);\n sigma2 = gsl_spline_eval(hf->sigma2, a_vec[i], NULL);\n\n data.a = a_vec[i];\n data.r = rsigma;\n data.r2 = rsigma * rsigma;\n\n gsl_status = gsl_integration_cquad(\n &F,\n lnkmin, lnkmax,\n 0.0, cosmo->gsl_params.INTEGRATION_SIGMAR_EPSREL,\n workspace, &result, NULL, NULL);\n\n if (gsl_status != GSL_SUCCESS) {\n *status = CCL_ERROR_INTEG;\n ccl_raise_gsl_warning(\n gsl_status,\n \"ccl_power.c: ccl_halofit_struct_new(): could not eval \"\n \"points for n_eff spline\\n\");\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): could not eval \"\n \"points for n_eff spline\\n\");\n break;\n }\n\n // this is n_eff but expressed in terms of linear derivs\n // see eqn A5 of Takahashi et al.\n vals[i] = -rsigma / sigma2 * result - 3.0;\n }\n }\n\n if (*status == 0) {\n hf->n_eff = gsl_spline_alloc(gsl_interp_akima, n_a);\n if (hf->n_eff == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for n_eff spline\\n\");\n }\n }\n\n if (*status == 0) {\n gsl_status = gsl_spline_init(hf->n_eff, a_vec, vals, n_a);\n if (gsl_status != GSL_SUCCESS) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): could not build n_eff spline\\n\");\n }\n }\n\n ///////////////////////////////////////////////////////\n // now compute the curvature C\n if (*status == 0) {\n F.function = &twoderiv_gauss_norm_int_func;\n F.params = &data;\n\n for (i=0; irsigma, a_vec[i], NULL);\n sigma2 = gsl_spline_eval(hf->sigma2, a_vec[i], NULL);\n\n // we need to solve for the deriv we need from n_eff here\n dsigma2drsigma = gsl_spline_eval(hf->n_eff, a_vec[i], NULL);\n dsigma2drsigma = (dsigma2drsigma + 3.0) / (-rsigma / sigma2);\n\n data.a = a_vec[i];\n data.r = rsigma;\n data.r2 = rsigma * rsigma;\n\n gsl_status = gsl_integration_cquad(\n &F,\n lnkmin, lnkmax,\n 0.0, cosmo->gsl_params.INTEGRATION_SIGMAR_EPSREL,\n workspace, &result, NULL, NULL);\n\n if (gsl_status != GSL_SUCCESS) {\n *status = CCL_ERROR_INTEG;\n ccl_raise_gsl_warning(\n gsl_status,\n \"ccl_power.c: ccl_halofit_struct_new(): could not eval \"\n \"points for C spline\\n\");\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): could not eval \"\n \"points for C spline\\n\");\n break;\n }\n\n // this is C but expressed in terms of linear derivs\n // see eqn A5 of Takahashi et al.\n vals[i] = (\n -1.0 * (\n result * rsigma * rsigma / sigma2 +\n dsigma2drsigma * rsigma / sigma2 -\n dsigma2drsigma * dsigma2drsigma * rsigma * rsigma / sigma2 / sigma2));\n }\n }\n\n if (*status == 0) {\n hf->C = gsl_spline_alloc(gsl_interp_akima, n_a);\n if (hf->C == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): \"\n \"memory could not be allocated for C spline\\n\");\n }\n }\n\n if (*status == 0) {\n gsl_status = gsl_spline_init(hf->C, a_vec, vals, n_a);\n if (gsl_status != GSL_SUCCESS) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_halofit.c: ccl_halofit_struct_new(): could not build C spline\\n\");\n }\n }\n\n // free stuff on the way out\n // if the status is non-zero, then we should free any data already\n // accumulated\n if (*status != 0) {\n ccl_halofit_struct_free(hf);\n hf = NULL;\n }\n gsl_integration_cquad_workspace_free(workspace);\n free(vals);\n free(vals_om);\n free(vals_de);\n if (cosmo_w0eff != NULL) {\n ccl_parameters_free(&(cosmo_w0eff->params));\n ccl_cosmology_free(cosmo_w0eff);\n }\n\n return hf;\n}\n\n/*\n * Free a halofit struct\n * @param hf, pointer to halofit struct to free\n */\nvoid ccl_halofit_struct_free(halofit_struct *hf) {\n if (hf != NULL) {\n if (hf->rsigma != NULL)\n gsl_spline_free(hf->rsigma);\n\n if (hf->sigma2 != NULL)\n gsl_spline_free(hf->sigma2);\n\n if (hf->n_eff != NULL)\n gsl_spline_free(hf->n_eff);\n\n if (hf->C != NULL)\n gsl_spline_free(hf->C);\n\n if (hf->weff != NULL)\n gsl_spline_free(hf->weff);\n\n if (hf->omeff != NULL)\n gsl_spline_free(hf->omeff);\n\n if (hf->deeff != NULL)\n gsl_spline_free(hf->deeff);\n\n free(hf);\n }\n}\n\n/**\n * Computes the halofit non-linear power spectrum\n * @param cosmo: cosmology object containing parameters\n * @param lk: natural logarithm of wavenumber in units of Mpc^{-1}\n * @param a: scale factor normalised to a=1 today\n * @param status: Status flag: 0 if there are no errors, non-zero otherwise\n * @param hf: halofit splines for evaluating the power spectrum\n * @return halofit_matter_power: halofit power spectrum, P(k), units of Mpc^{3}\n */\ndouble ccl_halofit_power(ccl_cosmology *cosmo, ccl_f2d_t *plin,\n double lk, double a, halofit_struct *hf, int *status) {\n double rsigma, neff, C;\n double ksigma, weffa, omegaMz, omegaDEwz, kh;\n double PkL, PkNL, f1, f2, f3, an, bn, cn, gamman, alphan, betan, nun, mun, y, fy;\n double DeltakL, DeltakL_tilde, DeltakQ, DeltakH, DeltakHprime, DeltakNL;\n double Qnu, fnu;\n double f1a, f2a, f3a, f1b, f2b, f3b, fb_frac;\n double neff2, neff3, neff4;\n double kh2, y2;\n double delta2_norm, om_nu;\n double k=exp(lk);\n\n // all eqns are from Takahashi et al. unless stated otherwise\n // eqns A4 - A5\n rsigma = gsl_spline_eval(hf->rsigma, a, NULL);\n neff = gsl_spline_eval(hf->n_eff, a, NULL);\n C = gsl_spline_eval(hf->C, a, NULL);\n\n weffa = cosmo->params.w0;\n omegaMz = ccl_omega_x(cosmo, a, ccl_species_m_label, status);\n omegaDEwz = ccl_omega_x(cosmo, a, ccl_species_l_label, status);\n\n // not using these to match CLASS better - might be a bug in CLASS\n // weffa = gsl_spline_eval(hf->weff, a, NULL);\n // omegaMz = gsl_spline_eval(hf->omeff, a, NULL);\n // omegaDEwz = gsl_spline_eval(hf->deeff, a, NULL);\n\n ksigma = 1.0 / rsigma;\n neff2 = neff * neff;\n neff3 = neff2 * neff;\n neff4 = neff3 * neff;\n\n delta2_norm = k*k*k/2.0/M_PI/M_PI;\n\n // compute the present day neutrino massive neutrino fraction\n // uses all neutrinos even if they are moving fast\n om_nu = cosmo->params.sum_nu_masses / 93.14 / cosmo->params.h / cosmo->params.h;\n fnu = om_nu / (cosmo->params.Omega_m);\n\n // eqns A6 - A13 of Takahashi et al.\n an = pow(\n 10.0,\n 1.5222 + 2.8553*neff + 2.3706*neff2 + 0.9903*neff3 +\n 0.2250*neff4 - 0.6038*C + 0.1749*omegaDEwz*(1.0 + weffa));\n bn = pow(10.0, -0.5642 + 0.5864*neff + 0.5716*neff2 - 1.5474*C + 0.2279*omegaDEwz*(1.0 + weffa));\n cn = pow(10.0, 0.3698 + 2.0404*neff + 0.8161*neff2 + 0.5869*C);\n gamman = 0.1971 - 0.0843*neff + 0.8460*C;\n alphan = fabs(6.0835 + 1.3373*neff - 0.1959*neff2 - 5.5274*C);\n betan = 2.0379 - 0.7354*neff + 0.3157*neff2 + 1.2490*neff3 + 0.3980*neff4 - 0.1682*C;\n mun = 0.0;\n nun = pow(10.0, 5.2105 + 3.6902*neff);\n\n // eqns C17 and C18 for Smith et al.\n if (fabs(1.0 - omegaMz) > 0.01) {\n f1a = pow(omegaMz, -0.0732);\n f2a = pow(omegaMz, -0.1423);\n f3a = pow(omegaMz, 0.0725);\n f1b = pow(omegaMz, -0.0307);\n f2b = pow(omegaMz, -0.0585);\n f3b = pow(omegaMz, 0.0743);\n fb_frac = omegaDEwz / (1.0 - omegaMz);\n f1 = fb_frac * f1b + (1.0 - fb_frac) * f1a;\n f2 = fb_frac * f2b + (1.0 - fb_frac) * f2a;\n f3 = fb_frac * f3b + (1.0 - fb_frac) * f3a;\n } else {\n f1 = 1.0;\n f2 = 1.0;\n f3 = 1.0;\n }\n\n // correction to betan from Bird et al., eqn A10\n betan += (fnu * (1.081 + 0.395*neff2));\n\n // eqns A1 - A3\n PkL = ccl_f2d_t_eval(plin, lk, a, cosmo, status);\n y = k/ksigma;\n y2 = y * y;\n fy = y/4.0 + y2/8.0;\n DeltakL = PkL * delta2_norm;\n\n // correction to DeltakL from Bird et al., eqn A9\n kh = k / cosmo->params.h;\n kh2 = kh * kh;\n DeltakL_tilde = DeltakL * (1.0 + fnu * (47.48 * kh2) / (1.0 + 1.5 * kh2));\n DeltakQ = DeltakL * pow(1.0 + DeltakL_tilde, betan) / (1.0 + alphan*DeltakL_tilde) * exp(-fy);\n\n DeltakHprime = an * pow(y, 3.0*f1) / (1.0 + bn*pow(y, f2) + pow(cn*f3*y, 3.0 - gamman));\n DeltakH = DeltakHprime / (1.0 + mun/y + nun/y2);\n\n // correction to DeltakH from Bird et al., eqn A6-A7\n Qnu = fnu * (0.977 - 18.015 * (cosmo->params.Omega_m - 0.3));\n DeltakH *= (1.0 + Qnu);\n\n DeltakNL = DeltakQ + DeltakH;\n PkNL = DeltakNL / delta2_norm;\n\n // we check the status once\n if(*status != 0)\n return NAN;\n else\n return PkNL;\n}\n", "meta": {"hexsha": "04e0103c8fa81ea05ba6333f49181b5002572318", "size": 29512, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_halofit.c", "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_issues_repo_path": "src/ccl_halofit.c", "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 703.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_forks_repo_path": "src/ccl_halofit.c", "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "avg_line_length": 30.2997946612, "max_line_length": 119, "alphanum_fraction": 0.6138519924, "num_tokens": 9636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4377722422839425}} {"text": "/******************************************************************************\n * *\n * ELECTRONS.C *\n * *\n * ELECTRON THERMODYNAMICS *\n * *\n ******************************************************************************/\n\n#include \"decs.h\"\n#include \n\n/* TODO: Encapsulate electron equation of state in EOS framework.\n * For now, I'v ebroken encapsulation but made the code\n *\t complain/break if EOS_TYPE is not EOS_TYPE_GAMMA\n *\t when ELECTRONS are active.\n *\n * The best strategy is probably to make a two-temperature\n * electron EOS one of the available EOS's.\n *\n * Until then, I'm worried that we might hit a maintainability\n * problem becasue if the implementation in ELECTRONS changes\n * the implementation in EOS_TYPE_GAMMA needs to change too.\n * ~JMM\n */\n\n#if ELECTRONS\n#if EOS == EOS_TYPE_GAMMA\nvoid heat_electrons_zone(int i, int j, int k, double Pi[NVAR], double Ps[NVAR],\n double Pf[NVAR], double Dt);\nvoid fixup_electrons_1zone(double P[NVAR]);\n\nvoid init_electrons() {\n double uel;\n\n ZSLOOP(-NG, N1 + NG - 1, -NG, NG + N2 - 1, -NG, NG + N3 - 1) {\n // Set electron internal energy to constant fraction of internal energy\n uel = fel0 * P[i][j][k][UU];\n\n // Initialize entropies\n P[i][j][k][KTOT] = (gam - 1.) * P[i][j][k][UU] * pow(P[i][j][k][RHO], -gam);\n P[i][j][k][KEL] = (game - 1.) * uel * pow(P[i][j][k][RHO], -game);\n }\n\n bound_prim(P);\n}\n\nvoid heat_electrons(\n grid_prim_type Pi, grid_prim_type Ps, grid_prim_type Pf, double Dt) {\n timer_start(TIMER_ELECTRON);\n#pragma omp parallel for collapse(3) schedule(dynamic)\n ZLOOP {\n heat_electrons_zone(i, j, k, Pi[i][j][k], Ps[i][j][k], Pf[i][j][k], Dt);\n }\n timer_stop(TIMER_ELECTRON);\n}\n\nvoid heat_electrons_zone(int i, int j, int k, double Pi[NVAR], double Ps[NVAR],\n double Pf[NVAR], double Dt) {\n double ktotharm, ktotadv, fel;\n\n // Calculated and advected entropy at final time\n ktotharm = (gam - 1.) * Pf[UU] / pow(Pf[RHO], gam);\n ktotadv = Pf[KTOT];\n\n // Electron heating fraction\n fel = get_fel(i, j, k, Ps);\n\n // Update final electron entropy according to Ressler+ 2015 Eqn. 27:\n Pf[KEL] += (game - 1.) / (gam - 1.) * pow(Ps[RHO], gam - game) * fel *\n (ktotharm - ktotadv);\n\n // Diagnostics\n struct of_geom *geom = &ggeom[i][j][CENT];\n struct of_state q;\n get_state(Ps, geom, &q);\n double uadv = ktotadv / (gam - 1.) * pow(Pf[RHO], gam);\n double Qud = q.ucon[0] * q.ucov[0] * (Pf[UU] - uadv) *\n pow(Ps[RHO] / Pf[RHO], gam) / Dt;\n Qvisc[i][j][k] = fel * Qud;\n\n // Reset total entropy\n Pf[KTOT] = ktotharm;\n}\n\ndouble get_fel(int i, int j, int k, double P[NVAR]) {\n#if BETA_HEAT == 0\n return fel0;\n#endif\n\n struct of_geom geom;\n double beta, fel, c1, Trat, Tpr, mbeta, qrat;\n double pres, bsq;\n double c2, c3, c22, c32;\n\n c1 = 0.92;\n\n Tpr = (gam - 1.) * P[UU] / P[RHO];\n double uel = 1. / (game - 1.) * P[KEL] * pow(P[RHO], game);\n double Tel = (game - 1.) * uel / P[RHO];\n if (Tel <= 0.)\n Tel = SMALL;\n if (Tpr <= 0.)\n Tpr = SMALL;\n Trat = fabs(Tpr / Tel);\n\n pres = P[RHO] * Tpr; // Proton pressure\n\n geom = *get_geometry(i, j, k, CENT);\n bsq = bsq_calc(P, &geom);\n\n beta = pres / bsq * 2.;\n if (beta > 1.e20)\n beta = 1.e20;\n mbeta = 2. - 0.2 * log10(Trat);\n\n if (Trat <= 1.) {\n c2 = 1.6 / Trat;\n c3 = 18. + 5. * log10(Trat);\n } else {\n c2 = 1.2 / Trat;\n c3 = 18.;\n }\n c22 = pow(c2, 2.);\n c32 = pow(c3, 2.);\n\n qrat = c1 * (c22 + pow(beta, mbeta)) / (c32 + pow(beta, mbeta)) *\n exp(-1. / beta) * pow(MP / ME * Trat, .5);\n fel = 1. / (1. + qrat);\n\n return fel;\n}\n\n// Modified Bessel function of second kind with safe inputs\ndouble safe_Kn(int n, double x) {\n if (x > 100.) {\n return exp(-x) * sqrt(M_PI / (2. * x));\n } else {\n return gsl_sf_bessel_Kn(n, x);\n }\n}\n\n#if RADIATION\nvoid coulomb(\n grid_prim_type Pi, grid_prim_type Ps, grid_prim_type Pf, double Dt) {\n timer_start(TIMER_ELECTRON);\n\n#pragma omp parallel for collapse(3)\n ZLOOP {\n double rho = Ps[i][j][k][RHO];\n double thetae = MP / ME * Ps[i][j][k][KEL] * pow(rho, game - 1.);\n double ue = Ps[i][j][k][KEL] * pow(rho, game) / (game - 1.);\n double up = Ps[i][j][k][UU] - ue;\n double n = rho * Ne_unit;\n double Ti = up * U_unit * (gamp - 1.) / (n * KBOL);\n double thetai = KBOL * Ti / (MP * CL * CL);\n double thetam = 1. / (1. / thetae + 1. / thetai);\n double logCoul = COULOMB_LOG;\n double Te = thetae * ME * CL * CL / KBOL;\n struct of_geom *geom;\n struct of_state q;\n\n // Sanity checks, although electron fixup routine should catch these\n if (!isnan(Te) && !isnan(Ti) && Te > 0. && Ti > 0.) {\n double Qc, term1, term2;\n\n // Get Coulomb heating rate.\n // Need to handle cases where Thetai < 1e-2, Thetae < 1e-2, and both\n // Thetae and Thetai < 1e-2 separately due to Bessel functions exploding\n double prefac =\n 3. / 2. * ME / MP * n * n * logCoul * CL * KBOL * THOMSON * (Ti - Te);\n double thetaCrit = 1.e-2;\n if (thetae < thetaCrit && thetai < thetaCrit) {\n term1 = sqrt(thetam / (M_PI * thetae * thetai / 2.));\n term2 = sqrt(thetam / (M_PI * thetae * thetai / 2.));\n } else if (thetae < thetaCrit) {\n term1 =\n exp(-1. / thetai) / safe_Kn(2, 1. / thetai) * sqrt(thetam / thetae);\n term2 =\n exp(-1. / thetai) / safe_Kn(2, 1. / thetai) * sqrt(thetam / thetae);\n } else if (thetai < thetaCrit) {\n term1 =\n exp(-1. / thetae) / safe_Kn(2, 1. / thetae) * sqrt(thetam / thetai);\n term2 =\n exp(-1. / thetae) / safe_Kn(2, 1. / thetae) * sqrt(thetam / thetai);\n } else {\n term1 = safe_Kn(1, 1. / thetam) /\n (safe_Kn(2, 1. / thetae) * safe_Kn(2, 1. / thetai));\n term2 = safe_Kn(0, 1. / thetam) /\n (safe_Kn(2, 1. / thetae) * safe_Kn(2, 1. / thetai));\n }\n term1 *= (2. * pow(thetae + thetai, 2) + 1.) / (thetae + thetai);\n term2 *= 2.;\n Qc = prefac * (term1 + term2);\n\n // Convert to code units\n Qc *= T_unit / U_unit;\n\n // Update electron internal energy\n geom = &ggeom[i][j][CENT];\n get_state(Ps[i][j][k], geom, &q);\n\n double ue_f =\n Pf[i][j][k][KEL] * pow(Pf[i][j][k][RHO], game) / (game - 1.);\n ue_f += Qc * Dt / q.ucon[0];\n\n // Record diagnostic\n Qcoul[i][j][k] = q.ucov[0] * Qc;\n\n // Update electron entropy\n Pf[i][j][k][KEL] = (game - 1.) * ue_f * pow(Pf[i][j][k][RHO], -game);\n }\n } // ZLOOP\n\n timer_stop(TIMER_ELECTRON);\n}\n\nvoid apply_rad_force_e(grid_prim_type Prh, grid_prim_type Pr,\n grid_fourvector_type radG, double Dt) {\n// Apply only to active zones for this proc -- ghost zone four-force\n// depositions already communicated over MPI\n#pragma omp parallel for collapse(3) schedule(dynamic)\n ZLOOP {\n struct of_geom *geom = &ggeom[i][j][CENT];\n struct of_state q;\n double Uel, Urho;\n double C = 0.;\n\n // Get fluid state at n + 1/2 where radiation four-force is centered\n get_state(Prh[i][j][k], geom, &q);\n\n for (int mu = 0; mu < NDIM; mu++) {\n C += -q.ucon[mu] * radG[i][j][k][mu];\n }\n\n // Get fluid state at n+1 for full update\n get_state(Pr[i][j][k], geom, &q);\n\n // Remove \\sqrt{-g} from radG\n C = C / geom->g;\n\n Urho = Pr[i][j][k][RHO] * q.ucon[0];\n Uel = Pr[i][j][k][KEL] * Urho;\n\n Uel += Dt * (C * (game - 1.) * pow(Prh[i][j][k][RHO], 1. - game));\n\n // Supercooling diagnostics\n if (Uel < 0.) {\n double U_1[NVAR], prim_2[NVAR], U_2[NVAR];\n struct of_state q_1, q_2;\n Nsuper[i][j][k]++;\n\n // (1) Record total energy density after cooling\n get_state(Pr[i][j][k], &ggeom[i][j][CENT], &q_1);\n primtoflux(Pr[i][j][k], &q_1, 0, 0, &ggeom[i][j][CENT], U_1);\n\n // (2) Calculate total energy density with zero electron energy density\n PLOOP prim_2[ip] = psupersave[i][j][k][ip];\n double ue = prim_2[KEL] * pow(prim_2[RHO], game) / (game - 1.);\n prim_2[UU] -= ue;\n get_state(prim_2, &ggeom[i][j][CENT], &q_2);\n primtoflux(prim_2, &q_2, 0, 0, &ggeom[i][j][CENT], U_2);\n\n // Subtract (2) from (1); integrated over volume, this is fake energy\n Esuper[i][j][k] += fabs((U_1[UU] - U_2[UU]) * dx[1] * dx[2] * dx[3]);\n } // Uel < 0\n\n Pr[i][j][k][KEL] = Uel / Urho;\n\n // Reset total entropy\n Pr[i][j][k][KTOT] =\n (gam - 1.) * Pr[i][j][k][UU] * pow(Pr[i][j][k][RHO], -gam);\n } // ZSLOOP\n}\n#endif // RADIATION\n\nvoid fixup_electrons(grid_prim_type P) {\n timer_start(TIMER_ELECTRON);\n#pragma omp parallel for collapse(3) schedule(dynamic)\n ZLOOP { fixup_electrons_1zone(P[i][j][k]); }\n timer_stop(TIMER_ELECTRON);\n}\n\nvoid fixup_electrons_1zone(double P[NVAR]) {\n double kelmax =\n P[KTOT] * pow(P[RHO], gam - game) / (tptemin + (gam - 1.) / (game - 1.));\n double kelmin =\n P[KTOT] * pow(P[RHO], gam - game) / (tptemax + (gam - 1.) / (game - 1.));\n\n // Replace NANs with cold electrons\n if (isnan(P[KEL]))\n P[KEL] = kelmin;\n\n // Enforce maximum Tp/Te\n P[KEL] = MY_MAX(P[KEL], kelmin);\n\n // Enforce minimum Tp/Te\n P[KEL] = MY_MIN(P[KEL], kelmax);\n}\n#endif // EOS == EOS_TYPE_GAMMA\n#endif // ELECTRONS\n", "meta": {"hexsha": "6b37ceeabce08661c16a0ed44710dc9fdefc46d9", "size": 9758, "ext": "c", "lang": "C", "max_stars_repo_path": "core/electrons.c", "max_stars_repo_name": "soumide1102/nubhlight", "max_stars_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-02-05T22:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:05:37.000Z", "max_issues_repo_path": "core/electrons.c", "max_issues_repo_name": "soumide1102/nubhlight", "max_issues_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T02:10:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T20:00:30.000Z", "max_forks_repo_path": "core/electrons.c", "max_forks_repo_name": "soumide1102/nubhlight", "max_forks_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-02-21T04:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T21:42:12.000Z", "avg_line_length": 32.4186046512, "max_line_length": 80, "alphanum_fraction": 0.5265423242, "num_tokens": 3348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.43697971609420444}} {"text": "//////////////////////////////////////////// Spin glass phase transition ////////////////////////////////////////\n\n/* \n\nPhase space of the SK model.\n\nPlease cite the following paper when you use this code.\n\n[Ezaki T, Fonseca dos Reis E, Watanabe T, Sakaki M, Masuda N. Closer to critical resting-state neural dynamics in individuals with higher fluid intelligence. Commun Biol 3:1 (2020).](https://www.nature.com/articles/s42003-020-0774-y)\n\nIf you find a bug in this code, please contact the authors.\n\nAuthor: Elohim Fonseca dos Reis\n\nDate: July 8, 2020\n\n\nParameters:\n----------\n This program maps the SK model phase space using the following parameters that have to be set by the user before compiling:\n * Total number of spins (N);\n * Number of time steps to calculate the averages given a fixed configuration of $J_{ij}$ (tdim);\n * Number of $J_{ij}$ configurations for the configurational average (conf_num);\n * Number of sweeps in the transient period (thermal);\n * Array with the mean values of $J_{ij}$ (mu). The user has to set the minimum value (mu_min), maximum value (mu_max) and the step (mu_step). The size of the array with the mean values of $J_{ij}$ is given by 1+(mu_max-mu_min)/mu_step.\n * Array with the standard deviation values of $J_{ij}$ (sd). The user has to set the minimum value (sd_min), the maximum value (sd_max) and the step (sd_step). The size of the array with the standard deviation values of $J_{ij}$ is given by 1+(max_sd-min_sd)/sd_step.\n\nOutputs:\n-------\nThe program outputs the following measures: \n * spin glass susceptibility (Xsg);\n * uniform susceptibility (Xuni);\n * spin glass order parameter (q);\n * magnetization (m);\n * specific heat (c).\n\nThe outputs of the program are multiple .txt files, one for each pair of (mu, sd), and each .txt file contains one line with seven values in this \norder: mu, sd, Xsg, Xuni, q, m, c. For example, if the user sets *n* values for the mu array and *m* values for the sd array, the program outputs *nm* .txt files. The files are named as: file_0_0.txt, file_0_1.txt, ..., file_1_0.txt, file_1_1.txt... The reason for generating multiple .txt files is for parallelizing the program.\n\nThe program has a built-in naive parallelization for the mu and sd arrays, i.e., after compiling the code, if the user runs the same program on 10 different instances,\nfor example, the total time will decrease 10 times. So the user might be interested in running an array of jobs, each job running the same program for a given set of parameters.\n\n*/\n \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mt19937ar.h\"\n\n// Parameters\n#define N 264 // Total number of spins\n#define tdim 10000 // Thermal average dimension size\n#define conf_num 1000 // Number of interaction configurations\n#define thermal 10000 // Equilibration sweeps\n\n#define mu_min -0.002 // Minimum Average Interaction\n#define mu_max 0.01 // Maximum Average Interaction\n#define mu_step 0.0005 // Average interaction step\n#define sd_min 0 // Minimum interaction standard deviation\n#define sd_max 0.15 // Maximum interaction standard deviation\n#define sd_step 0.0075 // Interaction sd step\n\n\n// Matrix Serializations\n#define SSArr(SS,i,j) SS[ tdim*i + j ] // Spin series array\n#define JArr(J,i,j) J[ N*i + j ] // Interactions array\n#define CovArr(var,i,j) var[N*i + j] // Covariance array\n\n// Global Variables\nint *s; // Spins\nint *SS; // Spin series array (N x T)\ndouble *J; // Interactions (Jij) drawn from a gaussian distribution\n\n// Functions\ndouble randnum(); // Real random number [0,1)\nvoid init_randnum(); // Seed of the random number generator\nvoid sweep(); // Sweep of the system with N metropolis steps\ndouble cov(int *A, int k, int l); // Covariance cov[A(k),A(l)]\nvoid elapsed_time();\n\n\nint main()\n{\n\n///////////////////////////// Summary /////////////////////////////\n\tprintf(\"\\n\\nSummary:\\n\\n\");\n\tprintf(\"Number of spins: %d\\n\", N);\n\tprintf(\"Thermal average dimension: %d\\n\",tdim);\n\tprintf(\"Number of configurations: %d\\n\",conf_num);\n\tprintf(\"Equilibration sweeps: %d\\n\",thermal);\n\tprintf(\"Number of parameter values: %d mean(J), %d std(J)\", (int)round(((mu_max - mu_min) / mu_step + 1)), (int)round(((sd_max - sd_min) / sd_step + 1)));\n\tprintf(\"\\n\\n\");\n\n///////////////////////////// Model Parameters /////////////////////////////\n\n\t/* Average interaction array (main function variable) */\n\tint mu_size = (int)round( (mu_max - mu_min) / mu_step + 1); //printf(\"\\n\\nmu size: %d\\n\\n\", mu_size);\n\tdouble *mu=malloc(mu_size*sizeof(double));\n\tif(!mu){\n\t\tprintf(\"Out of memory.1\\n\");\n\t\texit(1);\n\t}\n\tfor(int i=0; i s d c\n *\n **/\n#include \n#include \"common.h\"\n\n#define COMPLEX\n/***************************************************************************//**\n *\n * @ingroup PLASMA_Complex64_t\n *\n * PLASMA_zgesdd - computes the singular value decomposition (SVD) of a complex\n * M-by-N matrix A, optionally computing the left and/or right singular\n * vectors, by using divide-and-conquer method. The SVD is written\n *\n * A = U * SIGMA * conjugate-transpose(V)\n *\n * where SIGMA is an M-by-N matrix which is zero except for its\n * min(m,n) diagonal elements, U is an M-by-M unitary matrix, and\n * V is an N-by-N unitary matrix. The diagonal elements of SIGMA\n * are the singular values of A; they are real and non-negative, and\n * are returned in descending order. The first min(m,n) columns of\n * U and V are the left and right singular vectors of A.\n *\n * Note that the routine returns VT = V**H, not V.\n *\n * The divide and conquer algorithm makes very mild assumptions about\n * floating point arithmetic. It will work on machines with a guard\n * digit in add/subtract, or on those binary machines without guard\n * digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or\n * Cray-2. It could conceivably fail on hexadecimal or decimal machines\n * without guard digits, but we know of none.\n *\n * NOTE that the input parameter of this function differ from the\n * LAPACK ZGESDD. We have jobu and jobvt instead of only jobz first\n * to be consistent with ZGESVD and second to allow a computation\n * of only U or VT.\n *******************************************************************************\n *\n * @param[in] jobu\n * Specifies options for computing all or part of the matrix U.\n * Intended usage:\n * = PlasmaVec = 'A'(lapack): all M columns of U are returned\n * in array U;\n * = PlasmaNoVec = 'N': no columns of U (no left singular vectors)\n * are computed.\n * = PlasmaSVec = 'S': the first min(m,n) columns of U (the left\n * singular vectors) are returned in the array U;\n * NOT SUPPORTTED YET\n * = PlasmaOVec = 'O': the first min(m,n) columns of U (the left\n * singular vectors) are overwritten on the array A;\n * NOT SUPPORTTED YET\n *\n * @param[in] jobvt\n * Specifies options for computing all or part of the matrix V**H.\n * Intended usage:\n * = PlasmaVec = 'A'(lapack): all N rows of V**H are returned\n * in the array VT;\n * = PlasmaNoVec = 'N': no rows of V**H (no right singular vectors)\n * are computed.\n * = PlasmaSVec = 'S': the first min(m,n) rows of V**H (the right\n * singular vectors) are returned in the array VT;\n * NOT SUPPORTTED YET\n * = PlasmaOVec = 'O': the first min(m,n) rows of V**H (the right\n * singular vectors) are overwritten on the array A;\n * NOT SUPPORTTED YET\n *\n * Note: jobu and jobvt cannot both be PlasmaOVec.\n *\n * @param[in] M\n * The number of rows of the matrix A. M >= 0.\n *\n * @param[in] N\n * The number of columns of the matrix A. N >= 0.\n *\n * @param[in,out] A\n * On entry, the M-by-N matrix A.\n * On exit,\n * if JOBU = 'O', A is overwritten with the first min(m,n)\n * columns of U (the left singular vectors,\n * stored columnwise);\n * if JOBVT = 'O', A is overwritten with the first min(m,n)\n * rows of V**H (the right singular vectors,\n * stored rowwise);\n * if JOBU .ne. 'O' and JOBVT .ne. 'O', the contents of A\n * are destroyed.\n *\n * @param[in] LDA\n * The leading dimension of the array A. LDA >= max(1,M).\n *\n * @param[out] S\n * The double precision singular values of A, sorted so that S(i) >= S(i+1).\n *\n * @param[in, out] descT\n * On entry, descriptor as return by PLASMA_Alloc_Workspace_zgesdd\n * On exit, contains auxiliary factorization data.\n *\n * @param[out] U\n * (LDU,M) if JOBU = 'A' or (LDU,min(M,N)) if JOBU = 'S'.\n * If JOBU = 'A', U contains the M-by-M unitary matrix U;\n * if JOBU = 'S', U contains the first min(m,n) columns of U\n * (the left singular vectors, stored columnwise);\n * if JOBU = 'N' or 'O', U is not referenced.\n *\n * @param[in] LDU\n * The leading dimension of the array U. LDU >= 1; if\n * JOBU = 'S' or 'A', LDU >= M.\n *\n * @param[out] VT\n * If JOBVT = 'A', VT contains the N-by-N unitary matrix\n * V**H;\n * if JOBVT = 'S', VT contains the first min(m,n) rows of\n * V**H (the right singular vectors, stored rowwise);\n * if JOBVT = 'N' or 'O', VT is not referenced.\n *\n * @param[in] LDVT\n * The leading dimension of the array VT. LDVT >= 1; if\n * JOBVT = 'A', LDVT >= N; if JOBVT = 'S', LDVT >= min(M,N).\n *\n *******************************************************************************\n *\n * @return\n * \\retval PLASMA_SUCCESS successful exit\n * \\retval <0 if -i, the i-th argument had an illegal value\n *\n *******************************************************************************\n *\n * @sa PLASMA_zgesdd_Tile\n * @sa PLASMA_zgesdd_Tile_Async\n * @sa PLASMA_cgesdd\n * @sa PLASMA_dgesdd\n * @sa PLASMA_sgesdd\n *\n ******************************************************************************/\nint PLASMA_zgesdd(PLASMA_enum jobu, PLASMA_enum jobvt, int M, int N,\n PLASMA_Complex64_t *A, int LDA,\n double *S,\n PLASMA_desc *descT,\n PLASMA_Complex64_t *U, int LDU,\n PLASMA_Complex64_t *VT, int LDVT)\n{\n int NB;\n int status;\n plasma_context_t *plasma;\n PLASMA_sequence *sequence = NULL;\n PLASMA_request request = PLASMA_REQUEST_INITIALIZER;\n PLASMA_desc descA;\n\n plasma = plasma_context_self();\n if (plasma == NULL) {\n plasma_fatal_error(\"PLASMA_zgesdd\", \"PLASMA not initialized\");\n return PLASMA_ERR_NOT_INITIALIZED;\n }\n\n /* Check input arguments */\n if (jobu != PlasmaNoVec && jobu !=PlasmaVec) {\n plasma_error(\"PLASMA_zgesdd\", \"illegal value of jobu\");\n return -1;\n }\n if (jobvt != PlasmaNoVec && jobvt != PlasmaVec) {\n plasma_error(\"PLASMA_zgesdd\", \"illegal value of jobvt\");\n return -2;\n }\n if (jobvt != jobu) {\n plasma_error(\"PLASMA_zgesdd\", \"in this version: jobu should be equal jobvt\");\n return -22;\n }\n if (M < 0) {\n plasma_error(\"PLASMA_zgesdd\", \"illegal value of M\");\n return -3;\n }\n if (N < 0) {\n plasma_error(\"PLASMA_zgesdd\", \"illegal value of N\");\n return -4;\n }\n if (LDA < max(1, M)) {\n plasma_error(\"PLASMA_zgesdd\", \"illegal value of LDA\");\n return -6;\n }\n if (LDU < 1) {\n plasma_error(\"PLASMA_zgesdd\", \"illegal value of LDU\");\n return -9;\n }\n if (LDVT < 1) {\n plasma_error(\"PLASMA_zgesdd\", \"illegal value of LDVT\");\n return -11;\n }\n /* Quick return */\n if (min(M, N) == 0) {\n return PLASMA_SUCCESS;\n }\n\n\n /* Tune NB & IB depending on M & N; Set NBNB */\n status = plasma_tune(PLASMA_FUNC_ZGESVD, M, N, 0);\n if (status != PLASMA_SUCCESS) {\n plasma_error(\"PLASMA_zgesdd\", \"plasma_tune() failed\");\n return status;\n }\n\n /* Set MT, NT */\n NB = PLASMA_NB;\n\n plasma_sequence_create(plasma, &sequence);\n\n if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n plasma_zooplap2tile( descA, A, NB, NB, LDA, N, 0, 0, M, N, sequence, &request,\n plasma_desc_mat_free(&(descA)) );\n } else {\n plasma_ziplap2tile( descA, A, NB, NB, LDA, N, 0, 0, M, N,\n sequence, &request);\n }\n\n\n\n /* Call the tile interface */\n PLASMA_zgesdd_Tile_Async(jobu, jobvt, &descA, S, descT, U, LDU, VT, LDVT, sequence, &request);\n\n\n if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n plasma_zooptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);\n plasma_dynamic_sync();\n plasma_desc_mat_free(&descA);\n } else {\n plasma_ziptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);\n plasma_dynamic_sync();\n }\n\n\n status = sequence->status;\n plasma_sequence_destroy(plasma, sequence);\n return status;\n}\n\n/***************************************************************************//**\n *\n * @ingroup PLASMA_Complex64_t_Tile\n *\n * PLASMA_zgesdd_Tile - computes the singular value decomposition (SVD) of a complex\n * M-by-N matrix A, optionally computing the left and/or right singular\n * vectors.\n * Tile equivalent of PLASMA_zgesdd().\n * Operates on matrices stored by tiles.\n * All matrices are passed through descriptors.\n * All dimensions are taken from the descriptors.\n *\n *******************************************************************************\n *\n * @param[in] jobu\n * Specifies options for computing all or part of the matrix U.\n * Intended usage:\n * = PlasmaVec = 'A'(lapack): all M columns of U are returned\n * in array U;\n * = PlasmaNoVec = 'N': no columns of U (no left singular vectors)\n * are computed.\n * = PlasmaSVec = 'S': the first min(m,n) columns of U (the left\n * singular vectors) are returned in the array U;\n * NOT SUPPORTTED YET\n * = PlasmaOVec = 'O': the first min(m,n) columns of U (the left\n * singular vectors) are overwritten on the array A;\n * NOT SUPPORTTED YET\n *\n * @param[in] jobvt\n * Specifies options for computing all or part of the matrix V**H.\n * Intended usage:\n * = PlasmaVec = 'A'(lapack): all N rows of V**H are returned\n * in the array VT;\n * = PlasmaNoVec = 'N': no rows of V**H (no right singular vectors)\n * are computed.\n * = PlasmaSVec = 'S': the first min(m,n) rows of V**H (the right\n * singular vectors) are returned in the array VT;\n * NOT SUPPORTTED YET\n * = PlasmaOVec = 'O': the first min(m,n) rows of V**H (the right\n * singular vectors) are overwritten on the array A;\n * NOT SUPPORTTED YET\n *\n * Note: jobu and jobvt cannot both be PlasmaOVec.\n *\n * @param[in,out] A\n * On entry, the M-by-N matrix A.\n * On exit,\n * if JOBU = 'O', A is overwritten with the first min(m,n)\n * columns of U (the left singular vectors,\n * stored columnwise);\n * if JOBVT = 'O', A is overwritten with the first min(m,n)\n * rows of V**H (the right singular vectors,\n * stored rowwise);\n * if JOBU .ne. 'O' and JOBVT .ne. 'O', the contents of A\n * are destroyed.\n *\n * @param[out] S\n * The singular values of A, sorted so that S(i) >= S(i+1).\n *\n * @param[in, out] T\n * On entry, descriptor as return by PLASMA_Alloc_Workspace_zgesdd\n * On exit, contains auxiliary factorization data.\n *\n * @param[out] U\n * (LDU,M) if JOBU = 'A' or (LDU,min(M,N)) if JOBU = 'S'.\n * If JOBU = 'A', U contains the M-by-M unitary matrix U;\n * if JOBU = 'S', U contains the first min(m,n) columns of U\n * (the left singular vectors, stored columnwise);\n * if JOBU = 'N' or 'O', U is not referenced.\n *\n * @param[in] LDU\n * The leading dimension of the array U. LDU >= 1; if\n * JOBU = 'S' or 'A', LDU >= M.\n *\n * @param[out] VT\n * If JOBVT = 'A', VT contains the N-by-N unitary matrix\n * V**H;\n * if JOBVT = 'S', VT contains the first min(m,n) rows of\n * V**H (the right singular vectors, stored rowwise);\n * if JOBVT = 'N' or 'O', VT is not referenced.\n *\n * @param[in] LDVT\n * The leading dimension of the array VT. LDVT >= 1; if\n * JOBVT = 'A', LDVT >= N; if JOBVT = 'S', LDVT >= min(M,N).\n *\n *******************************************************************************\n *\n * @return\n * \\return PLASMA_SUCCESS successful exit\n *\n *******************************************************************************\n *\n * @sa PLASMA_zgesdd\n * @sa PLASMA_zgesdd_Tile_Async\n * @sa PLASMA_cgesdd_Tile\n * @sa PLASMA_dgesdd_Tile\n * @sa PLASMA_sgesdd_Tile\n *\n ******************************************************************************/\nint PLASMA_zgesdd_Tile(PLASMA_enum jobu, PLASMA_enum jobvt,\n PLASMA_desc *A,\n double *S,\n PLASMA_desc *T,\n PLASMA_Complex64_t *U, int LDU,\n PLASMA_Complex64_t *VT, int LDVT)\n{\n plasma_context_t *plasma;\n PLASMA_sequence *sequence = NULL;\n PLASMA_request request = PLASMA_REQUEST_INITIALIZER;\n int status;\n\n plasma = plasma_context_self();\n if (plasma == NULL) {\n plasma_fatal_error(\"PLASMA_zgesdd_Tile\", \"PLASMA not initialized\");\n return PLASMA_ERR_NOT_INITIALIZED;\n }\n plasma_sequence_create(plasma, &sequence);\n PLASMA_zgesdd_Tile_Async(jobu, jobvt, A, S, T, U, LDU, VT, LDVT, sequence, &request);\n plasma_dynamic_sync();\n status = sequence->status;\n plasma_sequence_destroy(plasma, sequence);\n return status;\n}\n\n/***************************************************************************//**\n *\n * @ingroup PLASMA_Complex64_t_Tile_Async\n *\n * PLASMA_zgesdd_Tile_Async - computes the singular value decomposition (SVD) of a complex\n * M-by-N matrix A, optionally computing the left and/or right singular\n * vectors.\n * Non-blocking equivalent of PLASMA_zgesdd_Tile().\n * May return before the computation is finished.\n * Allows for pipelining of operations at runtime.\n *\n *******************************************************************************\n *\n * @param[in] sequence\n * Identifies the sequence of function calls that this call belongs to\n * (for completion checks and exception handling purposes).\n *\n * @param[out] request\n * Identifies this function call (for exception handling purposes).\n *\n *******************************************************************************\n *\n * @sa PLASMA_zgesdd\n * @sa PLASMA_zgesdd_Tile\n * @sa PLASMA_cgesdd_Tile_Async\n * @sa PLASMA_dgesdd_Tile_Async\n * @sa PLASMA_sgesdd_Tile_Async\n *\n ******************************************************************************/\nint PLASMA_zgesdd_Tile_Async(PLASMA_enum jobu, PLASMA_enum jobvt,\n PLASMA_desc *A,\n double *S,\n PLASMA_desc *T,\n PLASMA_Complex64_t *U, int LDU,\n PLASMA_Complex64_t *VT, int LDVT,\n PLASMA_sequence *sequence, PLASMA_request *request)\n{\n PLASMA_desc descA;\n PLASMA_desc descT;\n PLASMA_desc descU, descVT;\n PLASMA_Complex64_t *AB;\n double *E;\n int M;\n int N;\n int MINMN;\n int NB;\n int LDAB;\n int i;\n int status;\n\n plasma_context_t *plasma;\n plasma = plasma_context_self();\n\n if (plasma == NULL) {\n plasma_fatal_error(\"PLASMA_zgesdd_Tile_Async\", \"PLASMA not initialized\");\n return PLASMA_ERR_NOT_INITIALIZED;\n }\n if (sequence == NULL) {\n plasma_fatal_error(\"PLASMA_zgesdd_Tile_Async\", \"NULL sequence\");\n return PLASMA_ERR_UNALLOCATED;\n }\n if (request == NULL) {\n plasma_fatal_error(\"PLASMA_zgesdd_Tile_Async\", \"NULL request\");\n return PLASMA_ERR_UNALLOCATED;\n }\n /* Check sequence status */\n if (sequence->status == PLASMA_SUCCESS)\n request->status = PLASMA_SUCCESS;\n else\n return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);\n\n /* Check descriptors for correctness */\n if (plasma_desc_check(A) != PLASMA_SUCCESS) {\n plasma_error(\"PLASMA_zgesdd_Tile_Async\", \"invalid first descriptor\");\n return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n } else {\n descA = *A;\n }\n if (plasma_desc_check(T) != PLASMA_SUCCESS) {\n plasma_error(\"PLASMA_zgesdd_Tile_Async\", \"invalid fourth descriptor\");\n return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n } else {\n descT = *T;\n }\n /* Check input arguments */\n if (jobu != PlasmaNoVec && jobu != PlasmaVec) {\n plasma_error(\"PLASMA_zgesdd_Tile_Async\", \"illegal value of jobu\");\n return PLASMA_ERR_NOT_SUPPORTED;\n }\n if (jobvt != PlasmaNoVec && jobvt != PlasmaVec) {\n plasma_error(\"PLASMA_zgesdd_Tile_Async\", \"illegal value of jobvt\");\n return PLASMA_ERR_NOT_SUPPORTED;\n }\n if (jobvt != jobu) {\n plasma_error(\"PLASMA_zgesdd_Tile_Async\", \"in this version: jobu should be equal jobvt\");\n return PLASMA_ERR_NOT_SUPPORTED;\n }\n if (descA.nb != descA.mb) {\n plasma_error(\"PLASMA_zgesdd_Tile_Async\", \"only square tiles supported\");\n return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n }\n\n\n #if defined(ENABLE_TIMER)\n PLASMA_Double_t timelpk=0.0,timeaplQ2=0.0, timeT=0.0;\n PLASMA_Double_t timeB=0.0,timeblg=0.0,timeaplQ1=0.0,timeconv1=0.0,timeconv2=0.0,timeall=0.0;\n timeall = PLASMA_Wtime();\n #endif\n PLASMA_enum uplo = descA.m >= descA.n ? PlasmaUpper : PlasmaLower;\n M = descA.m;\n N = descA.n;\n MINMN = min(M,N);\n NB = min(descA.mb,MINMN);\n LDAB = 3*NB+1;\n /*=======================================\n * case Mworld_size);\n /* call SVD solver using lapack routine */\n PLASMA_enum jobz = jobu == PlasmaVec ? PlasmaAllVec : PlasmaNoVec;\n status = LAPACKE_zgesdd(LAPACK_COL_MAJOR, lapack_const(jobz),\n M, N, AB, M, S, U, LDU, VT, LDVT);\n if(status != 0){\n plasma_error(\"PLASMA_zgesvd\",\"ZGESVD\");\n }\n sequence->status = status;\n plasma_setlapack_sequential(plasma);\n #if defined(ENABLE_TIMER)\n timelpk = PLASMA_Wtime()-timelpk;\n printf(\" Finish Eigensolver-lpkonly timing= %lf threads %d\\n\" ,timelpk, plasma->world_size);\n #endif\n /*=======================================\n * END of calling SVD solver\n *=======================================*/\n /* convert the lapack to the tile descA */\n if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n //plasma_zooplap2tile_noalloc( descA, AB, NB, NB, M, N, 0, 0, M, N, sequence, request);\n plasma_parallel_call_5( plasma_pzlapack_to_tile,\n PLASMA_Complex64_t*, AB,\n int, M,\n PLASMA_desc, descA,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n plasma_dynamic_sync();\n free(AB);\n } else {\n plasma_ziplap2tile( descA, AB, NB, NB, M, N, 0, 0, M, N,\n sequence, request);\n }\n plasma_dynamic_sync();\n return PLASMA_SUCCESS;\n }\n /*=======================================\n * END OF case Mhouseholder == PLASMA_FLAT_HOUSEHOLDER) { */\n plasma_dynamic_call_4(plasma_pzgebrd_ge2gb,\n PLASMA_desc, descA,\n PLASMA_desc, descT,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n /* } */\n /* else { */\n /* plasma_dynamic_call_4(plasma_pzgebrd_ge2gb_rh, */\n /* PLASMA_desc, descA, */\n /* PLASMA_desc, descT, */\n /* PLASMA_sequence*, sequence, */\n /* PLASMA_request*, request); */\n /* } */\n //plasma_dynamic_sync();\n plasma_dynamic_call_6( plasma_pzgbcpy_t2bl,\n PLASMA_enum, descA.m >= descA.n ? PlasmaUpper : PlasmaLower,\n PLASMA_desc, descA,\n PLASMA_Complex64_t*, &(AB[NB]),\n int, LDAB,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n plasma_dynamic_sync();\n status = sequence->status;\n if (status != PLASMA_SUCCESS) {\n plasma_error(\"PLASMA_zgesdd\",\"pzgebrd_ge2gb+pzcopy\");\n return status;\n }\n #if defined(ENABLE_TIMER)\n timeB = PLASMA_Wtime()-timeB;\n printf(\"\\n Finish Band red timing= %lf \\n\",timeB);\n #endif\n /*=======================================\n * END of calling Reduction to BAND\n *=======================================*/\n /*=======================================\n * calling Reduction from BAND to bidiag\n *=======================================*/\n PLASMA_Complex64_t *VQ2 = NULL;\n PLASMA_Complex64_t *VP2 = NULL;\n PLASMA_Complex64_t *TAUQ2 = NULL;\n PLASMA_Complex64_t *TAUP2 = NULL;\n PLASMA_Complex64_t *TQ2 = NULL;\n PLASMA_Complex64_t *TP2 = NULL;\n int Vblksiz, blkcnt, LDT, LDV;\n int WANTZ = 0;\n /* compute fraction of singular vectors */\n /* for future use when a portion of the eigenvectors are requested */\n int ME = M;\n int NE = N;\n int MINMNE = MINMN;\n /*\n int fraction = 100;\n if((fraction<100)&&(fraction>0)) {\n MINMNE = plasma_ceildiv(fraction*MINMN,100);\n ME = MINMNE;\n NE = MINMNE;\n }\n */\n if( jobu == PlasmaNoVec )\n WANTZ=0;\n else\n WANTZ=2;\n /* Vblksiz correspond to the blocking used when applying V2 to the matrix U\n * it is similar to IB in LAPACK ZUNMQR.\n * blkcnt is the number of diamond or tile of Vs */\n /* Note that in case PlamaVec requested, the V2 and T2 are stored by the\n * bulgechasing function in a special format:\n * for V2s: it store the V2(LDV,Vblksiz) of each diamond in a tile storage meaning\n * that V2_1 is stored then V2_2,..., V2_blkcnt.\n * blkcnt is the number of diamond.\n * */\n Vblksiz = min(NB,48);\n LDT = Vblksiz;\n /* data for U */\n if( jobu == PlasmaVec ) {\n findVTsiz(MINMN, NB, Vblksiz, &blkcnt, &LDV);\n TAUQ2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, blkcnt*Vblksiz, PlasmaComplexDouble);\n VQ2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, LDV*blkcnt*Vblksiz, PlasmaComplexDouble);\n TQ2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, LDT*blkcnt*Vblksiz, PlasmaComplexDouble);\n if ( (TAUQ2 == NULL) || (VQ2 == NULL) || (TQ2 == NULL) ) {\n plasma_error(\"PLASMA_zgesdd\", \"plasma_shared_alloc() failed\");\n plasma_shared_free(plasma, TAUQ2);\n plasma_shared_free(plasma, VQ2);\n plasma_shared_free(plasma, TQ2);\n return PLASMA_ERR_OUT_OF_RESOURCES;\n }\n memset(TAUQ2, 0, blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));\n memset(VQ2, 0, LDV*blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));\n memset(TQ2, 0, LDT*blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));\n }\n else {\n TAUQ2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaComplexDouble);\n VQ2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaComplexDouble);\n if ( (TAUQ2 == NULL) || (VQ2 == NULL) ) {\n plasma_error(\"PLASMA_zgesdd\", \"plasma_shared_alloc() failed\");\n plasma_shared_free(plasma, TAUQ2);\n plasma_shared_free(plasma, VQ2);\n return PLASMA_ERR_OUT_OF_RESOURCES;\n }\n memset(TAUQ2, 0, 2*MINMN*sizeof(PLASMA_Complex64_t));\n memset(VQ2, 0, 2*MINMN*sizeof(PLASMA_Complex64_t));\n }\n /* data for VT */\n if( jobvt == PlasmaVec ) {\n findVTsiz(MINMN, NB, Vblksiz, &blkcnt, &LDV);\n TAUP2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, blkcnt*Vblksiz, PlasmaComplexDouble);\n VP2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, LDV*blkcnt*Vblksiz, PlasmaComplexDouble);\n TP2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, LDT*blkcnt*Vblksiz, PlasmaComplexDouble);\n if ( (TAUP2 == NULL) || (VP2 == NULL) || (TP2 == NULL) ) {\n plasma_error(\"PLASMA_zgesdd\", \"plasma_shared_alloc() failed\");\n plasma_shared_free(plasma, TAUP2);\n plasma_shared_free(plasma, VP2);\n plasma_shared_free(plasma, TP2);\n return PLASMA_ERR_OUT_OF_RESOURCES;\n }\n memset(TAUP2, 0, blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));\n memset(VP2, 0, LDV*blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));\n memset(TP2, 0, LDT*blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));\n }\n else {\n TAUP2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaComplexDouble);\n VP2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaComplexDouble);\n if ( (TAUP2 == NULL) || (VP2 == NULL) ) {\n plasma_error(\"PLASMA_zgesdd\", \"plasma_shared_alloc() failed\");\n plasma_shared_free(plasma, TAUQ2);\n plasma_shared_free(plasma, VQ2);\n return PLASMA_ERR_OUT_OF_RESOURCES;\n }\n memset(TAUP2, 0, 2*MINMN*sizeof(PLASMA_Complex64_t));\n memset(VP2, 0, 2*MINMN*sizeof(PLASMA_Complex64_t));\n }\n /*=======================================\n * calling bulge chasing\n *=======================================*/\n #if defined(ENABLE_TIMER)\n timeblg = PLASMA_Wtime();\n #endif\n plasma_parallel_call_16(plasma_pzgebrd_gb2bd_v1,\n PLASMA_enum, uplo,\n int, MINMN,\n int, NB,\n int, Vblksiz,\n PLASMA_Complex64_t*, AB,\n int, LDAB,\n PLASMA_Complex64_t*, VQ2,\n PLASMA_Complex64_t*, TAUQ2,\n PLASMA_Complex64_t*, VP2,\n PLASMA_Complex64_t*, TAUP2,\n double*, S,\n double*, E,\n int, WANTZ,\n int, WANTZ,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n /* WARNING: If plasma_pzgebrd_gb2bd is implemented through a dynamic call, don't\n * forget to synchronize */\n plasma_dynamic_sync();\n #if defined(ENABLE_TIMER)\n timeblg = PLASMA_Wtime()-timeblg;\n printf(\" Finish Bulge timing= %lf \\n\" ,timeblg);\n #endif\n /*=======================================\n * END of calling bulge chasing\n *=======================================*/\n /*=======================================\n * calling SVD solver\n *=======================================*/\n plasma_setlapack_multithreads(plasma->world_size);\n /* call SVD solver using lapack routine for our resulting bidiag [S E] */\n /* call eigensolver using lapack routine for our resulting tridiag [D E] */\n if((jobu == PlasmaNoVec)&&(jobvt == PlasmaNoVec)){\n #if defined(ENABLE_TIMER)\n timelpk = PLASMA_Wtime();\n #endif\n status = LAPACKE_dbdsdc(LAPACK_COL_MAJOR, lapack_const(uplo), lapack_const(PlasmaNoVec),\n MINMN, S, E, NULL, LDU, NULL, LDVT, NULL, NULL);\n #if defined(ENABLE_TIMER)\n timelpk = PLASMA_Wtime()-timelpk;\n #endif\n } else {\n // set U and VT to zero\n memset(VT, 0, N*LDVT*sizeof(PLASMA_Complex64_t));\n memset(U, 0, M*LDU*sizeof(PLASMA_Complex64_t));\n /* Initialize U(N+1:M,N+1:M) and VT(M+1:N,M+1:N) to Identity */\n\n for(i=N; istatus = status;\n plasma_setlapack_sequential(plasma);\n #if defined(ENABLE_TIMER)\n int fraction = (MINMNE*100)/N;\n printf(\" Finish Eigensolver timing= %lf WANTZ %d threads %d fraction %d MINMNE %d \\n\" ,timelpk, WANTZ, plasma->world_size, fraction, MINMNE);\n #endif\n /*=======================================\n * END of calling SVD solver\n *=======================================*/\n /*=======================================\n * generate U from the bulge\n *=======================================*/\n if (jobu == PlasmaVec){\n #if defined(ENABLE_TIMER)\n timeT = PLASMA_Wtime();\n #endif\n /* compute T2 */\n plasma_static_call_8(plasma_pzlarft_blgtrd,\n int, MINMN,\n int, NB,\n int, Vblksiz,\n PLASMA_Complex64_t*, VQ2,\n PLASMA_Complex64_t*, TQ2,\n PLASMA_Complex64_t*, TAUQ2,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n #if defined(ENABLE_TIMER)\n plasma_dynamic_sync();\n timeT = PLASMA_Wtime()-timeT;\n printf(\" Finish compute TU2 timing= %lf \\n\" ,timeT);\n timeaplQ2 = PLASMA_Wtime();\n #endif\n /* apply Q2 from Left */\n plasma_static_call_14(plasma_pzunmqr_blgtrd,\n PLASMA_enum, PlasmaLeft,\n PLASMA_enum, PlasmaNoTrans,\n int, MINMN,\n int, NB,\n int, MINMNE,\n int, Vblksiz,\n int, WANTZ,\n PLASMA_Complex64_t*, VQ2,\n PLASMA_Complex64_t*, TQ2,\n PLASMA_Complex64_t*, TAUQ2,\n PLASMA_Complex64_t*, U,\n int, LDU,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n #if defined(ENABLE_TIMER)\n plasma_dynamic_sync();\n timeaplQ2 = PLASMA_Wtime()-timeaplQ2;\n printf(\" Finish compute U2 timing= %lf \\n\" ,timeaplQ2);\n #endif\n /*=======================================\n * apply Q1 from the reduction to band\n *=======================================*/\n /* CASE NB>N, Q1 doesn't need to be applied, only bulge chasing has been done */\n if( NB < N ){\n #if defined(ENABLE_TIMER)\n plasma_dynamic_sync();\n timeconv1 = PLASMA_Wtime();\n #endif\n if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n plasma_zooplap2tile( descU, U, NB, NB, LDU, ME, 0, 0, M, ME, sequence, request, plasma_desc_mat_free(&(descU)) );\n } else {\n plasma_ziplap2tile( descU, U, NB, NB, LDU, ME, 0, 0, M, ME, sequence, request);\n }\n #if defined(ENABLE_TIMER)\n timeconv1 = PLASMA_Wtime()-timeconv1;\n timeaplQ1 = PLASMA_Wtime();\n #endif\n /* Accumulate the transformations from the first stage */\n if(MN, Q1 doesn't need to be applied, only bulge chasing has been done */\n if( NB < N ){\n #if defined(ENABLE_TIMER)\n plasma_dynamic_sync();\n timeconv1 = PLASMA_Wtime();\n #endif\n if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n plasma_zooplap2tile( descVT, VT, NB, NB, LDVT, N, 0, 0, NE, N, sequence, request, plasma_desc_mat_free(&(descVT)) );\n } else {\n plasma_ziplap2tile( descVT, VT, NB, NB, LDVT, N, 0, 0, NE, N, sequence, request);\n }\n #if defined(ENABLE_TIMER)\n timeconv1 = PLASMA_Wtime()-timeconv1;\n timeaplQ1 = PLASMA_Wtime();\n #endif\n /* Accumulate the transformations from the first stage */\n if(Mworld_size, MINMN, fraction, MINMNE, timeall);\n #endif\n if( jobu == PlasmaVec )\n plasma_shared_free(plasma, TQ2);\n if( jobvt == PlasmaVec )\n plasma_shared_free(plasma, TP2);\n plasma_shared_free(plasma, VQ2);\n plasma_shared_free(plasma, TAUQ2);\n plasma_shared_free(plasma, VP2);\n plasma_shared_free(plasma, TAUP2);\n plasma_shared_free(plasma, E);\n plasma_shared_free(plasma, AB);\n return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "961896f96786924736a4674eb520b4a490576196", "size": 42986, "ext": "c", "lang": "C", "max_stars_repo_path": "compute/zgesdd.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compute/zgesdd.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute/zgesdd.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5911237016, "max_line_length": 153, "alphanum_fraction": 0.533150328, "num_tokens": 11476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.43687772604750835}} {"text": "/* randist/gsl_randist.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_RANDIST_H__\n#define __GSL_RANDIST_H__\n#include \n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nunsigned int gsl_ran_bernoulli (const gsl_rng * r, double p);\ndouble gsl_ran_bernoulli_pdf (const unsigned int k, double p);\n\ndouble gsl_ran_beta (const gsl_rng * r, const double a, const double b);\ndouble gsl_ran_beta_pdf (const double x, const double a, const double b);\n\nunsigned int gsl_ran_binomial (const gsl_rng * r, double p, unsigned int n);\nunsigned int gsl_ran_binomial_knuth (const gsl_rng * r, double p, unsigned int n);\nunsigned int gsl_ran_binomial_tpe (const gsl_rng * r, double p, unsigned int n);\ndouble gsl_ran_binomial_pdf (const unsigned int k, const double p, const unsigned int n);\n\ndouble gsl_ran_exponential (const gsl_rng * r, const double mu);\ndouble gsl_ran_exponential_pdf (const double x, const double mu);\n\ndouble gsl_ran_exppow (const gsl_rng * r, const double a, const double b);\ndouble gsl_ran_exppow_pdf (const double x, const double a, const double b);\n\ndouble gsl_ran_cauchy (const gsl_rng * r, const double a);\ndouble gsl_ran_cauchy_pdf (const double x, const double a);\n\ndouble gsl_ran_chisq (const gsl_rng * r, const double nu);\ndouble gsl_ran_chisq_pdf (const double x, const double nu);\n\nvoid gsl_ran_dirichlet (const gsl_rng * r, const size_t K, const double alpha[], double theta[]);\ndouble gsl_ran_dirichlet_pdf (const size_t K, const double alpha[], const double theta[]);\ndouble gsl_ran_dirichlet_lnpdf (const size_t K, const double alpha[], const double theta[]);\n\ndouble gsl_ran_erlang (const gsl_rng * r, const double a, const double n);\ndouble gsl_ran_erlang_pdf (const double x, const double a, const double n);\n\ndouble gsl_ran_fdist (const gsl_rng * r, const double nu1, const double nu2);\ndouble gsl_ran_fdist_pdf (const double x, const double nu1, const double nu2);\n\ndouble gsl_ran_flat (const gsl_rng * r, const double a, const double b);\ndouble gsl_ran_flat_pdf (double x, const double a, const double b);\n\ndouble gsl_ran_gamma (const gsl_rng * r, const double a, const double b);\ndouble gsl_ran_gamma_int (const gsl_rng * r, const unsigned int a);\ndouble gsl_ran_gamma_pdf (const double x, const double a, const double b);\ndouble gsl_ran_gamma_mt (const gsl_rng * r, const double a, const double b);\ndouble gsl_ran_gamma_knuth (const gsl_rng * r, const double a, const double b);\n\ndouble gsl_ran_gaussian (const gsl_rng * r, const double sigma);\ndouble gsl_ran_gaussian_ratio_method (const gsl_rng * r, const double sigma);\ndouble gsl_ran_gaussian_ziggurat (const gsl_rng * r, const double sigma);\ndouble gsl_ran_gaussian_pdf (const double x, const double sigma);\n\ndouble gsl_ran_ugaussian (const gsl_rng * r);\ndouble gsl_ran_ugaussian_ratio_method (const gsl_rng * r);\ndouble gsl_ran_ugaussian_pdf (const double x);\n\ndouble gsl_ran_gaussian_tail (const gsl_rng * r, const double a, const double sigma);\ndouble gsl_ran_gaussian_tail_pdf (const double x, const double a, const double sigma);\n\ndouble gsl_ran_ugaussian_tail (const gsl_rng * r, const double a);\ndouble gsl_ran_ugaussian_tail_pdf (const double x, const double a);\n\nvoid gsl_ran_bivariate_gaussian (const gsl_rng * r, double sigma_x, double sigma_y, double rho, double *x, double *y);\ndouble gsl_ran_bivariate_gaussian_pdf (const double x, const double y, const double sigma_x, const double sigma_y, const double rho);\n\ndouble gsl_ran_landau (const gsl_rng * r);\ndouble gsl_ran_landau_pdf (const double x);\n\nunsigned int gsl_ran_geometric (const gsl_rng * r, const double p);\ndouble gsl_ran_geometric_pdf (const unsigned int k, const double p);\n\nunsigned int gsl_ran_hypergeometric (const gsl_rng * r, unsigned int n1, unsigned int n2, unsigned int t);\ndouble gsl_ran_hypergeometric_pdf (const unsigned int k, const unsigned int n1, const unsigned int n2, unsigned int t);\n\ndouble gsl_ran_gumbel1 (const gsl_rng * r, const double a, const double b);\ndouble gsl_ran_gumbel1_pdf (const double x, const double a, const double b);\n\ndouble gsl_ran_gumbel2 (const gsl_rng * r, const double a, const double b);\ndouble gsl_ran_gumbel2_pdf (const double x, const double a, const double b);\n\ndouble gsl_ran_logistic (const gsl_rng * r, const double a);\ndouble gsl_ran_logistic_pdf (const double x, const double a);\n\ndouble gsl_ran_lognormal (const gsl_rng * r, const double zeta, const double sigma);\ndouble gsl_ran_lognormal_pdf (const double x, const double zeta, const double sigma);\n\nunsigned int gsl_ran_logarithmic (const gsl_rng * r, const double p);\ndouble gsl_ran_logarithmic_pdf (const unsigned int k, const double p);\n\nvoid gsl_ran_multinomial (const gsl_rng * r, const size_t K,\n const unsigned int N, const double p[],\n unsigned int n[] );\ndouble gsl_ran_multinomial_pdf (const size_t K,\n const double p[], const unsigned int n[] );\ndouble gsl_ran_multinomial_lnpdf (const size_t K,\n const double p[], const unsigned int n[] );\n\n\nunsigned int gsl_ran_negative_binomial (const gsl_rng * r, double p, double n);\ndouble gsl_ran_negative_binomial_pdf (const unsigned int k, const double p, double n);\n\nunsigned int gsl_ran_pascal (const gsl_rng * r, double p, unsigned int n);\ndouble gsl_ran_pascal_pdf (const unsigned int k, const double p, unsigned int n);\n\ndouble gsl_ran_pareto (const gsl_rng * r, double a, const double b);\ndouble gsl_ran_pareto_pdf (const double x, const double a, const double b);\n\nunsigned int gsl_ran_poisson (const gsl_rng * r, double mu);\nvoid gsl_ran_poisson_array (const gsl_rng * r, size_t n, unsigned int array[],\n double mu);\ndouble gsl_ran_poisson_pdf (const unsigned int k, const double mu);\n\ndouble gsl_ran_rayleigh (const gsl_rng * r, const double sigma);\ndouble gsl_ran_rayleigh_pdf (const double x, const double sigma);\n\ndouble gsl_ran_rayleigh_tail (const gsl_rng * r, const double a, const double sigma);\ndouble gsl_ran_rayleigh_tail_pdf (const double x, const double a, const double sigma);\n\ndouble gsl_ran_tdist (const gsl_rng * r, const double nu);\ndouble gsl_ran_tdist_pdf (const double x, const double nu);\n\ndouble gsl_ran_laplace (const gsl_rng * r, const double a);\ndouble gsl_ran_laplace_pdf (const double x, const double a);\n\ndouble gsl_ran_levy (const gsl_rng * r, const double c, const double alpha);\ndouble gsl_ran_levy_skew (const gsl_rng * r, const double c, const double alpha, const double beta);\n\ndouble gsl_ran_weibull (const gsl_rng * r, const double a, const double b);\ndouble gsl_ran_weibull_pdf (const double x, const double a, const double b);\n\nvoid gsl_ran_dir_2d (const gsl_rng * r, double * x, double * y);\nvoid gsl_ran_dir_2d_trig_method (const gsl_rng * r, double * x, double * y);\nvoid gsl_ran_dir_3d (const gsl_rng * r, double * x, double * y, double * z);\nvoid gsl_ran_dir_nd (const gsl_rng * r, size_t n, double * x);\n\nvoid gsl_ran_shuffle (const gsl_rng * r, void * base, size_t nmembm, size_t size);\nint gsl_ran_choose (const gsl_rng * r, void * dest, size_t k, void * src, size_t n, size_t size) ;\nvoid gsl_ran_sample (const gsl_rng * r, void * dest, size_t k, void * src, size_t n, size_t size) ;\n\n\ntypedef struct { /* struct for Walker algorithm */\n size_t K;\n size_t *A;\n double *F;\n} gsl_ran_discrete_t;\n\ngsl_ran_discrete_t * gsl_ran_discrete_preproc (size_t K, const double *P);\nvoid gsl_ran_discrete_free(gsl_ran_discrete_t *g);\nsize_t gsl_ran_discrete (const gsl_rng *r, const gsl_ran_discrete_t *g);\ndouble gsl_ran_discrete_pdf (size_t k, const gsl_ran_discrete_t *g);\n\n\n__END_DECLS\n\n#endif /* __GSL_RANDIST_H__ */\n", "meta": {"hexsha": "49775bde016824b7d6bc0dc527dd4d4e60c5aba0", "size": 8601, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/gsl_randist.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/randist/gsl_randist.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/randist/gsl_randist.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 46.2419354839, "max_line_length": 133, "alphanum_fraction": 0.7566562028, "num_tokens": 2323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.43666333908955784}} {"text": "/* specfunc/bessel_Jnu.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, 2017 Konrad Griessinger\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n#include \"bessel.h\"\n#include \"bessel_olver.h\"\n#include \"bessel_temme.h\"\n\n\n/* Evaluate at large enough nu to apply asymptotic\n * results and apply backward recurrence.\n */\n#if 0\nstatic\nint\nbessel_J_recur_asymp(const double nu, const double x,\n gsl_sf_result * Jnu, gsl_sf_result * Jnup1)\n{\n const double nu_cut = 25.0;\n int n;\n int steps = ceil(nu_cut - nu) + 1;\n\n gsl_sf_result r_Jnp1;\n gsl_sf_result r_Jn;\n int stat_O1 = gsl_sf_bessel_Jnu_asymp_Olver_e(nu + steps + 1.0, x, &r_Jnp1);\n int stat_O2 = gsl_sf_bessel_Jnu_asymp_Olver_e(nu + steps, x, &r_Jn);\n double r_fe = fabs(r_Jnp1.err/r_Jnp1.val) + fabs(r_Jn.err/r_Jn.val);\n double Jnp1 = r_Jnp1.val;\n double Jn = r_Jn.val;\n double Jnm1;\n double Jnp1_save;\n\n for(n=steps; n>0; n--) {\n Jnm1 = 2.0*(nu+n)/x * Jn - Jnp1;\n Jnp1 = Jn;\n Jnp1_save = Jn;\n Jn = Jnm1;\n }\n\n Jnu->val = Jn;\n Jnu->err = (r_fe + GSL_DBL_EPSILON * (steps + 1.0)) * fabs(Jn);\n Jnup1->val = Jnp1_save;\n Jnup1->err = (r_fe + GSL_DBL_EPSILON * (steps + 1.0)) * fabs(Jnp1_save);\n\n return GSL_ERROR_SELECT_2(stat_O1, stat_O2);\n}\n#endif\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_bessel_Jnupos_e(const double nu, const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n \n if(x == 0.0) {\n if(nu == 0.0) {\n result->val = 1.0;\n result->err = 0.0;\n }\n else {\n result->val = 0.0;\n result->err = 0.0;\n }\n return GSL_SUCCESS;\n }\n else if(x*x < 10.0*(nu+1.0)) {\n return gsl_sf_bessel_IJ_taylor_e(nu, x, -1, 100, GSL_DBL_EPSILON, result);\n }\n else if(nu > 50.0) {\n return gsl_sf_bessel_Jnu_asymp_Olver_e(nu, x, result);\n }\n else if(x > 1000.0)\n {\n /* We need this to avoid feeding large x to CF1; note that\n * due to the above check, we know that n <= 50. See similar\n * block in bessel_Jn.c.\n */\n return gsl_sf_bessel_Jnu_asympx_e(nu, x, result);\n }\n else {\n /* -1/2 <= mu <= 1/2 */\n int N = (int)(nu + 0.5);\n double mu = nu - N;\n\n /* Determine the J ratio at nu.\n */\n double Jnup1_Jnu;\n double sgn_Jnu;\n const int stat_CF1 = gsl_sf_bessel_J_CF1(nu, x, &Jnup1_Jnu, &sgn_Jnu);\n\n if(x < 2.0) {\n /* Determine Y_mu, Y_mup1 directly and recurse forward to nu.\n * Then use the CF1 information to solve for J_nu and J_nup1.\n */\n gsl_sf_result Y_mu, Y_mup1;\n const int stat_mu = gsl_sf_bessel_Y_temme(mu, x, &Y_mu, &Y_mup1);\n \n double Ynm1 = Y_mu.val;\n double Yn = Y_mup1.val;\n double Ynp1 = 0.0;\n int n;\n for(n=1; nval = 2.0/(M_PI*x) / (Jnup1_Jnu*Yn - Ynp1);\n result->err = GSL_DBL_EPSILON * (N + 2.0) * fabs(result->val);\n return GSL_ERROR_SELECT_2(stat_mu, stat_CF1);\n }\n else {\n /* Recurse backward from nu to mu, determining the J ratio\n * at mu. Use this together with a Steed method CF2 to\n * determine the actual J_mu, and thus obtain the normalization.\n */\n double Jmu;\n double Jmup1_Jmu;\n double sgn_Jmu;\n double Jmuprime_Jmu;\n double P, Q;\n const int stat_CF2 = gsl_sf_bessel_JY_steed_CF2(mu, x, &P, &Q);\n double gamma;\n \n double Jnp1 = sgn_Jnu * GSL_SQRT_DBL_MIN * Jnup1_Jnu;\n double Jn = sgn_Jnu * GSL_SQRT_DBL_MIN;\n double Jnm1;\n int n;\n for(n=N; n>0; n--) {\n Jnm1 = 2.0*(mu+n)/x * Jn - Jnp1;\n Jnp1 = Jn;\n Jn = Jnm1;\n }\n Jmup1_Jmu = Jnp1/Jn;\n sgn_Jmu = GSL_SIGN(Jn);\n Jmuprime_Jmu = mu/x - Jmup1_Jmu;\n\n gamma = (P - Jmuprime_Jmu)/Q;\n Jmu = sgn_Jmu * sqrt(2.0/(M_PI*x) / (Q + gamma*(P-Jmuprime_Jmu)));\n\n result->val = Jmu * (sgn_Jnu * GSL_SQRT_DBL_MIN) / Jn;\n result->err = 2.0 * GSL_DBL_EPSILON * (N + 2.0) * fabs(result->val);\n\n return GSL_ERROR_SELECT_2(stat_CF2, stat_CF1);\n }\n }\n}\n\nint\ngsl_sf_bessel_Jnu_e(const double nu, const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x <= 0.0) {\n DOMAIN_ERROR(result);\n }\n else if (nu < 0.0) {\n int Jstatus = gsl_sf_bessel_Jnupos_e(-nu, x, result);\n double Jval = result->val;\n double Jerr = result->err;\n int Ystatus = gsl_sf_bessel_Ynupos_e(-nu, x, result);\n double Yval = result->val;\n double Yerr = result->err;\n /* double s = sin(M_PI*nu), c = cos(M_PI*nu); */\n int sinstatus = gsl_sf_sin_pi_e(nu, result);\n double s = result->val;\n double serr = result->err;\n int cosstatus = gsl_sf_cos_pi_e(nu, result);\n double c = result->val;\n double cerr = result->err;\n result->val = s*Yval + c*Jval;\n result->err = fabs(c*Yerr) + fabs(s*Jerr) + fabs(cerr*Yval) + fabs(serr*Jval);\n return GSL_ERROR_SELECT_4(Jstatus, Ystatus, sinstatus, cosstatus);\n }\n else return gsl_sf_bessel_Jnupos_e(nu, x, result);\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_Jnu(const double nu, const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_Jnu_e(nu, x, &result));\n}\n", "meta": {"hexsha": "aa219bd914d95cf53c98bbfdc148050c5de846c9", "size": 6153, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/bessel_Jnu.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/specfunc/bessel_Jnu.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/specfunc/bessel_Jnu.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 28.8873239437, "max_line_length": 85, "alphanum_fraction": 0.6188850967, "num_tokens": 2135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4365667794125081}} {"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C code for the conversion between time scales.\n *\n * Formulas are taken from the UNITED STATES NAVAL OBSERVATORY CIRCULAR NO. 179 by George H. Kaplan\n * See http://aa.usno.navy.mil/publications/docs/Circular_179.php\n *\n */\n\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n#include \"timeconversion.h\"\n\n\n/***********************************************************/\n/********* Core functions to compute overlaps **************/\n\n/* Table of leap seconds - from LAL XLALLeapSeconds.h */\nstatic const struct leaps_table { double jd; int gpssec; int taiutc; } leaps[] =\n{\n {2444239.5, -43200, 19}, /* 1980-Jan-01 */\n {2444786.5, 46828800, 20}, /* 1981-Jul-01 */\n {2445151.5, 78364801, 21}, /* 1982-Jul-01 */\n {2445516.5, 109900802, 22}, /* 1983-Jul-01 */\n {2446247.5, 173059203, 23}, /* 1985-Jul-01 */\n {2447161.5, 252028804, 24}, /* 1988-Jan-01 */\n {2447892.5, 315187205, 25}, /* 1990-Jan-01 */\n {2448257.5, 346723206, 26}, /* 1991-Jan-01 */\n {2448804.5, 393984007, 27}, /* 1992-Jul-01 */\n {2449169.5, 425520008, 28}, /* 1993-Jul-01 */\n {2449534.5, 457056009, 29}, /* 1994-Jul-01 */\n {2450083.5, 504489610, 30}, /* 1996-Jan-01 */\n {2450630.5, 551750411, 31}, /* 1997-Jul-01 */\n {2451179.5, 599184012, 32}, /* 1999-Jan-01 */\n {2453736.5, 820108813, 33}, /* 2006-Jan-01 */\n {2454832.5, 914803214, 34}, /* 2009-Jan-01 */\n {2456109.5, 1025136015, 35}, /* 2012-Jul-01 */\n {2457204.5, 1119744016, 36} /* 2015-Jul-01 */\n};\nstatic const int numleaps = sizeof( leaps ) / sizeof( *leaps );\n\n/* Returns the leap seconds TAI-UTC at a given GPS second */\nstatic int leapseconds(const double gpstime)\n{\n int leap;\n\n if ( gpstime < leaps[0].gpssec )\n {\n printf( \"Error - Don't know leap seconds before GPS time %d\\n\", leaps[0].gpssec );\n exit(1);\n }\n\n /* scan leap second table and locate the appropriate interval */\n for ( leap = 1; leap < numleaps; ++leap )\n if ( gpstime < leaps[leap].gpssec )\n break;\n\n return leaps[leap-1].taiutc;\n}\n\n/***********************************************************/\n/********* Core functions to compute overlaps **************/\n\n/* Function computing the correction from the earth rotation angle to the gmst angle */\n/* Formula (2.12) of the USNO circular */\nstatic double gmst_correction(const double gpstime) /* gpstime in seconds */\n{\n /* T is the number of julian centuries since J2000.0 */\n double T = (gpstime - EPOCH_J2000_0_GPS)/(86400.0*36525.0);\n double correction = 2*PI*(0.014506 + 4612.156534*T + 1.3915817*T*T - 0.00000044*T*T*T - 0.000029956*T*T*T*T - 0.0000000368*T*T*T*T*T)/15.0/86400.0;\n return correction;\n}\n\n/* Earth rotation angle from the UT1 seconds elapsed since J2000.0 */\n/* Formula (2.11) of the USNO circular */\nstatic double era_angle_from_ut1(const double ut1_j2000) /* ut1_j2000 in seconds */\n{\n double DU = ut1_j2000/86400.0;\n double fracDU = DU - trunc(DU);\n double era_angle = 2*PI*(0.7790572732640 + 0.00273781191135448*DU + fracDU);\n return era_angle;\n}\n\n/* Function computing the gmst angle from the gps time */\n/* Formula (2.12) of the USNO circular */\ndouble gmst_angle_from_gpstime(const double gpstime) /* gpstime in seconds */\n{\n /* UTC time - UTC at J2000, computed from the GPS time */\n double utc_j2000 = (gpstime - EPOCH_J2000_0_GPS) - (leapseconds(gpstime) - EPOCH_J2000_0_TAI_UTC);\n\n /* Earth rotation angle */\n /* BEWARE: here we assimilate UTC and UT1 times - by construction, |UTC-UT1| < 1sec */\n double era_angle = era_angle_from_ut1(utc_j2000);\n\n /* GMST angle */\n double gmst_angle = era_angle + gmst_correction(gpstime);\n return gmst_angle;\n}\n\n\n\n\n", "meta": {"hexsha": "35ae512ebd09ab6ec05b3bdb912f78ce25e4d0f4", "size": 4105, "ext": "c", "lang": "C", "max_stars_repo_path": "tools/timeconversion.c", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "tools/timeconversion.c", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/timeconversion.c", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 31.8217054264, "max_line_length": 149, "alphanum_fraction": 0.6462850183, "num_tokens": 1359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.43636885505561884}} {"text": "/* \n * PARTICLE SWARM OPTIMIZATION\n * ===========================\n *\n * Author: Gabriel E Leventhal, 2011-12-02\n *\n * adapted from \n * Author: Tomas V. Arredondo\n * SimPSOLib: A simple yet flexible PSO implementation in C++.\n *\n */\n\n#ifndef __PSO_SWARM__\n#define __PSO_SWARM__\n\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#include \"GSLRng.h\"\n#include \n\n#include \"Particle.h\"\n#include \"Point.h\"\n#include \"Parameters.h\"\n#include \"Network.h\"\n\n#ifdef USE_MPI\n#include \"mpi.h\"\n#endif\n\nnamespace PSO {\n class Swarm {\n public:\n Swarm() {}\n\n Swarm(int size, int np, Parameters* pars) \n : swarmSize(size), numParams(np), numEvals(0), curIt(0),\n numInform(3), \n phiPi(np,2.5), phiPf(np,0.5), phiGi(np,0.5),phiGf(np,2.5),\n omegai(np,0.721), omegaf(np,0.721), p(pars),\n bestVal(-INFINITY), bestParticle(-1),\n mpi_type(0), mpi_rank(0), mpi_ntasks(1)\n {\n bestPos = Point(np,0.0);\n setInformants(numInform);\n }\n\n virtual ~Swarm() { destroy(); }\n\n inline void setMPI(int type) { mpi_type = (type >= 0) ? type : 0; }\n\n inline void setVars(const Point& pp, const Point& pg, const Point& o) {\n phiPi = pp; phiGi = pg; omegai = o;\n phiPf = pp; phiGf = pg; omegaf = o;\n phiP = pp; phiG = pg; omega = o;\n }\n\n inline void setInformants(int K) {\n numInform = (K > swarmSize-1) ? swarmSize-1 : K;\n links.resize(swarmSize);\n init_network();\n }\n\n double maximum_swarm_radius() const;\n double search_space_diameter() const;\n\n // get everything ready to go\n void begin(int argc, char* argv[]);\n // finish up stuff\n void end();\n\n void initialize(int type = 0);\n void display(ostream* out = &cout, string prefix = \"\");\n\n virtual void evaluate(int vflag = 0, ostream* out = NULL, ostream* hist = NULL);\n virtual double evaluateParticle(int j);\n\n void updateVelocity(int j, bool bestVals = true);\n void updateVelocity(bool bestVals = true);\n\n void updatePosition(int j);\n void updatePosition();\n\n void randomizeInf(int maxTries = 1000);\n void randomPosition(int j);\n\n virtual void run(int numIt, int slowdown = 0, int vflag = 0, \n ostream* out = NULL, ostream* hist = NULL);\n\n inline bool is_master() const { return (mpi_rank == 0); }\n\n inline void seed_rng(unsigned long seed) { rng.set(seed); }\n\n inline const Particle& at(size_t i) const { return *swarm[i]; }\n inline Particle best() const { return *swarm[bestParticle]; }\n\n inline double fitness(int i) const { return swarm.at(i)->fitness(); }\n\n inline int size() const { return swarmSize; }\n\n inline int nextIt() { return ++curIt; }\n inline void setIt(int i) { curIt = i; }\n\n double mean(int i) const;\n double var(int i) const;\n Point mean() const;\n Point var() const;\n\n#ifdef USE_MPI\n virtual void evaluate_slave();\n void run_mpi(int numInt, int vflag = 0, ostream* out = NULL, ostream* hist = NULL);\n virtual void run_master(int numInt, int vflag, ostream* out, ostream* hist);\n inline void evaluate_master(int vflag = 0) { run_master(-1,vflag,NULL,NULL); }\n#endif\n\n protected:\n void create();\n void destroy();\n\n void init_network();\n int find_best();\n\n int swarmSize; /* swarm size */\n vector swarm; /* swarm */\n int numParams; /* number of parameters */\n int numEvals; /* current number of function evaluations */\n int curIt; /* current swarm iteration */\n\n int numInform; /* number of informants */\n Network links; /* information network */\n\n Point phiP;\n Point phiG;\n Point omega;\n Point phiPi; /* phiP initial */\n Point phiPf; /* phiP final */\n Point phiGi; /* phiG initial */\n Point phiGf; /* phiG final */\n Point omegai; /* omega initial */\n Point omegaf; /* omega final */\n\n Parameters* p;\n\n double bestVal; /* current best value */\n Point bestPos; /* current best position */\n int bestParticle;\n\n myGSL::Rng rng;\n\n int mpi_type;\n int mpi_rank;\n int mpi_ntasks;\n };\n}\n\n#endif // __PSO_SWARM__\n", "meta": {"hexsha": "26d6a2f301cf2843ea6fc8a7ef7ae7de8c2e8660", "size": 4746, "ext": "h", "lang": "C", "max_stars_repo_path": "Swarm.h", "max_stars_repo_name": "marieberth/tiff_opt", "max_stars_repo_head_hexsha": "9c831df9bdcd2eb9890a4d12c47f1935e53a7062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2016-11-28T07:13:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T11:02:58.000Z", "max_issues_repo_path": "Swarm.h", "max_issues_repo_name": "marieberth/tiff_opt", "max_issues_repo_head_hexsha": "9c831df9bdcd2eb9890a4d12c47f1935e53a7062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Swarm.h", "max_forks_repo_name": "marieberth/tiff_opt", "max_forks_repo_head_hexsha": "9c831df9bdcd2eb9890a4d12c47f1935e53a7062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-11-11T13:00:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T09:34:55.000Z", "avg_line_length": 29.2962962963, "max_line_length": 92, "alphanum_fraction": 0.5478297514, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.4361090509559389}} {"text": "/* -*- mode: C; c-basic-offset: 4 -*- */\n/* ex: set shiftwidth=4 tabstop=4 expandtab: */\n/*\n * Copyright (c) 2011, Georgia Tech Research Corporation\n * All rights reserved.\n *\n * Author(s): Neil T. Dantam \n * Georgia Tech Humanoid Robotics Lab\n * Under Direction of Prof. Mike Stilman \n *\n *\n * This file is provided under the following \"BSD-style\" License:\n *\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n * CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n\n#include \n#include \n#include \"reflex.h\"\n\n#define SYMM_PART CblasUpper\n#define SYMM_PARTC \"U\"\n\nAA_API void rfx_lqg_kf_predict_cov( size_t n, const double *A, const double *V, double *P )\n{\n // P = A * P * A**T + V\n int ni = (int)n;\n double *T = (double*)aa_mem_region_local_tmpalloc( 2 * n*n * sizeof(P[0]) );\n\n // T := A*P\n cblas_dsymm( CblasColMajor, CblasRight, SYMM_PART,\n ni, ni,\n 1.0, P, ni,\n A, ni,\n 0.0, T, ni );\n\n // P := (A*P) * A**T + V\n dlacpy_( SYMM_PARTC, &ni, &ni,\n V, &ni,\n P, &ni );\n cblas_dgemm( CblasColMajor, CblasNoTrans, CblasTrans,\n ni, ni, ni,\n 1.0, T, ni,\n A, ni,\n 1.0, P, ni );\n}\n\nint rfx_lqg_kf_correct_gain\n( size_t n_x, size_t n_z, const double *C, const double *P, const double *W, double *K )\n{\n int nxi = (int)n_x;\n int nzi = (int)n_z;\n\n double *ptr = (double*) aa_mem_region_local_alloc( sizeof(ptr[0]) *\n (n_z*n_x + n_z*n_z) );\n\n double *CP = ptr;\n double *Kp = &ptr[n_z*n_x];\n\n // P is symmetric, so P*C^T == (C*P^T)^T == (C*P)^T\n\n // Kp := C * P * C**T + W = C*(C*P)^T\n // Kp^T := C*(C * P)^T\n cblas_dsymm( CblasColMajor, CblasRight, SYMM_PART,\n nzi, nxi,\n 1.0, P, nxi,\n C, nzi,\n 0.0, CP, nzi );\n\n dlacpy_( SYMM_PARTC, &nzi, &nzi,\n W, &nzi,\n Kp, &nzi );\n cblas_dgemm( CblasColMajor, CblasNoTrans, CblasTrans,\n nzi, nzi, nxi,\n 1.0, C, nzi,\n CP, nzi,\n 1.0, Kp, nzi );\n\n // K := P * C**T * Kp^-1\n // K Kp := P * C**T\n // CP = Kp^T K^T\n // Kp is symmetric\n // CP = Kp K^T\n int info;\n\n // Cholesky\n dpotrf_( SYMM_PARTC, &nzi,\n Kp, &nzi,\n &info );\n\n // Solve it!\n dpotrs_( SYMM_PARTC, &nzi, &nxi,\n Kp, &nzi,\n CP, &nzi,\n &info );\n\n // Transpose\n for( size_t j = 0; j < n_z; j ++ )\n for( size_t i = 0; i < n_x; i ++ )\n K[j*n_x+i] = CP[i*n_z+j];\n\n int i = 0;\n\n return i;\n}\n\nvoid rfx_lqg_kf_correct_cov\n( size_t n_x, size_t n_z, const double *C, double *P, double *K )\n{\n int nxi = (int)n_x;\n int nzi = (int)n_z;\n\n double *ptr = (double*)aa_mem_region_local_tmpalloc( 2 * n_x*n_x * sizeof(P[0]) );\n double *KC = ptr;\n double *P1 = &ptr[n_x*n_x];\n\n // P := (I - K*C) * P\n cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,\n nxi, nxi, nzi,\n -1.0, K, nxi,\n C, nzi,\n 0.0, KC, nxi );\n // KC += I\n for( size_t i = 0; i < n_x*n_x; i = i + n_x + 1 )\n KC[i] += 1;\n\n cblas_dsymm( CblasColMajor, CblasRight, SYMM_PART,\n nxi, nxi,\n 1.0, P, nxi,\n KC, nxi,\n 0.0, P1, nxi );\n dlacpy_( SYMM_PARTC, &nxi, &nxi, P1, &nxi, P, &nxi );\n}\n\n\nint rfx_lqg_ekf_predict\n( void *cx, size_t n_x, double *x, const double *u, double *P, const double *V,\n rfx_lqg_ekf_process_fun process )\n{\n double F[n_x*n_x];\n int i = process( cx, x, u, F );\n rfx_lqg_kf_predict_cov( n_x, F, V, P );\n return i;\n}\n\n\nint rfx_lqg_ekf_correct\n( void *cx, size_t n_x, size_t n_z, double *x, const double *z, double *P, const double *W,\n rfx_lqg_ekf_measure_fun measure, rfx_lqg_ekf_innovate_fun innovate, rfx_lqg_ekf_update_fun update )\n{\n int i;\n\n double H[n_z*n_x];\n double K[n_x*n_z];\n {\n double y[n_z];\n i = measure(cx, x, y, H);\n if(i) return i;\n\n i = rfx_lqg_kf_correct_gain( n_x, n_z, H, P, W, K );\n if(i) return i;\n\n i = innovate(cx, x, z, y);\n if(i) return i;\n\n {\n double Ky[n_x];\n cblas_dgemv( CblasColMajor, CblasNoTrans,\n (int)n_x, (int)n_z,\n 1.0, K, (int)n_x,\n y, 1,\n 0.0, Ky, 1 );\n\n i = update(cx, x, Ky);\n }\n }\n\n rfx_lqg_kf_correct_cov( n_x, n_z, H, P, K );\n\n return i;\n}\n\n\n\n\n\nAA_API void rfx_lqg_init( rfx_lqg_t *lqg, size_t n_x, size_t n_u, size_t n_z ) {\n memset( lqg, 0, sizeof(*lqg) );\n lqg->n_x = n_x;\n lqg->n_u = n_u;\n lqg->n_z = n_z;\n\n lqg->x = AA_NEW0_AR( double, lqg->n_x );\n lqg->u = AA_NEW0_AR( double, lqg->n_u );\n lqg->z = AA_NEW0_AR( double, lqg->n_z );\n\n lqg->A = AA_NEW0_AR( double, lqg->n_x * lqg->n_x );\n lqg->B = AA_NEW0_AR( double, lqg->n_x * lqg->n_u );\n lqg->C = AA_NEW0_AR( double, lqg->n_z * lqg->n_x );\n\n lqg->P = AA_NEW0_AR( double, lqg->n_x * lqg->n_x );\n lqg->V = AA_NEW0_AR( double, lqg->n_x * lqg->n_x );\n lqg->W = AA_NEW0_AR( double, lqg->n_z * lqg->n_z );\n\n lqg->Q = AA_NEW0_AR( double, lqg->n_x * lqg->n_x );\n lqg->R = AA_NEW0_AR( double, lqg->n_u * lqg->n_u );\n\n lqg->K = AA_NEW0_AR( double, lqg->n_z * lqg->n_x );\n lqg->L = AA_NEW0_AR( double, lqg->n_u * lqg->n_x );\n\n}\nAA_API void rfx_lqg_destroy( rfx_lqg_t *lqg ) {\n\n free(lqg->x);\n free(lqg->u);\n free(lqg->z);\n\n free(lqg->A);\n free(lqg->B);\n free(lqg->C);\n\n free(lqg->Q);\n free(lqg->R);\n\n free(lqg->L);\n free(lqg->K);\n\n\n}\n\n\n\n/*\n * X = op(A)*op(B)*op(C) + beta*X\n *\n * m*n = (m*k) * (k*n)\n *\n * X: m*n\n * op(A): m*k\n * op(B): k*p\n * op(C): p*n\n */\n\nstatic inline void matmul3( size_t m, size_t n, size_t k, size_t p,\n enum CBLAS_TRANSPOSE transA,\n enum CBLAS_TRANSPOSE transB,\n enum CBLAS_TRANSPOSE transC,\n const double *A, size_t lda,\n const double *B, size_t ldb,\n const double *C, size_t ldc,\n double beta, double *X, size_t ldx) {\n double T[m*p];\n // T := A*B\n cblas_dgemm( CblasColMajor, transA, transB,\n (int)m, (int)p, (int)k,\n 1.0, A, (int)lda,\n B, (int)ldb,\n 0.0, T, (int)m );\n\n // X := (A*B) * C + beta*X\n cblas_dgemm( CblasColMajor, CblasNoTrans, transC,\n (int)m, (int)n, (int)p,\n 1.0, T, (int)m,\n C, (int)ldc,\n beta, X, (int)ldx );\n}\n\nstatic void kf_innovate( rfx_lqg_t *lqg, double *xh ) {\n\n // xh = x + K * (z - C*x)\n\n // T := z - C*x\n double T[lqg->n_z];\n memcpy(T, lqg->z, sizeof(T));\n cblas_dgemv( CblasColMajor, CblasNoTrans,\n (int)lqg->n_z, (int)lqg->n_x,\n -1.0, lqg->C, (int)lqg->n_z,\n lqg->x, 1,\n 1.0, T, 1 );\n // xh = K * (z - C*x) + xh\n cblas_dgemv( CblasColMajor, CblasNoTrans,\n (int)lqg->n_x, (int)lqg->n_z,\n 1.0, lqg->K, (int)lqg->n_x,\n T, 1,\n 1.0, xh, 1 );\n}\n\nAA_API void rfx_lqg_kf_predict( rfx_lqg_t *lqg ) {\n // x = A*x + B*u\n {\n double x[lqg->n_x];\n aa_lsim_dstep( lqg->n_x, lqg->n_u,\n lqg->A, lqg->B,\n lqg->x, lqg->u,\n x );\n memcpy(lqg->x, x, sizeof(x));\n }\n // P = A * P * A**T + V\n rfx_lqg_kf_predict_cov( lqg->n_x, lqg->A, lqg->V, lqg->P );\n}\n\nAA_API void rfx_lqg_kf_correct( rfx_lqg_t *lqg ) {\n\n rfx_lqg_kf_correct_gain( lqg->n_x, lqg->n_z,\n lqg->C, lqg->P, lqg->W, lqg->K );\n\n // x = x + K * (z - C*x)\n kf_innovate( lqg, lqg->x );\n\n // P = (I - K*C) * P\n rfx_lqg_kf_correct_cov( lqg->n_x, lqg->n_z,\n lqg->C, lqg->P, lqg->K );\n}\n\n// kalman-bucy gain\nvoid rfx_lqg_kbf_gain( rfx_lqg_t *lqg )\n{\n rfx_lqg_kbf_gain_work( lqg->n_x, lqg->n_z,\n lqg->A, lqg->C, lqg->V, lqg->W, lqg->P, lqg->K );\n}\n\n\n// kalman-bucy gain\nvoid rfx_lqg_kbf_gain_work\n( size_t n_x, size_t n_z,\n const double *A, const double *C, const double *V, const double *W, double *P, double *K )\n{\n // dP = A*P + P*A' - P*C'*W^{-1}*C*P + V\n // K = P * C' * W^{-1}\n\n double Winv[n_z*n_z];\n memcpy(Winv, W, sizeof(Winv));\n aa_la_inv( n_z, Winv);\n\n {\n double ric_B[n_x*n_x];\n\n // ric_B := C' * W^{-1} * C\n matmul3( n_x, n_x, n_z, n_z,\n CblasTrans, CblasNoTrans, CblasNoTrans,\n C, n_z,\n Winv, n_z,\n C, n_z,\n 0.0, ric_B, n_x );\n\n double ric_A[n_x*n_x];\n aa_la_transpose2(n_x, n_x, A, ric_A );\n\n // solve ARE with dP = 0, result is P\n //aa_tick(\"laub: \");\n aa_la_care_laub( n_x, n_x, n_x,\n ric_A, ric_B, V, P );\n //aa_tock();\n }\n\n // K = P * C' * W^{-1}\n matmul3( n_x, n_z, n_x, n_z,\n CblasNoTrans, CblasTrans, CblasNoTrans,\n P, n_x,\n C, n_z,\n Winv, n_z,\n 0.0, K, n_x );\n\n}\n\n\nvoid rfx_lqg_lqr_gain( rfx_lqg_t *lqg ) {\n // A'*S + S*A - S*B*R^{-1}*B'*S + Q = 0\n\n double Rinv[lqg->n_u*lqg->n_u];\n memcpy(Rinv, lqg->R, sizeof(Rinv));\n aa_la_inv( lqg->n_u, Rinv);\n\n double S[lqg->n_x*lqg->n_x];\n {\n double ric_B[lqg->n_x*lqg->n_x];\n\n // ric_B := B * R^{-1} * B'\n matmul3( lqg->n_x, lqg->n_x, lqg->n_u, lqg->n_u,\n CblasNoTrans, CblasNoTrans, CblasTrans,\n lqg->B, lqg->n_x,\n Rinv, lqg->n_u,\n lqg->B, lqg->n_x,\n 0.0, ric_B, lqg->n_x );\n\n // solve ARE with dS = 0, result is S\n aa_la_care_laub( lqg->n_x, lqg->n_x, lqg->n_x,\n lqg->A, ric_B, lqg->Q, S );\n }\n\n // L = R^{-1}*B'*S\n matmul3( lqg->n_u, lqg->n_x, lqg->n_u, lqg->n_x,\n CblasNoTrans, CblasTrans, CblasNoTrans,\n Rinv, lqg->n_u,\n lqg->B, lqg->n_x,\n S, lqg->n_x,\n 0.0, lqg->L, lqg->n_u );\n}\n\n\nstatic void kbf_step_fun( const void *cx,\n double t, const double *restrict x,\n double *restrict dx ) {\n // dx = A*x + B*u + K(z-Cx)\n (void)t;\n rfx_lqg_t *lqg = (rfx_lqg_t*)cx;\n\n // dx := A*x + B*u\n aa_lsim_dstep( lqg->n_x, lqg->n_u,\n lqg->A, lqg->B,\n x, lqg->u,\n dx );\n // dx := K * (z - C*x) + dx\n kf_innovate( lqg, dx );\n}\n\n\nvoid rfx_lqg_kbf_step1( rfx_lqg_t *lqg, double dt ) {\n // dx = A*x + B*u + K(z-Cx)\n double dx[lqg->n_x];\n kbf_step_fun( lqg, 0, lqg->x, dx );\n\n // x := dt*dx + x\n cblas_daxpy( (int)lqg->n_x, dt, dx, 1, lqg->x, 1 );\n}\n\n\nvoid rfx_lqg_kbf_step4( rfx_lqg_t *lqg, double dt ) {\n double x1[lqg->n_x];\n // runge-kutta 4\n aa_odestep_rk4( lqg->n_x, kbf_step_fun, lqg,\n 0, dt, lqg->x, x1 );\n memcpy( lqg->x, x1, sizeof(x1) );\n}\n\n\n\nAA_API void rfx_lqg_lqr_ctrl( rfx_lqg_t *lqg ) {\n cblas_dgemv( CblasColMajor, CblasNoTrans,\n (int)lqg->n_u, (int)lqg->n_x,\n -1.0, lqg->L, (int)lqg->n_u,\n lqg->x, 1,\n 0.0, lqg->u, 1 );\n}\n\nvoid rfx_lqg_sys( const void *cx,\n double t, const double *restrict x,\n double *restrict dx ) {\n rfx_lqg_t * lqg = (rfx_lqg_t*)cx;\n (void)t;\n aa_lsim_dstep( lqg->n_x, lqg->n_u,\n lqg->A, lqg->B,\n x, lqg->u,\n dx );\n}\n\n//AA_API void rfx_lqg_observe_euler( rfx_lqg_t *lqg, double dt, aa_mem_region_t *reg ) {\n // --- calculate kalman gain ---\n\n\n // --- predict from previous input ---\n // dx = A*x + B*u + K * ( z - C*xh )\n //double *dx = (double*)aa_mem_region_alloc(reg, sizeof(double)*lqg->n_x);\n // zz := z\n //double *zz = (double*)aa_mem_region_alloc(reg, sizeof(double)*lqg->n_z);\n\n\n // x = x + dx * dt\n //aa_la_axpy( lqg->n_x, dt, dx, lqg->x );\n//}\n\n//AA_API void rfx_lqg_ctrl( rfx_lqg_t *lqg, double dt, aa_mem_region_t *reg ) {\n // compute optimal gain\n // -dS = A'*S + S*A - S*B*R^{-1}*B' + Q\n // solve ARE, result is S\n // L = R^{-1} * B' * S : (nu*nu) * (nu*nx) * (nx*nx)\n\n // compute current input\n // u = -Lx\n//}\n\n/* int rfx_lqg_duqu_predict */\n/* ( double dt, double *S, double *dx, double *P, const double *V ) */\n/* { */\n/* return 0; */\n/* } */\n", "meta": {"hexsha": "05377a441dd0bd8a1a6d9aa14ce81b18c0d5482a", "size": 14158, "ext": "c", "lang": "C", "max_stars_repo_path": "src/lqg/lqg.c", "max_stars_repo_name": "golems/reflex", "max_stars_repo_head_hexsha": "a6df1ee7f101a1545186997401b200bbbbebcc64", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-11-29T02:12:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T10:12:01.000Z", "max_issues_repo_path": "src/lqg/lqg.c", "max_issues_repo_name": "golems/reflex", "max_issues_repo_head_hexsha": "a6df1ee7f101a1545186997401b200bbbbebcc64", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lqg/lqg.c", "max_forks_repo_name": "golems/reflex", "max_forks_repo_head_hexsha": "a6df1ee7f101a1545186997401b200bbbbebcc64", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-03-23T18:09:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-05T12:58:33.000Z", "avg_line_length": 27.5447470817, "max_line_length": 101, "alphanum_fraction": 0.5015538918, "num_tokens": 5140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.43588063667779087}} {"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file rk_2_2.c\n * \\brief Source file to optimize Runge-Kutta 3 steps 2nd order methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"rk.h\"\n#include \"rk_2_2.h\"\n\n#define DEBUG_RK_2_2 0 ///< macro to debug.\n\n/**\n * Function to obtain the coefficients of a 2 steps 2nd order Runge-Kutta \n * method.\n */\nint\nrk_tb_2_2 (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb, *r;\n#if DEBUG_RK_2_2\n fprintf (stderr, \"rk_tb_2_2: start\\n\");\n#endif\n tb = optimize->coefficient;\n r = optimize->random_data;\n t2 (tb) = 1.L;\n t1 (tb) = r[0];\n b21 (tb) = 0.5L / t1 (tb);\n rk_b_2 (tb);\n#if DEBUG_RK_2_2\n rk_print_tb (optimize, \"rk_tb_2_2\", stderr);\n fprintf (stderr, \"rk_tb_2_2: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 2 steps 2nd order, 3rd order in\n * equations depending only in time, Runge-Kutta method.\n */\nint\nrk_tb_2_2t (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb;\n#if DEBUG_RK_2_2\n fprintf (stderr, \"rk_tb_2_2t: start\\n\");\n#endif\n tb = optimize->coefficient;\n t2 (tb) = 1.L;\n t1 (tb) = 2.L / 3.L;\n b21 (tb) = 0.5L / t1 (tb);\n rk_b_2 (tb);\n#if DEBUG_RK_2_2\n rk_print_tb (optimize, \"rk_tb_2_2t\", stderr);\n fprintf (stderr, \"rk_tb_2_2t: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 2 steps 1st-2nd order Runge-Kutta \n * pair.\n */\nint\nrk_tb_2_2p (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb;\n#if DEBUG_RK_2_2\n fprintf (stderr, \"rk_tb_2_2p: start\\n\");\n#endif\n if (!rk_tb_2_2 (optimize))\n return 0;\n tb = optimize->coefficient;\n e20 (tb) = 1.L;\n#if DEBUG_RK_2_2\n rk_print_tb (optimize, \"rk_tb_2_2p\", stderr);\n fprintf (stderr, \"rk_tb_2_2p: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 2 steps 1st-2nd order, 1st-3rd order\n * in equations depending only on time, Runge-Kutta pair.\n */\nint\nrk_tb_2_2tp (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb;\n#if DEBUG_RK_2_2\n fprintf (stderr, \"rk_tb_2_2tp: start\\n\");\n#endif\n if (!rk_tb_2_2t (optimize))\n return 0;\n tb = optimize->coefficient;\n e20 (tb) = 1.L;\n#if DEBUG_RK_2_2\n rk_print_tb (optimize, \"rk_tb_2_2tp\", stderr);\n fprintf (stderr, \"rk_tb_2_2tp: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to calculate the objective function of a 2 steps 2nd order \n * Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_2_2 (RK * rk) ///< RK struct.\n{\n long double *tb;\n long double o;\n#if DEBUG_RK_2_2\n fprintf (stderr, \"rk_objective_tb_2_2: start\\n\");\n#endif\n tb = rk->tb->coefficient;\n if (b20 (tb) < 0.L)\n {\n o = 40.L - b20 (tb);\n goto end;\n }\n o = 30.L + fmaxl (1.L, t1 (tb));\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\nend:\n#if DEBUG_RK_2_2\n fprintf (stderr, \"rk_objective_tb_2_2: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_2_2: end\\n\");\n#endif\n return o;\n}\n\n/**\n * Function to calculate the objective function of a 2 steps 2nd order, 3rd \n * order in equations depending only in time, Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_2_2t (RK * rk) ///< RK struct.\n{\n long double o;\n#if DEBUG_RK_2_2\n fprintf (stderr, \"rk_objective_tb_2_2t: start\\n\");\n#endif\n o = 31.L;\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\n#if DEBUG_RK_2_2\n fprintf (stderr, \"rk_objective_tb_2_2t: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_2_2t: end\\n\");\n#endif\n return o;\n}\n", "meta": {"hexsha": "ff34ebca611c33bbf842bfb10fdf245d06312d13", "size": 5169, "ext": "c", "lang": "C", "max_stars_repo_path": "rk_2_2.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rk_2_2.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rk_2_2.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9748743719, "max_line_length": 80, "alphanum_fraction": 0.6931708261, "num_tokens": 1646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.43575632393604385}} {"text": "#ifndef libCV_ellipse\n#define libCV_ellipse\n\n#include \n#include \"cvtypes.h\"\n#include \"util.h\"\n#include \"Array.h\"\n#include \"math.h\"\n#include \n#include \n#include \n#include \n\n@interface Ellipse : Object {\n\t\n\tf64 x_axis;\n\tf64 y_axis;\n\tf64 x_center;\n\tf64 y_center;\n\tf64 rotation;\n\t\n\tf64 general[6];\n\t\n\tf64 bounds[4];\n\t\n}\n\n+(id) newAtX:(f64)xc andY:(f64)yc withXAxis:(f64)xa andYAxis:(f64)ya rotatedBy:(f64)phi;\n+(id) newWithA:(f64)a b:(f64)b c:(f64)c d:(f64)d e:(f64)e f:(f64)f;\n\n+(id) newFromPoints:(ArrayP)points;\n\n-(void) drawInArray:(ArrayP)array;\n\n-(void) toGeneralConic;\n-(void) toGeneralEllipse;\n-(void) findBounds;\n\n// Get and set general ellipse parameters\n\n-(f64) x_axis;\n-(f64) y_axis;\n-(f64) major_axis;\n-(f64) minor_axis;\n-(f64) rotation;\n-(f64) majorRotation;\n-(f64) minorRotation;\n-(f64) x_center;\n-(f64) y_center;\n\n-(void) setX_axis:(f64)newx;\n-(void) setY_axis:(f64)newy;\n-(void) setX_center:(f64)newx;\n-(void) setY_center:(f64)newy;\n-(void) setRotation:(f64)newr;\n-(void) setX_axis:(f64)xa y_axis:(f64)ya x_center:(f64)xc y_center:(f64)yc rotation:(f64)r;\n\n// Get and set general conic parameters\n\n-(f64) A;\n-(f64) B;\n-(f64) C;\n-(f64) D;\n-(f64) E;\n-(f64) F;\n\n-(f64 *) general;\n\n-(void) setA:(f64)A;\n-(void) setB:(f64)B;\n-(void) setC:(f64)C;\n-(void) setD:(f64)D;\n-(void) setE:(f64)E;\n-(void) setF:(f64)F;\n-(void) setGeneralA:(f64)A B:(f64)B C:(f64)C D:(f64)D E:(f64)E F:(f64)F;\n\n-(void) printInfoTo:(FILE *)fp;\n\n-(u08) isValid;\n-(id) free;\n\n@end\n\nenum ellipseindices {\n\tAX,\n\tBX,\n\tCX,\n\tDX,\n\tEX,\n\tFX,\n};\n\nenum ellipsebounds {\n\tXHI,\n\tXLO,\n\tYHI,\n\tYLO,\n};\n\ntypedef Ellipse * EllipseP;\n\nvoid originCenteredLSQEllipse( f64 x_values[], f64 y_values[], u64 number_of_points, f64 ellipse[] );\nvoid generateBoundEllipses( f64 e[], f64 b1[], f64 b2[], f64 treshold );\nf64 ellipseCircumference( f64 e[] );\nEllipseP ellipseRANSAC( ArrayP edges, f64 fit_treshold, f64 min_percent_inliers, f64 certainty_probability, u64 max_iterations );\n\n#endif\n", "meta": {"hexsha": "ead855260ec2c6946884f0abd7086eb3f080c88e", "size": 2025, "ext": "h", "lang": "C", "max_stars_repo_path": "programs/ace2/Ellipse.h", "max_stars_repo_name": "leschzinerlab/myami-3.2-freeHand", "max_stars_repo_head_hexsha": "974b8a48245222de0d9cfb0f433533487ecce60d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "programs/ace2/Ellipse.h", "max_issues_repo_name": "leschzinerlab/myami-3.2-freeHand", "max_issues_repo_head_hexsha": "974b8a48245222de0d9cfb0f433533487ecce60d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "programs/ace2/Ellipse.h", "max_forks_repo_name": "leschzinerlab/myami-3.2-freeHand", "max_forks_repo_head_hexsha": "974b8a48245222de0d9cfb0f433533487ecce60d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-05T20:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-05T20:58:37.000Z", "avg_line_length": 18.75, "max_line_length": 129, "alphanum_fraction": 0.68, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.43553467427534476}} {"text": "#include \n#include \n#include \n#include \n#include \n#define COMPEARTH_PRIVATE_CROSS3 1\n#define COMPEARTH_PRIVATE_NORM3 1\n#define COMPEARTH_PRIVATE_DOT3 1\n#define COMPEARTH_PRIVATE_WRAP360 1\n#include \"compearth.h\"\n#ifdef COMPEARTH_USE_MKL\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#pragma clang diagnostic ignored \"-Wstrict-prototypes\"\n#endif\n#include \n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include \n#endif\n\n//#define MAXMT 64\n\nstatic void setZero(const int nmt, const double tol, double *__restrict__ X);\nstatic void faultVec2Ang(const double *__restrict__ S,\n const double *__restrict__ N,\n double *theta, double *sigma,\n double *kappa, double *__restrict__ K, int *ierr);\nstatic int pickP1(const double thetaA, const double sigmaA, const double kappaA,\n const double thetaB, const double sigmaB, const double kappaB,\n const double tol, const int p1, const int p2);\n\n/*!\n * @brief Converts a moment tensor to six parameters of Tape and Tape 2012.\n * The reverse program is TT2CMT.c\n *\n * @param[in] nmt Number of moment tensors.\n * @param[in] Min [6 x nmt] array of moment tensors in CMT\n * convention (i.e. UP-SOUTH-EAST). M is packed:\n * \\f$\n * M = \\{ M_{rr}, M_{\\theta \\theta}, M_{\\phi \\phi}\n * M_{r \\theta}, M_{r \\phi}, M_{\\theta \\phi} \\}\n * \\f$.\n * The leading dimension is 6.\n * @param[in] ldisplay If true then display the results. \\n\n * Otherwise, this routine will be quiet unless\n * an error is encountered.\n * \n * @param[out] gamma Angle from DC meridian to MT point.\n * Note that \\f$ \\gamma \\in [-30, 30] \\f$. \n * This is an array of dimension [nmt].\n * @param[out] delta Angle from deviatoric plane to MT point.\n * Note that \\f$ \\delta \\in [-90, 90] \\f$.\n * This is an array of dimension [nmt].\n * @param[out] M0 Seismic moment in N-m. This is an array of\n * dimension [nmt].\n * @param[out] kappa Strike angle \\f$ \\kappa \\in [0,360] \\f$.\n * This is an array of dimension [nmt].\n * @param[out] theta Dip angle \\f$ \\theta \\in [0,90] \\f$.\n * This is an array of dimension [nmt].\n * @param[out] sigma Slip (or rake) angle \\f$ \\sigma \\in [-90,90] \\f$.\n * This is an array of dimension [nmt].\n * @param[out] K If K is not NULL then it is the strike vector\n * (SOUTH-EAST-UP). In this case K is an array\n * of dimension [3 x nmt] with leading dimension 3.\n * @param[out] N If N is not NULL then it is the normal vector\n * (SOUTH-EAST-UP). In this case N is an array\n * of dimension [3 x nmt] with leading dimension 3.\n * @param[out] S If S Is not NULL then it is the slip vector\n * (SOUTH-EAST-UP). In this case S is an array\n * of dimension [3 x nmt] with leading dimension 3.\n * @param[out] thetadc If thetadc is not NULL then it is angle between \n * the moment tensor and the double couple where\n * \\f$ \\theta_{DC} \\in [0,90] \\f$.\n * In this case thetadc is an array of dimension [nmt].\n * @param[out] lam If lam is not NULL then these are the eigenvalues\n * corresponding to the moment tensor. In this\n * case lam is an array of dimension [3 x nmt] \n * with leading dimension 3.\n * @param[out] U If U is not NULL then this is the basis in \n * SOUTH-EAST-UP for the moment tensor. In this\n * case U an array of dimension [3 x 3 x nmt] with\n * leading dimension 9 and the understanding that\n * each 3 x 3 matrix is in column major format.\n *\n * @result 0 indicates success.\n *\n * @author Carl Tape and translated to C by Ben Baker\n *\n * @date July 2017\n * \n * @copyright MIT\n * \n */\nint compearth_CMT2TT(const int nmt, const double *__restrict__ Min,\n const bool ldisplay,\n double *__restrict__ gamma,\n double *__restrict__ delta,\n double *__restrict__ M0,\n double *__restrict__ kappa,\n double *__restrict__ theta,\n double *__restrict__ sigma,\n double *__restrict__ K, double *__restrict__ N,\n double *__restrict__ S, double *__restrict__ thetadc,\n double *__restrict__ lam, double *__restrict__ U)\n{\n double *lamdev, *lamiso, Vwork[9], Yrot[9], M[6],\n Sloc[12], Kloc[12], Nloc[12], kappaL[4], sigmaL[4], thetaL[4];\n double *thetadcWork;\n double Uwork[9*CE_CHUNKSIZE] __attribute__((aligned(64)));\n double lamWork[3*CE_CHUNKSIZE] __attribute__((aligned(64)));\n double Nwork[3*CE_CHUNKSIZE] __attribute__((aligned(64)));\n double Swork[3*CE_CHUNKSIZE] __attribute__((aligned(64)));\n //double lamSpace[3*MAXMT];\n //double uSpace[9*MAXMT];\n bool lwantLam, lwantK, lwantN, lwantS, lwantU;\n int itemp[4], ierr, ierrAll, match, imt, j, jmt, nmtLoc, nMatch;\n const int isort = 1;\n const double rotAngle = 45.0;\n const double tol = 1.e-6;\n ierr = 0;\n if (nmt < 1 || Min == NULL || gamma == NULL || delta == NULL ||\n M0 == NULL || kappa == NULL || theta == NULL || sigma == NULL)\n {\n if (nmt < 1){fprintf(stderr, \"%s: No moment tensors\\n\", __func__);}\n if (Min == NULL){fprintf(stderr, \"%s: Min is NULL\\n\", __func__);}\n if (gamma == NULL){fprintf(stderr, \"%s: gamma is NULL\\n\", __func__);}\n if (delta == NULL){fprintf(stderr, \"%s: delta is NULL\\n\", __func__);}\n if (M0 == NULL){fprintf(stderr, \"%s: M0 is NULL\\n\", __func__);}\n if (kappa == NULL){fprintf(stderr, \"%s: kappa is NULL\\n\", __func__);}\n if (theta == NULL){fprintf(stderr, \"%s: theta is NULL\\n\", __func__);}\n if (sigma == NULL){fprintf(stderr, \"%s: sigma is NULL\\n\", __func__);}\n return -1; \n }\n // Determine if eigenvalue/eigenvector decomposition is requested\n lwantLam = false;\n if (lam != NULL){lwantLam = true;}\n lwantU = false;\n if (U != NULL){lwantU = true;}\n // Determine the desired fault vectors\n lwantK = false;\n lwantN = false;\n lwantS = false;\n if (K != NULL){lwantK = true;}\n if (N != NULL){lwantN = true;}\n if (S != NULL){lwantS = true;} \n // Loop on moment tensor chunks\n for (jmt=0; jmt U will be with respect to this basis (from CMTdecom.m)\n // ierr = compearth_convertMT(1, CE_USE, CE_NWU, &Min[6*imt], M);\n ierr = compearth_convertMT(1, CE_USE, CE_SEU,\n &Min[6*(jmt+imt)], M);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Error switching basis\\n\", __func__);\n ierrAll = ierrAll + 1; //break;\n }\n // PART 1: moment tensor source type (or pattern)\n // Decompose moment tensor into eigenvalues + basis (M = U*lam*U')\n // NOTE: ordering of eigenvalues is important.\n ierr = compearth_CMTdecom(1, M, isort, &lamWork[3*imt],\n &Uwork[9*imt]);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Error decomposing CMT\\n\", __func__);\n ierrAll = ierrAll + 1; //break;\n }\n }\n if (ierrAll != 0)\n {\n fprintf(stderr, \"%s: Error during eigendecomposition\\n\", __func__);\n ierr = 1;\n goto ERROR;\n }\n // Compute the lune coordinates and magnitude from eigenvalues\n lamdev = NULL;\n lamiso = NULL;\n thetadcWork = NULL;\n if (thetadc != NULL){thetadcWork = &thetadc[jmt];}\n ierr = compearth_lam2lune(nmtLoc, lamWork, &gamma[jmt], &delta[jmt],\n &M0[jmt], thetadcWork,\n lamdev, lamiso);\n // Part 2: moment tensor orientation; TT2012, Section 6.3\n ierr = compearth_eulerUtil_rotmat(1, &rotAngle, 2, Yrot);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Error computing rotation matrix\\n\", __func__);\n return -1;\n }\n // Compute candidate fault vectors\n for (imt=0; imt\n#include \n#include \n#include \n//#include \n#include \n#include \n#include \n#include \n\nvoid randperm(int*, int);\nvoid load_double_mat(double*, int, int, int, char*);\nvoid load_int_mat(int*, int, int, int, char*);\nvoid load_double_array(double*, int, char*);\nvoid load_int_array(int*, int, char*);\nvoid load_double_value(int,char);\nvoid load_int_value(int,char);\nint mat_size_row(int*);\nint find_value_in_array(int*,int,int,int);\nvoid mat2d_prod(double*, int, int, double*, int, int, double*, int, int);\ndouble obtainerr2_par(int,int,double*, int, int, int*, int, double*);\nvoid least_square_solver(double*, int, int, double*, double*);\n\n#define MASTER 0\n#define FROM_MASTER 1\n#define FROM_WORKER 2\n\nint main(int argc, char **argv)\n{\n int n1, n2, n3;\n int np, nfu;\n double kv[3][3], pk[3][3], pp[8][3];\n double *rp, *rpL, *rpN, *rpO;\n int *map_to_cluster1, *map_to_cluster2, *map_to_cluster3;\n int *nlist;\n int neighbor_num;\n int ncluster, ncluster2, ncluster3, ncorr_col;\n int c2start, c3start;\n int data;\n double *E, *Ef;\n int ndata;\n int i, j, k, nj, nk, ctn;\n int iter, max_iter;\n double kT=0.0256; // Default value of kT\n int howmanycluster;\n int dispfreq;\n char buff_line[200], dummy[200], param_name[100];\n int param_name_len;\n double cvs_tol = 0.01; // Default value of cvs_tol\n int construct_corr_mat = 0; //Default value of construct_corr_mat\n\n // mpi parameters and initialization\n int numprocs, rank, mtype;\n int row_dist_size;\n int row_ini, row_end, row_offset;\n MPI_Status status;\n MPI_Init(&argc, &argv);\n MPI_Comm_size(MPI_COMM_WORLD, &numprocs); // Get # processors\n MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get my rank (id)\n\n if (numprocs>1)\n printf(\"Parallel computing: the input files are read by all nodes. Multiple messages are not due to error!\\n\",numprocs);\n\n // Construct conrrelation matrix. It can also be loaded.\n \n int n_corr_mat_ug_row;\n int n_non_singular_col;\n FILE *fp;\n char dirname[100]=\"dir_inputs\";\n char paramfilename[100];\n sprintf(paramfilename,\"%s/param.dat\",dirname);\n char corr_mat_ugs_filename[200];\n fp = fopen(paramfilename, \"r\");\n while(fgets(buff_line,sizeof(buff_line),fp) != NULL) {\n if (buff_line[0] == '#') {\n // printf(\"Comment line: %s\",buff_line);\n continue;\n }\n strcpy(param_name,\"corr_mat_ugs_filename\");\n param_name_len = strlen(param_name);\n strncpy(dummy,buff_line,param_name_len);\n dummy[param_name_len] = '\\0';\n if (strcmp(dummy,param_name)==0) {\n sscanf(buff_line,\"%s %s\",dummy,corr_mat_ugs_filename);\n if (rank == MASTER)\n printf(\"corr_mat_ugs_filename = %s\\n\",corr_mat_ugs_filename);\n }\n strcpy(param_name,\"n_corr_mat_ug_row\");\n param_name_len = strlen(param_name);\n strncpy(dummy,buff_line,param_name_len);\n dummy[param_name_len] = '\\0';\n if (strcmp(dummy,param_name)==0) {\n sscanf(buff_line,\"%s %d\",dummy,&n_corr_mat_ug_row);\n if (rank == MASTER)\n printf(\"n_corr_mat_ug_row = %d\\n\",n_corr_mat_ug_row);\n }\n strcpy(param_name,\"n_non_singular_col\");\n param_name_len = strlen(param_name);\n strncpy(dummy,buff_line,param_name_len);\n dummy[param_name_len] = '\\0';\n if (strcmp(dummy,param_name)==0) {\n sscanf(buff_line,\"%s %d\",dummy,&n_non_singular_col);\n if (rank == MASTER)\n printf(\"n_non_singular_col = %d\\n\",n_non_singular_col);\n }\n strcpy(param_name,\"howmanycluster\");\n param_name_len = strlen(param_name);\n strncpy(dummy,buff_line,param_name_len);\n dummy[param_name_len] = '\\0';\n if (strcmp(dummy,param_name)==0) {\n sscanf(buff_line,\"%s %d\",dummy,&howmanycluster);\n if (rank == MASTER)\n printf(\"howmanycluster = %d\\n\",howmanycluster);\n }\n strcpy(param_name,\"max_iter\");\n param_name_len = strlen(param_name);\n strncpy(dummy,buff_line,param_name_len);\n dummy[param_name_len] = '\\0';\n if (strcmp(dummy,param_name)==0) {\n sscanf(buff_line,\"%s %d\",dummy,&max_iter);\n if (rank == MASTER)\n printf(\"max_iter = %d\\n\",max_iter);\n }\n strcpy(param_name,\"kT\");\n param_name_len = strlen(param_name);\n strncpy(dummy,buff_line,param_name_len);\n dummy[param_name_len] = '\\0';\n if (strcmp(dummy,param_name)==0) {\n sscanf(buff_line,\"%s %lf\",dummy,&kT);\n if (rank == MASTER)\n printf(\"kT = %f\\n\",kT);\n }\n strcpy(param_name,\"cvs_tol\");\n param_name_len = strlen(param_name);\n strncpy(dummy,buff_line,param_name_len);\n dummy[param_name_len] = '\\0';\n if (strcmp(dummy,param_name)==0) {\n sscanf(buff_line,\"%s %lf\",dummy,&cvs_tol);\n if (rank == MASTER)\n printf(\"cvs_tol = %f\\n\",cvs_tol);\n }\n strcpy(param_name,\"dispfreq\");\n param_name_len = strlen(param_name);\n strncpy(dummy,buff_line,param_name_len);\n dummy[param_name_len] = '\\0';\n if (strcmp(dummy,param_name)==0) {\n sscanf(buff_line,\"%s %d\",dummy,&dispfreq);\n if (rank == MASTER)\n printf(\"dispfreq = %d\\n\",dispfreq);\n }\n }\n fclose(fp);\n\n char loadfilename[100];\n double *corr_mat_ugs;\n corr_mat_ugs = (double*) malloc(n_corr_mat_ug_row*n_non_singular_col*sizeof(double));\n sprintf(loadfilename,\"%s/%s\",dirname,corr_mat_ugs_filename);\n load_double_mat(corr_mat_ugs,n_corr_mat_ug_row,n_non_singular_col,1,loadfilename);\n \n int usefulcorr_col[n_non_singular_col];\n sprintf(loadfilename,\"%s/usefulcorr_col.dat\",dirname);\n load_int_array(usefulcorr_col,n_non_singular_col,loadfilename);\n \n double Ef_ug[n_corr_mat_ug_row];\n sprintf(loadfilename,\"%s/Ef_ug.dat\",dirname);\n load_double_array(Ef_ug,n_corr_mat_ug_row,loadfilename);\n \n/* int nC_ug[n_corr_mat_ug_row];\n sprintf(loadfilename,\"%s/nC_ug.dat\",dirname);\n load_int_array(nC_ug,n_corr_mat_ug_row,loadfilename);\n*/\n row_offset = (int) ceil(n_corr_mat_ug_row*1.0/numprocs);\n if (numprocs>1 && rank==MASTER)\n printf(\"Correlation Matrix is calculated over %d processors: row_offset = %d\\n\",numprocs,row_offset);\n double err2_sum_from_master;\n double err2_sum_from_worker;\n int cluster_set1[howmanycluster];\n \n /**** Start of MC simulation ****/\n if (rank == MASTER) {\n int cluster_set1_old[howmanycluster], cluster_set1_min[howmanycluster], cluster_set2[n_non_singular_col-howmanycluster];\n double cvs, cvs_old, cvs_min;\n int select1, select2, target, candidate;\n \n for (i=0;i drand48())\n cluster_set2[select2] = target;\n else {\n cluster_set1[select1] = target;\n cvs = cvs_old;\n }\n if (cvs < cvs_min) {\n for (i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid generate_MCMC_parameters(MCMC_info *MCMC) {\n int i_P;\n int j_P;\n double factor_i;\n int flag_continue;\n static int reflect_priors;\n static int n_P;\n static double factor;\n static double * P_new;\n static double * P_chain;\n static double * P_init;\n static double * P_limit_min;\n static double * P_limit_max;\n static gsl_vector *b;\n static gsl_matrix *m;\n static RNG_info * RNG;\n\n // Initialize a few things on the first call\n switch(MCMC->first_parameter_call) {\n case GBP_TRUE:\n n_P = MCMC->n_P;\n P_new = MCMC->P_new;\n P_chain = MCMC->P_chain;\n P_init = MCMC->P_init;\n P_limit_min = MCMC->P_limit_min;\n P_limit_max = MCMC->P_limit_max;\n b = MCMC->b;\n m = MCMC->m;\n RNG = MCMC->RNG;\n factor = 2.4 / sqrt((double)MCMC->n_M_total);\n MCMC->first_parameter_call = GBP_FALSE;\n reflect_priors = SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_REFLECT_PRIORS);\n break;\n }\n\n // Loop until a satisfactory set of parameters has been selected\n flag_continue = GBP_TRUE;\n while(flag_continue) {\n // Generate a random displacement vector\n factor_i = MCMC->temperature * factor;\n for(i_P = 0; i_P < n_P; i_P++)\n gsl_vector_set(b, i_P, factor_i * random_gaussian(RNG));\n\n // Use the rotated covariance matrix (if available)\n if(m != NULL) {\n memcpy(P_new, P_chain, n_P * sizeof(double));\n for(i_P = 0; i_P < n_P; i_P++) {\n for(j_P = 0; j_P < n_P; j_P++)\n P_new[i_P] += gsl_matrix_get(m, i_P, j_P) * gsl_vector_get(b, j_P);\n }\n } else {\n for(j_P = 0; j_P < n_P; j_P++)\n P_new[j_P] = P_init[j_P] * (1. + gsl_vector_get(b, j_P));\n }\n\n // Enforce parameter limits\n if(reflect_priors) {\n for(i_P = 0; i_P < n_P; i_P++) {\n if(P_new[i_P] < P_limit_min[i_P])\n P_new[i_P] = 2 * (P_limit_min[i_P]) - P_new[i_P];\n if(P_new[i_P] > P_limit_max[i_P])\n P_new[i_P] = 2 * (P_limit_max[i_P]) - P_new[i_P];\n }\n } else {\n for(i_P = 0, flag_continue = GBP_FALSE; i_P < n_P; i_P++)\n if(P_new[i_P] < P_limit_min[i_P] || P_new[i_P] > P_limit_max[i_P])\n flag_continue = GBP_TRUE;\n }\n }\n\n if(!SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_PARALLEL))\n SID_Bcast(P_new, n_P, SID_DOUBLE, SID_MASTER_RANK, MCMC->comm);\n}\n", "meta": {"hexsha": "cb58f17c05975eaf628e5ae2842536cc58f73c16", "size": 3154, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpMCMC/generate_MCMC_parameters.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpMath/gbpMCMC/generate_MCMC_parameters.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpMath/gbpMCMC/generate_MCMC_parameters.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 37.1058823529, "max_line_length": 105, "alphanum_fraction": 0.5057070387, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.43496402688260327}} {"text": "/**\n * @file bblas_daccuracy.c\n *\n * @brief BBLAS accuracy tests for double_Complex precision.\n *\n * BBLAS is a software package provided by Univ. of Manchester,\n * Univ. of Tennessee.\n *\n * @version 1.0.0\n * @author Samuel D. Relton\n * @author Pedro V. Lara\n * @author Mawussi Zounon\n * @date 2016-02-20\n *\n **/\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n/**\n * Code generation\n * @generated from bblas_zaccuracy.c normal z -> d, Mon Jun 6 09:44:14 2016\n **/\n#endif\n\n#include \"bblas_common.h\"\n#include \n#include \n\n\n\n#define REAL\n\n/**\n * bblas_dgemm_tolerance computes the forward error\n * @f[\\|C - C_{\\mathrm{seq}}\\|_{\\infty}/((K|\\alpha|\\|A\\|_{\\infty}\\|B\\|_{\\infty} +\n * |\\beta|\\|C_{\\mathrm{init}}\\|_{\\infty})\\epsilon).@f]\n *\n **/\n\nvoid bblas_dgemm_tolerance(bblas_dtest_t *test, double **C_final)\n{\n\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, An, Bm, Bn, M, K, N, ldc;\n int max_work_size = max(test->maxK,max(test->maxM, test->maxN));\n double Anorm, Bnorm, Rnorm, result;\n double eps = LAPACKE_dlamch_work('e');\n double alpha =-1;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n /*Temporary buffer to save (test-arrayC -C_final) */\n double **C_diff;\n C_diff = (double **) malloc(batch_count*sizeof(double *));\n\n /*Make a copy of test->arrayC in C_diff */\n bblas_dcopy_Cinit(test, C_diff);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t M = test->M[batch_iter];\n\t K = test->K[batch_iter];\n\t N = test->N[batch_iter];\n\t ldc = test->ldc[batch_iter];\n\n\t if (test->transA[batch_iter] == BblasNoTrans) {\n\t\tAm = M; An = K;\n\t } else {\n\t\tAm = K; An = M;\n\t }\n\t if (test->transB[batch_iter] == BblasNoTrans) {\n\t\tBm = K; Bn = N;\n\t } else {\n\t\tBm = N; Bn = K;\n\t }\n\n\t /*Compute the error C - C_finial */\n\t cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t /*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', M, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm of B */\n\t Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t result = Rnorm / ((K*cabs(test->alpha[batch_iter])*Anorm*Bnorm + cabs(test->beta[batch_iter])*test->Cinitnorm[batch_iter])*eps);\n\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_dcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n\n }else if( test->batch_opts == BBLAS_FIXED ) //fixed size\n {\n\tM = test->M[first_index];\n\tK = test->K[first_index];\n\tldc = test->ldc[first_index];\n\tN = test->N[first_index];\n\n\tif (test->transA[first_index] == BblasNoTrans) {\n\t Am = M; An = K;\n\t} else {\n\t Am = K; An = M;\n\t}\n\tif (test->transB[first_index] == BblasNoTrans) {\n\t Bm = K; Bn = N;\n\t} else {\n\t Bm = N; Bn = K;\n\t}\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t\t/*Compute the error C - C_finial */\n\t cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\t /*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', M, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm of B */\n\t Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t /*Compute the relative error */\n\t result = Rnorm / ((K*cabs(test->alpha[first_index])*Anorm*Bnorm + cabs(test->beta[first_index])*test->Cinitnorm[batch_iter])*eps);\n\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_dcheck_Cfinal: Fixed, Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n }else\n {\n\tbblas_error(\"bblas_dtesting.c\", \"wrong batch_opts value\");\n }\n\n/*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(C_diff[index]);\n }\n free(C_diff);\n free(work);\n}\n\n\n/**\n * bblas_dstarmm_tolerance computes the forward error\n * @f[\\|C - C_{\\mathrm{seq}}\\|_{\\infty}/((K|\\alpha|\\|A\\|_{\\infty}\\|B\\|_{\\infty} +\n * |\\beta|\\|C_{\\mathrm{init}}\\|_{\\infty})\\epsilon).@f]\n *\n **/\n\nvoid bblas_dstarmm_tolerance(bblas_dtest_t *test, double **C_final)\n{\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, Bm, Bn, N, ldc;\n int max_work_size = max(test->maxM, test->maxN);\n double Anorm, Bnorm, Rnorm, result;\n double eps = LAPACKE_dlamch_work('e');\n double alpha =-1;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n /*Temporary buffer to save (test-arrayC -C_final) */\n double **C_diff;\n C_diff = (double **) malloc(batch_count*sizeof(double *));\n\n /*Make a copy of test->arrayC in C_diff */\n bblas_dcopy_Cinit(test, C_diff);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t N = test->N[batch_iter];\n\t ldc = test->ldc[batch_iter];\n\n\t if(test->side[batch_iter] == BblasLeft )\n\t {\n\t\tAm = test->M[batch_iter];\n\t } else {\n\t\tAm = test->N[batch_iter];\n\t }\n\t Bm = test->ldb[batch_iter];\n\t Bn = test->N[batch_iter];\n\t /*Compute the error C - C_finial */\n\t cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, Am, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm of B */\n\t Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t result = Rnorm / ((N*cabs(test->alpha[batch_iter])*Anorm*Bnorm + cabs(test->beta[batch_iter])*test->Cinitnorm[batch_iter])*eps);\n\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_dcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n\n }else if( test->batch_opts == BBLAS_FIXED ) //fixed size\n {\n\tN = test->N[first_index];\n\tldc = test->ldc[first_index];\n\n\tif(test->side[first_index] == BblasLeft )\n\t{\n\t Am = test->M[first_index];\n\t} else {\n\t Am = test->N[first_index];\n\t}\n\tBm = test->ldb[first_index];\n\tBn = test->N[first_index];\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t /*Compute the error C - C_finial */\n\t cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t /*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, Am, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm of B */\n\t Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t /*Compute the relative error */\n\t result = Rnorm / ((N*cabs(test->alpha[first_index])*Anorm*Bnorm + cabs(test->beta[first_index])*test->Cinitnorm[batch_iter])*eps);\n\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_dcheck_Cfinal: Fixed, Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n }else\n {\n\tbblas_error(\"bblas_dtesting.c\", \"wrong batch_opts value\");\n }\n\n/*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(C_diff[index]);\n }\n free(C_diff);\n free(work);\n}\n\n\n/**\n * bblas_dstark_tolerance computes the forward error\n * @f[\\|C - C_{\\mathrm{seq}}\\|_{\\infty}/((K|\\alpha|\\|A\\|_{\\infty}\\|A\\|_1 +\n * |\\beta|\\|C_{\\mathrm{init}}\\|_{\\infty})\\epsilon).@f]\n *\n **/\n\nvoid bblas_dstark_tolerance(bblas_dtest_t *test, double **C_final)\n{\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, An, N, K, ldc;\n char u;\n int max_work_size = max(test->maxK, test->maxN);\n double Anorm, ATnorm, Rnorm, result;\n double eps = LAPACKE_dlamch_work('e');\n double alpha_norm, beta_norm;\n double alpha =-1;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n /*Temporary buffer to save (test-arrayC -C_final) */\n double **C_diff;\n C_diff = (double **) malloc(batch_count*sizeof(double *));\n\n\n /*Make a copy of test->arrayC in C_diff */\n bblas_dcopy_Cinit(test, C_diff);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t N = test->N[batch_iter];\n\t K = test->K[batch_iter];\n\t ldc = test->ldc[batch_iter];\n\n\t if (test->trans[batch_iter] == BblasNoTrans) {\n\t\tAm = N; An = K;\n\t } else {\n\t\tAm = K; An = N;\n\t }\n\n\t if(test->uplo[batch_iter] == BblasLower )\n\t {\n\t\tu = 'L';\n\t }else\n\t {\n\t\tu = 'U';\n\t }\n\t /*Compute the error C - C_finial */\n\t cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t /*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_dlansy_work(LAPACK_COL_MAJOR, 'I', u, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the one norm of A */\n\t ATnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t if (test->routine == BBLAS_HERK)\n\t {\n\t\tbeta_norm = cabs(test->beta_herk[batch_iter]);\n\t\talpha_norm = cabs(test->alpha_herk[batch_iter]);\n\t }else{\n\t\tbeta_norm = cabs(test->beta[batch_iter]);\n\t\talpha_norm = cabs(test->alpha[batch_iter]);\n\t }\n\n\t result = Rnorm / ((K*alpha_norm*Anorm*ATnorm + beta_norm*test->Cinitnorm[batch_iter])*eps);\n\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_dcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n\n }else if( test->batch_opts == BBLAS_FIXED ) //fixed size\n {\n\t N = test->N[first_index];\n\t K = test->K[first_index];\n\t ldc = test->ldc[first_index];\n\n\t if (test->trans[first_index] == BblasNoTrans) {\n\t\tAm = N; An = K;\n\t } else {\n\t\tAm = K; An = N;\n\t }\n\t if(test->uplo[first_index] == BblasLower )\n\t {\n\t\tu = 'L';\n\t }else\n\t {\n\t\tu = 'U';\n\t }\n\n\t for( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t {\n\t\t/*Compute the error C - C_finial */\n\t\tcblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t\tRnorm = LAPACKE_dlansy_work(LAPACK_COL_MAJOR, 'I', u, N, C_diff[batch_iter], ldc, work);\n\n\t\t/*Compute the infinity norm of A */\n\t\tAnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t\t/*Compute the one norm of A */\n\t\tATnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t\tif (test->routine == BBLAS_HERK)\n\t\t{\n\t\t beta_norm = cabs(test->beta_herk[first_index]);\n\t\t alpha_norm = cabs(test->alpha_herk[first_index]);\n\t\t}else{\n\t\t beta_norm = cabs(test->beta[first_index]);\n\t\t alpha_norm = cabs(test->alpha[first_index]);\n\t\t}\n\n\t\t/*Compute the relative error */\n\t\tresult = Rnorm / ((K*alpha_norm*Anorm*ATnorm +\n\t\t\t\t beta_norm*test->Cinitnorm[batch_iter])*eps);\n\n\t\tswitch(test->target)\n\t\t{\n\t\t case BBLAS_MKL:\n\t\t\ttest->mkl_error[batch_iter] = result;\n\t\t\tbreak;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\t case BBLAS_OTHER:\n\t\t\ttest->other_error[batch_iter] = result;\n\t\t\tbreak;\n\t\t default:\n\t\t\tprintf(\"In bblas_dcheck_Cfinal: Fixed, Target no defined\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t }\n }else\n {\n\tbblas_error(\"bblas_dtesting.c\", \"wrong batch_opts value\");\n }\n\n/*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(C_diff[index]);\n }\n free(C_diff);\n free(work);\n}\n\n\n/**\n * bblas_dstar2k_tolerance computes the forward error\n * @f[\\|C - C_{\\mathrm{seq}}\\|_{\\infty}/((K|\\alpha|\\|A\\|_{\\infty}\\|B\\|_1 +\n * K|\\alpha|\\|B\\|_{\\infty}\\|A\\|_1 +\n * |\\beta|\\|C_{\\mathrm{init}}\\|_{\\infty})\\epsilon).@f]\n *\n **/\n\nvoid bblas_dstar2k_tolerance(bblas_dtest_t *test, double **C_final)\n{\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, An, Bn, Bm, N, K, ldc;\n int max_work_size = max(test->maxK, test->maxN);\n double Anorm, Bnorm, ATnorm, BTnorm, Rnorm, result;\n double beta_norm;\n double eps = LAPACKE_dlamch_work('e');\n double alpha =-1;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n /*Temporary buffer to save (test-arrayC -C_final) */\n double **C_diff;\n C_diff = (double **) malloc(batch_count*sizeof(double *));\n\n /*Make a copy of test->arrayC in C_diff */\n bblas_dcopy_Cinit(test, C_diff);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t N = test->N[batch_iter];\n\t K = test->K[batch_iter];\n\t ldc = test->ldc[batch_iter];\n\n\t if (test->trans[batch_iter] == BblasNoTrans) {\n\t\tAm = N; An = K;\n\t\tBn = K;\n\t } else {\n\t\tAm = K; An = N;\n\t\tBn = N;\n\t }\n\t Bm = test->ldb[batch_iter];\n\n\t /*Compute the error C - C_finial */\n\t cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the one norm of A */\n\t ATnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm of B */\n\t Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t /*Compute the one norm of B */\n\t BTnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t if(test->routine == BBLAS_HER2K)\n\t {\n\t\tbeta_norm = cabs(test->beta_herk[batch_iter]);\n\t }else\n\t {\n\t\tbeta_norm = cabs(test->beta[batch_iter]);\n\t }\n\n\t result = Rnorm / ((K*cabs(test->alpha[batch_iter])*Anorm*BTnorm +\n\t\t\t K*cabs(test->alpha[batch_iter])*Bnorm*ATnorm +\n\t\t\t beta_norm*test->Cinitnorm[batch_iter])*eps);\n\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_dcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n\n }else if( test->batch_opts == BBLAS_FIXED ) //fixed size\n {\n\tN = test->N[first_index];\n\tK = test->K[first_index];\n\tldc = test->ldc[first_index];\n\n\tif (test->trans[first_index] == BblasNoTrans) {\n\t\tAm = N; An = K;\n\t\tBn = K;\n\t} else {\n\t Am = K; An = N;\n\t Bn = N;\n\t}\n\tBm = test->ldb[first_index];\n\n\n\t for( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t {\n\t\t/*Compute the error C - C_finial */\n\t\tcblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the error */\n\t\tRnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);\n\n\t\t/*Compute the infinity norm of A */\n\t\tAnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t\t/*Compute the one norm of A */\n\t\tATnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t\t/*Compute the infinity norm of B */\n\t\tBnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t\t/*Compute the one norm of B */\n\t\tBTnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t\tif(test->routine == BBLAS_HER2K)\n\t\t{\n\t\t beta_norm = cabs(test->beta_herk[first_index]);\n\t\t}else\n\t\t{\n\t\t beta_norm = cabs(test->beta[first_index]);\n\t\t}\n\n\t\t/*Compute the relative error */\n\t\tresult = Rnorm / ((K*cabs(test->alpha[first_index])*Anorm*BTnorm +\n\t\t\t\t K*cabs(test->alpha[first_index])*Bnorm*ATnorm +\n\t\t\t\t beta_norm*test->Cinitnorm[batch_iter])*eps);\n\n\n\t\tswitch(test->target)\n\t\t{\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_dcheck_Cfinal: Fixed, Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t\t}\n\t }\n }else\n {\n\tbblas_error(\"bblas_dtesting.c\", \"wrong batch_opts value\");\n }\n\n/*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(C_diff[index]);\n }\n free(C_diff);\n free(work);\n}\n\n\n/**\n * bblas_dtrmm_tolerance computes the forward error\n * @f[\\|C - C_{\\mathrm{seq}}\\|_{\\infty}/((|\\alpha|\\|A\\|_{\\infty}\\|B\\|_{\\infty}N\\epsilon).@f]\n *\n **/\n\nvoid bblas_dtrmm_tolerance(bblas_dtest_t *test, double **B_final)\n{\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, An, ldb, N, M;\n int max_work_size = max(test->maxK, test->maxN);\n char u, diag;\n double Anorm, Rnorm, result;\n double eps = LAPACKE_dlamch_work('e');\n double alpha =-1;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n\n\n /*Temporary buffer to save (test-arrayB -B_final) */\n double **B_diff;\n B_diff = (double **) malloc(batch_count*sizeof(double *));\n\n /*Make a copy of test->arrayB in B_diff */\n bblas_dcopy_Binit(test, B_diff);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t N = test->N[batch_iter];\n\t M = test->M[batch_iter];\n\t ldb = test->ldb[batch_iter];\n\n\t Am = test->lda[batch_iter];\n\n\t if(test->side[batch_iter] == BblasLeft )\n\t {\n\t\tAn = M;\n\t }else\n\t {\n\t\tAn = N;\n\t }\n\n\t if(test->uplo[batch_iter] == BblasLower )\n\t {\n\t u = 'L';\n\t }else\n\t {\n\t u = 'U';\n\t }\n\n\t if(test->diag[batch_iter] == BblasUnit )\n\t {\n\t\tdiag = 'U';\n\t }else\n\t {\n\t\tdiag = 'N';\n\t }\n\n\t /*Compute the error B - B_finial */\n\t cblas_daxpy (ldb*N, (alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, B_diff[batch_iter], ldb, work);\n\n\t /*Infinity norm of the triangular matrix A */\n\t Anorm = LAPACKE_dlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,\n\t\t\t\t\tAn, test->arrayA[batch_iter], Am, work);\n\t \n\t\tresult = Rnorm/(N*cabs(test->alpha[batch_iter])*Anorm*test->Binitnorm[batch_iter]*eps);\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_dcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\n\t}\n }else if( test->batch_opts == BBLAS_FIXED )\n {\n\n\tN = test->N[first_index];\n\tM = test->M[first_index];\n\tldb = test->ldb[first_index];\n\n\tAm = test->lda[first_index];\n\n\tif(test->side[first_index] == BblasLeft )\n\t{\n\t An = M;\n\t}else\n\t{\n\t An = N;\n\t}\n\n\tif(test->uplo[first_index] == BblasLower )\n\t{\n\t u = 'L';\n\t}else\n\t{\n\t u = 'U';\n\t}\n\n\tif(test->diag[first_index] == BblasUnit )\n\t{\n\t diag = 'U';\n\t}else\n\t{\n\t diag = 'N';\n\t}\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t /*Compute the error B - B_finial */\n\t cblas_daxpy (ldb*N, (alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, B_diff[batch_iter], ldb, work);\n\n\t /*Infinity norm of the triangular matrix A */\n\t Anorm = LAPACKE_dlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,\n\t\t\t\t\tAn, test->arrayA[batch_iter], Am, work);\n\n\t result = Rnorm/(N*cabs(test->alpha[first_index])*Anorm*test->Binitnorm[batch_iter]*eps);\n\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_dcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n }\n else\n {\n\tbblas_error(\"bblas_dtesting.c\", \"wrong batch_opts value\");\n }\n\n /*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(B_diff[index]);\n }\n free(B_diff);\n free(work);\n}\n\n/**\n * bblas_dtrsm_tolerance computes the backward error\n * @f[\\|\\alpha B - AX \\|_{\\infty}/((\\|A\\|_{\\infty}\\|X\\| + |\\alpha|\\|B\\|_{\\infty})N\\epsilon).@f]\n *\n **/\n\nvoid bblas_dtrsm_tolerance(bblas_dtest_t *test, double **B_final)\n{\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, An, ldb, N, M;\n int max_work_size = max(test->maxK, test->maxN);\n char u, diag;\n double Anorm, Rnorm, result, Xnorm;\n double eps = LAPACKE_dlamch_work('e');\n double alpha;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n\n\n /*Variable to save the residual alphaB -AX */\n double **residual;\n residual = (double **) malloc(batch_count*sizeof(double *));\n\n /*Make a copy of test->arrayB (X) in residual */\n bblas_dcopy_Binit(test, residual);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t N = test->N[batch_iter];\n\t M = test->M[batch_iter];\n\t ldb = test->ldb[batch_iter];\n\n\t Am = test->lda[batch_iter];\n\n\t if(test->side[batch_iter] == BblasLeft )\n\t {\n\t\tAn = M;\n\t }else\n\t {\n\t\tAn = N;\n\t }\n\n\t if(test->uplo[batch_iter] == BblasLower )\n\t {\n\t u = 'L';\n\t }else\n\t {\n\t u = 'U';\n\t }\n\n\t if(test->diag[batch_iter] == BblasUnit )\n\t {\n\t\tdiag = 'U';\n\t }else\n\t {\n\t\tdiag = 'N';\n\t }\n\n\t /*Compute residual <- AX (dtrmm) */\n\t alpha = 1;\n\t cblas_dtrmm(BblasColMajor, test->side[batch_iter], test->uplo[batch_iter], test->transA[batch_iter],\n\t\t\ttest->diag[batch_iter], M, N, (alpha), test->arrayA[batch_iter],\n\t\t\ttest->lda[batch_iter], residual[batch_iter], ldb);\n\n\t /*Compute Binit = alpha Binit */\n\t for (int index=0; index < ldb*N; index++)\n\t {\n\t\ttest->Binit[batch_iter][index] = test->alpha[batch_iter]*test->Binit[batch_iter][index];\n\t }\n\n\t /*Compute the residual <- alpha B - Ax */\n\t alpha= -1;\n\t cblas_daxpy (ldb*N, (alpha), test->Binit[batch_iter], 1, residual[batch_iter], 1);\n\t\t/*Compute the infinity norm associated with the residual */\n\t Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, residual[batch_iter], ldb, work);\n\n\t /*Infinity norm of the triangular matrix A */\n\t Anorm = LAPACKE_dlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,\n\t\t\t\t\tAn, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm associated with X (B) */\n\t Xnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, test->arrayB[batch_iter], ldb, work);\n\n\t result = Rnorm/(Anorm*Xnorm*N*eps);\n\t \n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_dcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\n\t}\n }else if( test->batch_opts == BBLAS_FIXED )\n {\n\n\tN = test->N[first_index];\n\tM = test->M[first_index];\n\tldb = test->ldb[first_index];\n\n\tAm = test->lda[first_index];\n\n\tif(test->side[first_index] == BblasLeft )\n\t{\n\t An = M;\n\t}else\n\t{\n\t An = N;\n\t}\n\n\tif(test->uplo[first_index] == BblasLower )\n\t{\n\t u = 'L';\n\t}else\n\t{\n\t u = 'U';\n\t}\n\n\tif(test->diag[first_index] == BblasUnit )\n\t{\n\t diag = 'U';\n\t}else\n\t{\n\t diag = 'N';\n\t}\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\n\t /*Compute residual <- AX (dtrmm) */\n\t alpha = 1;\n\t cblas_dtrmm(BblasColMajor, test->side[first_index], test->uplo[first_index], test->transA[first_index],\n\t\t\ttest->diag[first_index], M, N, (alpha), (const double*) test->arrayA[batch_iter],\n\t\t\ttest->lda[first_index], residual[batch_iter], ldb);\n\n\t /*Compute Binit = alpha Binit */\n\t for (int index=0; index < ldb*N; index++)\n\t {\n\t\ttest->Binit[batch_iter][index] = test->alpha[first_index]*test->Binit[batch_iter][index];\n\t }\n\n\t /*Compute the residual <- alpha B - Ax */\n\t alpha = -1;\n\t cblas_daxpy (ldb*N, (alpha), test->Binit[batch_iter], 1, residual[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the residual */\n\t Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, residual[batch_iter], ldb, work);\n\n\t /*Infinity norm of the triangular matrix A */\n\t Anorm = LAPACKE_dlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,\n\t\t\t\t\tAn, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm associated with X (B) */\n\t Xnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, test->arrayB[batch_iter], ldb, work);\n\n\t result = Rnorm/(Anorm*Xnorm*N*eps);\n\t \n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_dcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n }\n else\n {\n\tbblas_error(\"bblas_dtesting.c\", \"wrong batch_opts value\");\n }\n\n /*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(residual[index]);\n }\n free(residual);\n free(work);\n}\n\n\n/**\n * Calls bblas_dstar2k_tolerance.\n **/\n#ifdef COMPLEX\nvoid bblas_dsyr2k_tolerance(bblas_dtest_t *test, double **C_final)\n{\n bblas_dstar2k_tolerance(test, C_final);\n\n}\n#endif\n/**\n * Calls bblas_dstar2k_tolerance.\n **/\n\nvoid bblas_dsyr2k_tolerance(bblas_dtest_t *test, double **C_final)\n{\n bblas_dstar2k_tolerance(test, C_final);\n}\n\n/**\n * Calls bblas_dstark_tolerance.\n **/\n\n#ifdef COMPLEX\nvoid bblas_dsyrk_tolerance(bblas_dtest_t *test, double **C_final)\n{\n bblas_dstark_tolerance(test, C_final);\n}\n#endif\n/**\n * Calls bblas_dstark_tolerance.\n **/\n\nvoid bblas_dsyrk_tolerance(bblas_dtest_t *test, double **C_final)\n{\n bblas_dstark_tolerance(test, C_final);\n}\n\n/**\n * Calls bblas_dstarmm_tolerance.\n **/\n\n#ifdef COMPLEX\nvoid bblas_dsymm_tolerance(bblas_dtest_t *test, double **C_final)\n{\n bblas_dstarmm_tolerance(test, C_final);\n}\n#endif\n/**\n * Calls bblas_dstamm_tolerance.\n **/\n\nvoid bblas_dsymm_tolerance(bblas_dtest_t *test, double **C_final)\n{\n bblas_dstarmm_tolerance(test, C_final);\n}\n", "meta": {"hexsha": "7bfab0c3276ab0b46749caa1a3b143b4d94238f5", "size": 29524, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/bblas_daccuracy.c", "max_stars_repo_name": "NLAFET/BBLAS-ref", "max_stars_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/bblas_daccuracy.c", "max_issues_repo_name": "NLAFET/BBLAS-ref", "max_issues_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/bblas_daccuracy.c", "max_forks_repo_name": "NLAFET/BBLAS-ref", "max_forks_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2669039146, "max_line_length": 135, "alphanum_fraction": 0.6259314456, "num_tokens": 9127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.4342222268762238}} {"text": "#include \n#include \n#include \n#include \n#include \"parmt_mtsearch.h\"\n#ifdef PARMT_USE_INTEL\n#include \n#else\n#include \n#endif\n#include \"iscl/array/array.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/signal/convolve.h\"\n\nint parmt_computeStackedCrossCorrelation_MPI(\n const MPI_Comm comm,\n const int npgrns,\n const double *__restrict__ Gxx,\n const double *__restrict__ Gyy,\n const double *__restrict__ Gzz,\n const double *__restrict__ Gxy,\n const double *__restrict__ Gxz,\n const double *__restrict__ Gyz,\n const int ldm, const int nmt, const double *__restrict__ mt, \n const int npts, const double *__restrict__ data,\n const int lxc, double *__restrict__ xc)\n{\n double *xcwork;\n int ierr, lx;\n ierr = 0;\n lx = npts + npgrns - 1;\n xcwork = memory_calloc64f(lxc);\n ierr = parmt_computeStackedCrossCorrelation(npgrns,\n Gxx, Gyy, Gzz,\n Gxy, Gxz, Gyz,\n ldm, nmt, mt,\n npts, data,\n lx, xcwork);\n MPI_Allreduce(xcwork, xc, lxc, MPI_DOUBLE, MPI_SUM, comm); \n memory_free64f(&xcwork);\n return ierr; \n}\n//============================================================================//\n/*!\n * @brief This is an alignment tool intended to optimize the lag by computing\n *\n * \\f[\n * x_c = \\frac{1}{n_{mt}} \\sum_{i=1}^{n_{mt}} \\textbf{u}_i \\textbf{d}\n * \\f]\n *\n * where the \\f$ \\star \\f$ implies a normalized cross-correlation.\n *\n * @param[in] npgrns number of points in Green's functions\n * @param[in] Gxx Green's functions scaled by \\f$ m_{xx} \\f$ [npgrns] \n * @param[in] Gyy Green's functions scaled by \\f$ m_{yy} \\f$ [npgrns]\n * @param[in] Gzz Green's functions scaled by \\f$ m_{zz} \\f$ [npgrns]\n * @param[in] Gxy Green's functions scaled by \\f$ m_{xy} \\f$ [npgrns]\n * @param[in] Gxz Green's functions scaled by \\f$ m_{xz} \\f$ [npgrns]\n * @param[in] Gyz Green's functions scaled by \\f$ m_{yz} \\f$ [npgrns]\n * @param[in] ldm leading dimension of moment tensors (>= 6)\n * @param[in] nmt number of moment tensors\n * @param[in] mt moment tensors. the i'th moment tensor begins at\n * i*ldm and the moment tensor terms are packed \n * \\f$ \\{ m_{xx}, m_{yy}, m_{zz},\n * m_{xy}, m_{xz}, m_{yz} \\f$.\n * @param[in] npts number of points in signal\n * @param[in] data Observed data. This is an array of dimension [npts].\n * @param[in] lxc max size of xc (should be >= npts + npgrns - 1)\n *\n * @param[out] xc stack of the observed and synthetic cross-correlations\n * [lxc]. the C indexed lag is computed:\n * npts - 1 + argmax(xc)\n * where the argmax takes values [0,lx-1] \n *\n * @result 0 indicates success\n * \n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n */\nint parmt_computeStackedCrossCorrelation(\n const int npgrns,\n const double *__restrict__ Gxx,\n const double *__restrict__ Gyy,\n const double *__restrict__ Gzz,\n const double *__restrict__ Gxy,\n const double *__restrict__ Gxz,\n const double *__restrict__ Gyz,\n const int ldm, const int nmt, const double *__restrict__ mt,\n const int npts, const double *__restrict__ data,\n const int lxc, double *__restrict__ xc)\n{\n const char *fcnm = \"parmt_computedStackedCrossCorrelation\\0\";\n double *Gmat, *Gxc, *xcorr, *xcw;\n double m6[8] __attribute__((aligned(64)));\n double dscal __attribute__((aligned(64))) = 0.0;\n double gscal __attribute__((aligned(64))) = 0.0;\n double xscal __attribute__((aligned(64))) = 0.0;\n double est __attribute__((aligned(64))) = 0.0; \n int i, ierr, j, lc;\n lc = npts + npgrns - 1;\n if (npts < 1 || npgrns < 1 ||\n Gxx == NULL || Gyy == NULL || Gzz == NULL ||\n Gxy == NULL || Gxz == NULL || Gyz == NULL ||\n data == NULL)\n {\n if (npts < 1){fprintf(stderr, \"%s: no data points\\n\", __func__);}\n if (npgrns < 1){fprintf(stderr, \"%s: no grns fns points\\n\", __func__);}\n if (data == NULL){fprintf(stderr, \"%s: data is NULL\\n\", __func__);}\n if (Gxx == NULL){fprintf(stderr, \"%s: Gxx is NULL\\n\", __func__);}\n if (Gyy == NULL){fprintf(stderr, \"%s: Gyy is NULL\\n\", __func__);}\n if (Gzz == NULL){fprintf(stderr, \"%s: Gzz is NULL\\n\", __func__);}\n if (Gxy == NULL){fprintf(stderr, \"%s: Gxy is NULL\\n\", __func__);}\n if (Gxz == NULL){fprintf(stderr, \"%s: Gxz is NULL\\n\", __func__);}\n if (Gyz == NULL){fprintf(stderr, \"%s: Gyz is NULL\\n\", __func__);}\n return -1;\n } \n if (lc > lxc)\n {\n fprintf(stderr, \"%s: Error xc is too small\\n\", __func__);\n return -1;\n }\n if (ldm < 6 || nmt < 1 || mt == NULL)\n {\n if (ldm < 6){fprintf(stderr, \"%s: ldm must be >= 6\\n\", __func__);}\n if (nmt < 1){fprintf(stderr, \"%s: no moment tensors\\n\", __func__);}\n if (mt == NULL){fprintf(stderr, \"%s: mt is NULL\\n\", __func__);}\n return -1;\n }\n // Set space and correlate data with columns of G\n xcorr = memory_calloc64f(lc);\n Gmat = memory_calloc64f(8*npgrns);\n Gxc = memory_calloc64f(8*lc);\n dscal = cblas_dnrm2(npts, data, 1);\n dscal = dscal*dscal;\n#ifdef __INTEL_COMPILER\n__assume_aligned(Gxc, 64);\n__assume_aligned(Gmat, 64);\n__assume_aligned(xcorr, 64);\n__assume_aligned(xc, 64);\n#endif\n for (i=0; i<6; i++)\n {\n if (i == 0)\n {\n cblas_dcopy(npgrns, Gxx, 1, &Gmat[i], 8);\n ierr = signal_convolve_correlate64f_work(npts, data,\n npgrns,\n Gxx,\n CONVCOR_FULL,\n lc, xcorr);\n }\n else if (i == 1)\n {\n cblas_dcopy(npgrns, Gyy, 1, &Gmat[i], 8);\n ierr = signal_convolve_correlate64f_work(npts, data,\n npgrns,\n Gyy,\n CONVCOR_FULL,\n lc, xcorr);\n }\n else if (i == 2)\n {\n cblas_dcopy(npgrns, Gzz, 1, &Gmat[i], 8);\n ierr = signal_convolve_correlate64f_work(npts, data,\n npgrns,\n Gzz,\n CONVCOR_FULL,\n lc, xcorr);\n }\n else if (i == 3)\n {\n cblas_dcopy(npgrns, Gxy, 1, &Gmat[i], 8);\n ierr = signal_convolve_correlate64f_work(npts, data,\n npgrns,\n Gxy,\n CONVCOR_FULL,\n lc, xcorr);\n }\n else if (i == 4)\n {\n cblas_dcopy(npgrns, Gxz, 1, &Gmat[i], 8);\n ierr = signal_convolve_correlate64f_work(npts, data,\n npgrns,\n Gxz,\n CONVCOR_FULL,\n lc, xcorr);\n }\n else if (i == 5)\n {\n cblas_dcopy(npgrns, Gyz, 1, &Gmat[i], 8);\n ierr = signal_convolve_correlate64f_work(npts, data,\n npgrns,\n Gyz,\n CONVCOR_FULL,\n lc, xcorr);\n }\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Error correlating Greens fn: %d\\n\",\n __func__, i+1);\n return -1;\n }\n cblas_dcopy(lc, xcorr, 1, &Gxc[i], 8);\n }\n array_zeros64f_work(lxc, xc);\n // Compute \\f$ x_c = \\sum_{i=1}^{n_{mt}} G \\textbf{m} \\star \\textbf{d} \\f$\n#pragma omp parallel shared(Gxc, Gmat, mt, lc, xc) \\\n firstprivate (dscal, xcorr) \\\n private (est, gscal, xscal, i, j, m6, xcw) default(none)\n{\n xcw = memory_calloc64f(lxc);\n#ifdef __INTEL_COMILER\n__assume_aligned(xcw, 64);\n#endif\n #pragma omp for\n for (i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../extern/include/f2c.h\"\n#include \"../extern/include/blaswrap.h\"\n#include \"../extern/include/clapack.h\"\n//#include \n//#include \n#include \"adkGSL.h\"\n\n#define SUM_LOG_THRESHOLD -10\n\n//gsl_matrix_covariance-- computes sample covariance matrix and stores it in matrix cov\nvoid gsl_matrix_covariance(gsl_matrix *data, gsl_matrix *cov){\n\tgsl_vector_view a, b;\n\tsize_t i, j;\n\tdouble v;\n\tfor (i = 0; i < data->size2; i++) {\n \t\tfor (j = 0; j < data->size2; j++) {\n \t\t\ta = gsl_matrix_column (data, i);\n \t\t\tb = gsl_matrix_column (data, j);\n \t\t\tv = gsl_stats_covariance (a.vector.data, a.vector.stride,\n \t\t\t\tb.vector.data, b.vector.stride, a.vector.size);\n \t\t\tgsl_matrix_set (cov, i, j, v);\n\t\t}\n\t}\n}\n\n\n/*gsl_vector_includes() - returns 1 or 0 depending on result */\nint gsl_vector_includes(gsl_vector *aVec, double aValue){\n int i;\n \n for(i = 0; i < aVec->size; i++){\n if (gsl_vector_get(aVec, i) == aValue){\n return(1);\n }\n }\n return(0);\n}\n\n\ndouble gsl_vector_sum(gsl_vector *aVec, int aVecSize){\n\tdouble sum;\n\tint i;\n\t\n\tsum = 0;\n\tfor (i = 0; i < aVecSize; i++){\n\t\tsum += gsl_vector_get(aVec, i);\n\t\t}\n\treturn sum;\n}\n\ndouble gsl_vector_dot_product(gsl_vector *vec1, gsl_vector *vec2){\n int i;\n double dot = 0.0;\n\n assert(vec1->size == vec2->size);\n for(i = 0; i < vec1->size; i++){\n dot += gsl_vector_get(vec1, i) * gsl_vector_get(vec2, i);\n }\n return(dot);\n}\n\nvoid gsl_vector_outer_product(gsl_vector *vec1, gsl_vector *vec2, gsl_matrix *result){\n\tint i,j;\n\t\n\tassert(vec1->size == result->size1 || vec2->size == result->size2);\n\tfor(i = 0; i < vec1->size; i++){\n\t\tfor(j = 0; j < vec2->size; j++){\n\t\t\tgsl_matrix_set(result,i,j,gsl_vector_get(vec1,i) * gsl_vector_get(vec2,j));\n\t\t}\n\t}\n}\n\n\ndouble gsl_matrix_row_sum(gsl_matrix *mat, int iRow, int rowSize){\n\tgsl_vector_view aRow;\n\tdouble sum = 0;\n\tint i;\n\t\n\taRow = gsl_matrix_row(mat, iRow);\n\tfor (i = 0; i< rowSize; i++){\n\t\tsum += gsl_vector_get(&aRow.vector, i);\n\t\t}\n\treturn sum;\n}\n\n/* efficiently compute log of sum of values, which themselves are\n stored as logs: that is, return log(sum_i exp(l_i)). The largest\n of the elements of l (call it maxval) is factored out, so that\n log(sum_i(exp(l_i))) = maxval + log(1 + sum_i(exp(l_i-maxval))),\n where the new sum is taken over 2 <= i < n. All of the quantities\n in the exp must be negative, and those smaller than some reasonable\n threshold can be ignored. [Thanks to David Haussler for showing me\n this trick]. This code was adapted from code kindly given to me by Adam Siepel */\n\ndouble log_sum(gsl_vector *vec) {\n double maxval, expsum;\n int k;\n\n if (vec->size > 1){\n \tgsl_sort_vector(vec);\n\tgsl_vector_reverse(vec);\n\t}\n\t\n maxval = gsl_vector_get(vec, 0);\n expsum = 1;\n k = 1;\n\n while (k < vec->size && gsl_vector_get(vec, k) - maxval > SUM_LOG_THRESHOLD){\n expsum += exp(gsl_vector_get(vec, k++) - maxval);\n\t}\n return maxval + log(expsum);\n}\n\n\n/*the following methods are wrappers for use with LAPACK */\n\nvoid set_lapack_entry(double *A, int i, int j, int nrows, double val){\n A[j*nrows+i] = val;\n}\n\ndouble get_lapack_entry(double *a, int i, int j,int nrows){\n printf(\"ha\");\n return a[j*nrows+i];\n}\n\n/*this is meant to be a conversion utility */\ndouble *gsl_matrix_2_lapack(gsl_matrix *m){\n double *lapack_mat;\n int i, j;\n\n lapack_mat = malloc(m->size1 * m->size2 * sizeof(double));\n for(i = 0; i < m->size1; i++){\n for(j = 0; j < m->size2; j++){\n set_lapack_entry(lapack_mat, i, j,m->size1, gsl_matrix_get(m, i, j));\n }\n }\n return lapack_mat;\n}\n\ngsl_matrix *lapack_2_gsl_matrix(double *A, int nrows, int ncols){\n int i, j;\n gsl_matrix *new;\n \n new = gsl_matrix_alloc(nrows,ncols);\n for(i=0;isize1, aMatrix->size2);\n for(i = 0; i < aMatrix->size1; i++){\n for(j = 0; j < aMatrix->size2; j++){\n x = gsl_matrix_get(powerMat, i, j);\n gsl_matrix_set(logMat, i, j, log(x));\n }\n }\n gsl_matrix_free(powerMat);\n return(logMat);\n}\n \ngsl_matrix *gsl_matrix_power(gsl_matrix *aMatrix, int power){\n gsl_matrix *revect, *levect;\n double *dataMat, *wr, *wi, *vl, *vr, *aMat, *bMat, *cMat, *dMat, *work;\n int lwork, i, j, n ,info;\n assert(aMatrix->size1 == aMatrix->size2);\n n = aMatrix->size1;\n\n if (power == 1){\n gsl_matrix * solMat = gsl_matrix_alloc(n, n);\n for(i=0; i < n; i++){\n for(j = 0; j< n; j++){\n\tgsl_matrix_set(solMat, i, j, gsl_matrix_get(aMatrix,i,j));\n }\n }\n return(solMat);\n }\n\n \n //allocate space for eigenvector matrices, and other result holders\n levect = gsl_matrix_alloc(n, n);\n revect = gsl_matrix_alloc(n, n);\n wr = malloc(n * sizeof(double));\n wi = malloc(n * sizeof(double));\n vl = malloc(n * n * sizeof(double));\n vr = malloc(n * n * sizeof(double));\n lwork = 20 * n;\n work = malloc(lwork * sizeof(double));\n \n //move data to LAPACK (col major) format\n dataMat = gsl_matrix_2_lapack(aMatrix);\n \n //run LAPACK routine dgeev\n #ifdef OSX\n dgeev('V','V',n, dataMat, n, wr, wi, vl, n, vr, n, work, lwork);\n #else\n dgeev_('V','V',n, dataMat, n, wr, wi, vl, n, vr, n, work, lwork, info);\n #endif\n //collect eigenvalues into matrices\n for(i=0; i < n; i++){\n for(j = 0; j< n; j++){\n gsl_matrix_set(revect, i, j, vr[j*2+i]);\n gsl_matrix_set(levect, j, i, vl[j*2+i]);\n }\n }\n \n /* rescale such that revect and levect are inverses */\n /* see Press et al. (Numerical Recipes) for a very clear explanation\n of the relationship between the left and right eigenvectors */\n for(i = 0; i < n; i++){\n double dotProd = 0.0;\n /* compute dot product of row i in levect and col i in revect */\n for(j = 0; j< n; j++){\n dotProd += gsl_matrix_get(levect, i, j) * gsl_matrix_get(revect,j,i); \n }\n \n /* now rescale levect */\n for(j = 0; j< n; j++){\n double old = gsl_matrix_get(levect, i, j);\n double scaled = old / dotProd;\n gsl_matrix_set(levect, i, j, scaled);\n } \n }\n\n //prepare for matrix multiplication\n gsl_matrix * solMat = gsl_matrix_alloc(n, n);\n gsl_matrix * diag = gsl_matrix_alloc(n, n);\n gsl_matrix_set_all(diag, 0);\n for(j = 0; j< n; j++){\n gsl_matrix_set(diag, j,j, pow(wr[j],power));\n }\n \n aMat = gsl_matrix_2_lapack(diag);\n bMat = gsl_matrix_2_lapack(revect);\n cMat = malloc(n * n * sizeof(double));\n\n //compute a^t = s^-1 * diag^t * s\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0, aMat, n, bMat, n, 0.0, cMat, n);\n free(bMat);\n\n bMat = gsl_matrix_2_lapack(levect);\n dMat = malloc(n * n * sizeof(double));\n cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n, n, n, 1, cMat, n, bMat, n, 0.0, dMat, n); \n\n //put results into gsl_matrix\n for(i = 0; i < n; i++){\n for(j = 0; j < n; j++){\n gsl_matrix_set(solMat, i, j, dMat[j*n+i]);\n }\n }\n \n //cleanup\n gsl_matrix_free(levect);\n gsl_matrix_free(revect);\n gsl_matrix_free(diag);\n free(work);\n free(vl);\n free(vr);\n free(wi);\n free(wr);\n free(aMat);\n free(bMat);\n free(cMat);\n free(dMat);\n free(dataMat);\n return(solMat);\n}\n\n//returns the trace of a matrix-- sum of diag\ndouble gsl_matrix_trace(gsl_matrix *x){\n\tint i;\n\tdouble sum = 0.0;\n\tfor(i=0;isize1;i++){\n\t\tsum += gsl_matrix_get(x,i,i);\n\t}\n\treturn(sum);\n}\n\n\n//copies the lower triangle of src in to dest, sets others to zero\nvoid gsl_matrix_lower_tri_copy(gsl_matrix *src, gsl_matrix *dest){\n\tint i, j;\n\tassert(src->size1 == dest->size1);\n\tassert(src->size2 == dest->size2);\n\tfor(i = 0; i < src->size1; i++){\n\t\tfor(j = 0; j < src->size2; j++){\n\t\t\tif(i<=j){\n\t\t\t\tgsl_matrix_set(dest,i,j,gsl_matrix_get(src,i,j));\n\t\t\t}\n\t\t\telse{\n\t\t\t\tgsl_matrix_set(dest,i,j,0.0);\n\t\t\t}\n\t\t}\n\t}\n}\n\n//copies the upper triangle of src in to dest, sets others to zero\nvoid gsl_matrix_upper_tri_copy(gsl_matrix *src, gsl_matrix *dest){\n\tint i, j;\n\tassert(src->size1 == dest->size1);\n\tassert(src->size2 == dest->size2);\n\tfor(i = 0; i < src->size1 ;i++){\n\t\tfor(j = 0; j < src->size2; j++){\n\t\t\tif(i>=j){\n\t\t\t\tgsl_matrix_set(dest,i,j,gsl_matrix_get(src,i,j));\n\t\t\t}\n\t\t\telse{\n\t\t\t\tgsl_matrix_set(dest,i,j,0.0);\n\t\t\t}\n\t\t}\n\t}\n}\n\n//zeros out everything but lower tri-- in place\nvoid gsl_matrix_lower_tri(gsl_matrix *x){\n\tint i, j;\n\tfor(i = 0; i < x->size1; i++){\n\t\tfor(j = 0; j < x->size2; j++){\n\t\t\tif(i>j)\tgsl_matrix_set(x,i,j,0.0);\n\t\t}\n\t}\n}\n\n//zeros out everything but upper tri-- in place\nvoid gsl_matrix_upper_tri(gsl_matrix *x){\n\t\tint i, j;\n\t\tfor(i = 0; i < x->size1; i++){\n\t\t\tfor(j = 0; j < x->size2; j++){\n\t\t\t\tif(isize1);\n\tfor(i = 0; i < nrow; i++){\n\t\tfor(j=0;jsize1);\n\tfor(i = 0; i < nrow; i++){\n\t\tfor(j=0;jsize1; i++){\n\t\tfor(j=0;jsize2;j++){\n\t\t\tgsl_vector_set(dest,count++, gsl_matrix_get(src,i,j));\n\t\t}\n\t}\n}\n\n\n\n//fillMatrixFromCholArray-- fills up a matrix based on nrow and ncol given arraay\n// representing the Cholesky decomp\nvoid fillMatrixFromCholArray(double *numbers, gsl_matrix *dest, int nrow, int ncol){\n\tint i, j, count = 0;\n\n\tfor(i = 0; i < nrow; i++){\n\t\tfor(j=0;jsize1; i++){\n\t\tfor(j=0;jsize2;j++){\n\t\t\tif(i<=j){\n\t\t\t\t gsl_vector_set(dest,count++, gsl_matrix_get(src,i,j));\n\t\t\t\t//printf(\"i:%d j: %d val: %f\\n\",i,j,gsl_matrix_get(src,i,j) );\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\n}\n\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////\n#ifdef OSX\n\n/*some wrappers for use with the OS X vecLib LAPACK implementation */\n/*wrapper for the lapack eigensystem routine dgeev_*/\n\nint dgeev(char jobvl, char jobvr, int n, double *a, int lda, double *wr, double *wi, double *vl, \n\t int ldvl,double *vr, int ldvr, double *work, int lwork){\n \n __CLPK_integer _n, _lda, _ldvl, _ldvr, _lwork, info;\n \n _n = (__CLPK_integer) n;\n _lda = (__CLPK_integer) lda;\n _ldvl =(__CLPK_integer) ldvl;\n _ldvr =(__CLPK_integer) ldvr;\n _lwork =(__CLPK_integer) lwork;\n \n dgeev_(&jobvl, &jobvr, &_n, a, &_lda, wr, wi, vl, &_ldvl, vr, &_ldvr, work, &_lwork, &info);\n return info;\n}\n\n/*wrapper for the lapack eigensystem routine dsyev_ \nint dsyev(char jobvl, char uplo, int n, double *a, int lda, double *w, double *work, int lwork){\n \n __CLPK_integer _n, _lda, _lwork, info;\n \n _n = (__CLPK_integer) n;\n _lda = (__CLPK_integer) lda;\n _lwork =(__CLPK_integer) lwork;\n \n dsyev_(&jobvl, &uplo, &_n, a, &_lda, w, work, &_lwork, &info);\n return info;\n}\n\nint dgehrd(int n, int ilo, int ihi, double *a, int lda, double *tau, double *work, int lwork){\n __CLPK_integer _n, _ilo, _ihi, _lda, _lwork, info;\n\n _n = (__CLPK_integer) n;\n _lda = (__CLPK_integer) lda;\n _lwork =(__CLPK_integer) lwork;\n _ilo =(__CLPK_integer) ilo;\n _ihi =(__CLPK_integer) ihi;\n \n dgehrd_(&_n, &_ilo, &_ihi, a, &_lda, tau, work, &_lwork, &info);\n return info;\n}\n\nint dgebal(char job, int n, double *a, int lda, int ilo, int ihi, double *scale){\n __CLPK_integer _n, _ilo, _ihi, _lda, info;\n\n _n = (__CLPK_integer) n;\n _lda = (__CLPK_integer) lda;\n _ilo =(__CLPK_integer) ilo;\n _ihi =(__CLPK_integer) ihi;\n \n dgebal_(&job, &_n, a, &_lda, &_ilo, &_ihi, scale, &info);\n return info;\n}\n\nint dhseqr(char job, char compz, int n, int ilo, int ihi,double *h, int ldh, double *wr, double *wi, double *z, int ldz, double *work, int lwork){\n __CLPK_integer _n, _ilo, _ihi, _ldh, _ldz, _lwork, info;\n\n _n = (__CLPK_integer) n;\n _ldh = (__CLPK_integer) ldh;\n _ilo =(__CLPK_integer) ilo;\n _ihi =(__CLPK_integer) ihi;\n _ldz = (__CLPK_integer) ldz;\n _lwork = (__CLPK_integer) lwork;\n dhseqr_(&job, &compz, &_n, &_ilo, &_ihi, h, &_ldh, wr, wi, z,&_ldz, work, &_lwork, &info);\n return info;\n}\n#endif\n\nint dgeev(char jobvl, char jobvr, int n, double *a, int lda, double *wr, double *wi, double *vl,\n int ldvl,double *vr, int ldvr, double *work, int lwork){\n\n long int _n, _lda, _ldvl, _ldvr, _lwork, info;\n\n _n = n;\n _lda = lda;\n _ldvl = ldvl;\n _ldvr = ldvr;\n _lwork = lwork;\n\n dgeev_(&jobvl, &jobvr, &_n, a, &_lda, wr, wi, vl, &_ldvl, vr, &_ldvr, work, &_lwork, &info);\n return info;\n}\n\nint dsyev(char jobvl, char uplo, int n, double *a, int lda, double *w, double *work, int lwork){\n\n long int _n, _lda, _lwork, info;\n\n _n = n;\n _lda = lda;\n _lwork = lwork;\n\n dsyev_(&jobvl, &uplo, &_n, a, &_lda, w, work, &_lwork, &info);\n return info;\n}\n\nint dgehrd(int n, int ilo, int ihi, double *a, int lda, double *tau, double *work, int lwork){\n long int _n, _ilo, _ihi, _lda, _lwork, info;\n\n _n = n;\n _lda = lda;\n _lwork = lwork;\n _ilo = ilo;\n _ihi = ihi;\n\n dgehrd_(&_n, &_ilo, &_ihi, a, &_lda, tau, work, &_lwork, &info);\n return info;\n}\n\nint dgebal(char job, int n, double *a, int lda, int ilo, int ihi, double *scale){\n long int _n, _ilo, _ihi, _lda, info;\n\n _n = n;\n _lda = lda;\n _ilo = ilo;\n _ihi = ihi;\n\n dgebal_(&job, &_n, a, &_lda, &_ilo, &_ihi, scale, &info);\n return info;\n}\n\nint dhseqr(char job, char compz, int n, int ilo, int ihi,double *h, int ldh, double *wr, double *wi, double *z, int ldz, double *work, int lwork){\n long int _n, _ilo, _ihi, _ldh, _ldz, _lwork, info;\n\n _n = n;\n _ldh = ldh;\n _ilo = ilo;\n _ihi = ihi;\n _ldz = ldz;\n _lwork = lwork;\n dhseqr_(&job, &compz, &_n, &_ilo, &_ihi, h, &_ldh, wr, wi, z,&_ldz, work, &_lwork, &info);\n return info;\n}\n*/\n#endif\n", "meta": {"hexsha": "dafcbca4c393de44f41359ffb1daced097eab7cd", "size": 14761, "ext": "c", "lang": "C", "max_stars_repo_path": "hmm/adkGSL.c", "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hmm/adkGSL.c", "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hmm/adkGSL.c", "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2651245552, "max_line_length": 146, "alphanum_fraction": 0.6271932796, "num_tokens": 5162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4341071741927113}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#define m(i,j) m[i*l+j]\n\n\ndouble* calcMys(char m[],int n,int l)\n{\n int i,j,k,k1,k2,k3,k4;\n char reslist[]={ 'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', \n 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'};\n int resnum=sizeof(reslist)/sizeof(char);\n double *simi;\n simi=malloc(n*n*sizeof(double));\n for (i=0;isimi[i*n+maxn[j]])\n max5=j;\n for (j=now;jsimi[i*n+maxn[max5]])\n {\n maxn[max5]=j;\n max5=-1;\n for(k=0;k<5;k++)\n if (max5==-1||simi[i*n+maxn[max5]]>simi[i*n+maxn[k]])\n max5=k;\n }\n }\n for (j=0;j<5;j++)\n {\n edge[edgenow*2+0]=i;\n edge[edgenow*2+1]=maxn[j];\n edgenow++;\n }\n }\n free(simi);\n double *mys;\n int n1=0,n2=0;\n mys=malloc(l*l*sizeof(double));\n for (i=0;i\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define NR_END 1\n#define FREE_ARG char*\n\n\n#define EXIT_MISSING_FILE(ein, purpose, filename) if (!ein) {fprintf(stderr, \"Could not find %s file %s\\n\",purpose,filename);exit(1);}\n\n\nstatic double darg __attribute__((unused)),maxarg1 __attribute__((unused)), maxarg2 __attribute__((unused));\n\n#define FMAX(a,b) (maxarg1=(a), maxarg2=(b), (maxarg1) > (maxarg2) ? (maxarg1) : (maxarg2))\n#define FMIN(a,b) (maxarg1=(a), maxarg2=(b), (maxarg1) < (maxarg2) ? (maxarg1) : (maxarg2))\n\n\n//Note: SQR*SQR....gives undefined warning\nstatic double sqrarg;\n#define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 : sqrarg*sqrarg)\nstatic double cubearg;\n#define CUBE(a) ((cubearg=(a)) == 0.0 ? 0.0 : cubearg*cubearg*cubearg)\nstatic double pow4arg;\n#define POW4(a) ((pow4arg=(a)) == 0.0 ? 0.0 : pow4arg*pow4arg*pow4arg*pow4arg)\n\nvoid SVD_inversion(gsl_matrix *cov, gsl_matrix *inverseSVD,int Nmatrix);\ndouble interpol2d(double **f, int nx, double ax, double bx, double dx, double x, int ny, double ay, double by, double dy, double y, double lower, double upper);\ndouble interpol2d_fitslope(double **f, int nx, double ax, double bx, double dx, double x, int ny, double ay, double by, double dy, double y, double lower);\n\ndouble interpol(double *f, int n, double a, double b, double dx, double x, double lower, double upper);\ndouble interpol_fitslope(double *f, int n, double a, double b, double dx, double x, double lower);\nvoid free_double_vector(double *v, long nl, long nh);\nlong *long_vector(long nl, long nh);\nint *int_vector(long nl, long nh);\ndouble *create_double_vector(long nl, long nh);\nvoid free_double_matrix(double **m, long nrl, long nrh, long ncl, long nch);\ndouble **create_double_matrix(long nrl, long nrh, long ncl, long nch);\nint line_count(char *filename);\n\nvoid error(char *s);\nvoid cdgamma(fftw_complex x, fftw_complex *res);\n\ndouble int_gsl_integrate_insane_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter);\ndouble int_gsl_integrate_high_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter);\ndouble int_gsl_integrate_medium_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter);\ndouble int_gsl_integrate_low_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter);\ndouble int_gsl_integrate_cov_precision(double (*func)(double, void*),void *arg,double a, double b, double *error, int niter);\n\ntypedef struct {\n double pi;\n double pi_sqr;\n double twopi;\n double ln2;\n double arcmin;\n double lightspeed;\n}con;\n\ncon constants = {\n 3.14159265358979323846, //pi\n 9.86960440108935861883, //pisqr\n 6.28318530717958647693, //twopi\n 0.69314718,\n 2.90888208665721580e-4, //arcmin\n 299792.458 //speed of light km/s\n};\n\n\ntypedef struct {\n double low;\n double medium;\n double high;\n double insane;\n}pre;\n\n\npre precision= {\n 1e-2, //low\n 1e-3, //medium\n 1e-5, //high\n 1e-7 //insane\n};\n\n\ntypedef struct {\n double a_min;\n double k_min_mpc;\n double k_max_mpc;\n double k_max_mpc_class;\n double k_min_cH0;\n double k_max_cH0;\n double P_2_s_min;\n double P_2_s_max;\n double xi_via_hankel_theta_min;\n double xi_via_hankel_theta_max;\n double xi_3d_rmin;\n double xi_3d_rmax;\n double M_min;\n double M_max;\n}lim;\n\n\n\nlim limits = {\n//\t0.19, //a_min (in order to compute z=4 WFIRST)\n 1./(1.+10.), //a_min (z=10, needed for CMB lensing)\n\t6.667e-6, //k_min_mpc\n\t1.e3, //k_max_mpc\n\t50., //k_max_mpc_class\n\t2.e-2, //k_min_cH0\n\t3.e+6, //k_max_cH0\n\t0.1,//P_2_s_min\n\t1.0e5,//P_2_s_max\n\t3.0e-7,//xi_via_hankel_theta_min\n\t0.12, //xi_via_hankel_theta_max\n 1.e-5,//xi_3d_rmin\n 1.e+0,//xi_3d_rmax\n\t1.e+6, //M_min\n\t1.e+17,//M_max\n};\n\n\ntypedef struct {\n int N_a ;\n int N_k_lin;\n int N_k_nlin;\n int N_ell;\n int N_theta;\n int N_thetaH;\n int N_S2;\n int N_DS;\n int N_norm;\n int N_r_3d;\n int N_k_3d;\n int N_a_halo;\n}Ntab;\n\n\n\nNtab Ntable = {\n100, //N_a\n500, //N_k_lin\n500, //N_k_nlin\n200, //N_ell\n200, //N_theta\n2048, //N_theta for Hankel\n1000, //N_S2\n1000, //N_DS\n50, //N_norm\n50, //N_r_3d\n25, //N_k_3d\n20, //N_a_halo\n};\n\n\nstruct cos{\n int ORDER ;\n double vt_max;\n double vt_min;\n double vt_bin_max;\n double vt_bin_min;\n int ni ;\n int nj ;\n};\n\nvoid SVD_inversion(gsl_matrix *cov, gsl_matrix *inverseSVD,int Nmatrix)\n{\n int i,j;\n gsl_matrix *V=gsl_matrix_calloc(Nmatrix,Nmatrix);\n gsl_matrix *U=gsl_matrix_calloc(Nmatrix,Nmatrix);\n gsl_vector *S=gsl_vector_calloc(Nmatrix);\n gsl_vector *work=gsl_vector_calloc(Nmatrix);\n\n gsl_matrix_memcpy(U,cov);\n\n gsl_linalg_SV_decomp(U,V,S,work);\n\n for (i=0;i= n) {\n\t\tif (upper==0.0) {\n\t\t\tif (i+1==n) {\n\t\t\t\treturn f[i]; /* constant extrapolation */\n\t\t\t} else {\n\t\t\t\t//error(\"value too big in interpol\");\n\t\t\t\treturn 0.0;\n\t\t\t}\n\t\t} else {\n\t\t\treturn f[n-1] + upper*(x-b); /* linear extrapolation */\n\t\t}\n\t} else {\n\t\treturn (r - i)*(f[i+1] - f[i]) + f[i]; /* interpolation */\n\t}\n}\ndouble interpol_fitslope(double *f, int n, double a, double b, double dx, double x, double lower)\n{\n\tdouble r;\n\tint i,fitrange;\n\tif (x < a) {\n\t\tif (lower==0.) {\n\t\t\t//error(\"value too small in interpol\");\n\t\t\treturn 0.0;\n\t\t}\n\t\treturn f[0] + lower*(x - a);\n\t}\n\tr = (x - a)/dx;\n\ti = (int)(floor(r));\n\tif (i+1 >= n) {\n\t\tif (n > 50){fitrange =5;}\n\t\telse{fitrange = (int)floor(n/10);}\n\t\tdouble upper = (f[n-1] - f[n-1-fitrange])/(dx*fitrange);\n\t\treturn f[n-1] + upper*(x-b); /* linear extrapolation */\n\n\t} else {\n\t\treturn (r - i)*(f[i+1] - f[i]) + f[i]; /* interpolation */\n\t}\n}\n\n\n/* ============================================================ *\n * like interpol, but f beeing a 2d-function\t\t\t*\n * 'lower' and 'upper' are the powers of a power law extra-\t*\n * polation in the second argument\t\t\t\t*\n * ============================================================ */\ndouble interpol2d(double **f,\n\t\t int nx, double ax, double bx, double dx, double x,\n\t\t int ny, double ay, double by, double dy, double y,\n\t\t double lower, double upper)\n{\n\tdouble t, dt, s, ds;\n\tint i, j;\n\tif (x < ax) {\n\t\treturn 0.;\n//\t\terror(\"value too small in interpol2d\");\n\t}\n\n\tif (x > bx) {\n\t\treturn 0.;//\n//\t\tprintf(\"%le %le\\n\",x,bx);\n\t//\terror(\"value too big in interpol2d\");\n\t}\n\tt = (x - ax)/dx;\n\ti = (int)(floor(t));\n\tdt = t - i;\n\tif (y < ay) {\n\t\treturn ((1.-dt)*f[i][0] + dt*f[i+1][0]) + (y-ay)*lower;\n\t} else if (y > by) {\n\t\treturn ((1.-dt)*f[i][ny-1] + dt*f[i+1][ny-1]) + (y-by)*upper;\n\t}\n\ts = (y - ay)/dy;\n\tj = (int)(floor(s));\n\tds = s - j;\n\tif ((i+1==nx)&&(j+1==ny)) {\n\t //printf(\"%d %d\\n\",i+1,j+1);\n\t return (1.-dt)*(1.-ds)*f[i][j];\n\n\t}\n\tif (i+1==nx){\n\t //printf(\"%d %d\\n\",i+1,j+1);\n\t return (1.-dt)*(1.-ds)*f[i][j]+ (1.-dt)*ds*f[i][j+1];\n\t}\n\tif (j+1==ny){\n\t //printf(\"%d %d\\n\",i+1,j+1);\n\t return (1.-dt)*(1.-ds)*f[i][j]+ dt*(1.-ds)*f[i+1][j];\n\t}\n\treturn (1.-dt)*(1.-ds)*f[i][j] +(1.-dt)*ds*f[i][j+1] + dt*(1.-ds)*f[i+1][j] + dt*ds*f[i+1][j+1];\n}\ndouble interpol2d_fitslope(double **f,\n\t\t int nx, double ax, double bx, double dx, double x,\n\t\t int ny, double ay, double by, double dy, double y,\n\t\t double lower)\n{\n\tdouble t, dt, s, ds, upper;\n\tint i, j, fitrange;\n\tif (x < ax) {\n\t\treturn 0.;\n//\t\terror(\"value too small in interpol2d\");\n\t}\n\n\tif (x > bx) {\n\t\treturn 0.;\n//\tprintf(\"%le %le\\n\",x,bx);\n//\t error(\"value too big in interpol2d\");\n\t}\n\tt = (x - ax)/dx;\n\ti = (int)(floor(t));\n\tdt = t - i;\n\tif (y < ay) {\n\t\treturn ((1.-dt)*f[i][0] + dt*f[i+1][0]) + (y-ay)*lower;\n\t} else if (y > by) {\n\t\tif (ny > 25){fitrange =5;}\n\t\telse{fitrange = (int)floor(ny/5);}\n\t\tupper = ((1.-dt)*(f[i][ny-1] - f[i][ny-1-fitrange])+dt*(f[i+1][ny-1] - f[i+1][ny-1-fitrange]))/(dy*fitrange);\n\t\treturn ((1.-dt)*f[i][ny-1] + dt*f[i+1][ny-1]) + (y-by)*upper;\n\t}\n\ts = (y - ay)/dy;\n\tj = (int)(floor(s));\n\tds = s - j;\n\tif ((i+1==nx)&&(j+1==ny)) {\n\t //printf(\"%d %d\\n\",i+1,j+1);\n\t return (1.-dt)*(1.-ds)*f[i][j];\n\n\t}\n\tif (i+1==nx){\n\t //printf(\"%d %d\\n\",i+1,j+1);\n\t return (1.-dt)*(1.-ds)*f[i][j]+ (1.-dt)*ds*f[i][j+1];\n\t}\n\tif (j+1==ny){\n\t //printf(\"%d %d\\n\",i+1,j+1);\n\t return (1.-dt)*(1.-ds)*f[i][j]+ dt*(1.-ds)*f[i+1][j];\n\t}\n\treturn (1.-dt)*(1.-ds)*f[i][j] +(1.-dt)*ds*f[i][j+1] + dt*(1.-ds)*f[i+1][j] + dt*ds*f[i+1][j+1];\n}\n\n\nvoid cdgamma(fftw_complex x, fftw_complex *res)\n{\n\tdouble xr, xi, wr, wi, ur, ui, vr, vi, yr, yi, t;\n\n\txr = (double) x[0];\n\txi = (double) x[1];\n\n\tif (xr<0) {\n\t\twr = 1 - xr;\n\t\twi = -xi;\n\t} else {\n\t\twr = xr;\n\t\twi = xi;\n\t}\n\n\tur = wr + 6.00009857740312429;\n\tvr = ur * (wr + 4.99999857982434025) - wi * wi;\n\tvi = wi * (wr + 4.99999857982434025) + ur * wi;\n\tyr = ur * 13.2280130755055088 + vr * 66.2756400966213521 +\n\t\t\t0.293729529320536228;\n\tyi = wi * 13.2280130755055088 + vi * 66.2756400966213521;\n\tur = vr * (wr + 4.00000003016801681) - vi * wi;\n\tui = vi * (wr + 4.00000003016801681) + vr * wi;\n\tvr = ur * (wr + 2.99999999944915534) - ui * wi;\n\tvi = ui * (wr + 2.99999999944915534) + ur * wi;\n\tyr += ur * 91.1395751189899762 + vr * 47.3821439163096063;\n\tyi += ui * 91.1395751189899762 + vi * 47.3821439163096063;\n\tur = vr * (wr + 2.00000000000603851) - vi * wi;\n\tui = vi * (wr + 2.00000000000603851) + vr * wi;\n\tvr = ur * (wr + 0.999999999999975753) - ui * wi;\n\tvi = ui * (wr + 0.999999999999975753) + ur * wi;\n\tyr += ur * 10.5400280458730808 + vr;\n\tyi += ui * 10.5400280458730808 + vi;\n\tur = vr * wr - vi * wi;\n\tui = vi * wr + vr * wi;\n\tt = ur * ur + ui * ui;\n\tvr = yr * ur + yi * ui + t * 0.0327673720261526849;\n\tvi = yi * ur - yr * ui;\n\tyr = wr + 7.31790632447016203;\n\tur = log(yr * yr + wi * wi) * 0.5 - 1;\n\tui = atan2(wi, yr);\n\tyr = exp(ur * (wr - 0.5) - ui * wi - 3.48064577727581257) / t;\n\tyi = ui * (wr - 0.5) + ur * wi;\n\tur = yr * cos(yi);\n\tui = yr * sin(yi);\n\tyr = ur * vr - ui * vi;\n\tyi = ui * vr + ur * vi;\n\tif (xr<0) {\n\t\twr = xr * 3.14159265358979324;\n\t\twi = exp(xi * 3.14159265358979324);\n\t\tvi = 1 / wi;\n\t\tur = (vi + wi) * sin(wr);\n\t\tui = (vi - wi) * cos(wr);\n\t\tvr = ur * yr + ui * yi;\n\t\tvi = ui * yr - ur * yi;\n\t\tur = 6.2831853071795862 / (vr * vr + vi * vi);\n\t\tyr = ur * vr;\n\t\tyi = ur * vi;\n\t}\n\n\t(*res)[0]=yr; (*res)[1]=yi;\n}\n", "meta": {"hexsha": "3d8a651fad6b31bca30719aff394bda709625a75", "size": 16695, "ext": "c", "lang": "C", "max_stars_repo_path": "cosmolike_core/theory/basics.c", "max_stars_repo_name": "joezuntz/CosmoCov", "max_stars_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-04-14T00:46:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:39:07.000Z", "max_issues_repo_path": "cosmolike_core/theory/basics.c", "max_issues_repo_name": "joezuntz/CosmoCov", "max_issues_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-12T19:43:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T16:27:09.000Z", "max_forks_repo_path": "cosmolike_core/theory/basics.c", "max_forks_repo_name": "joezuntz/CosmoCov", "max_forks_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T20:17:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:30:53.000Z", "avg_line_length": 27.6865671642, "max_line_length": 162, "alphanum_fraction": 0.6154537287, "num_tokens": 5714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4339632286121159}} {"text": "#ifndef _PK_SLOPE_H_\n#define _PK_SLOPE_H_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"cspline.h\"\n#include \"file_check.h\"\n\ntemplate class pkSlope{\n int N;\n std::vector k, Pk, n;\n cspline slope;\n \n void get_pk_spline();\n \n void calculate_n();\n \n void get_n_spline();\n \n public:\n cspline power;\n \n pkSlope();\n \n pkSlope(std::string in_pk_file);\n \n void initialize(std::string in_pk_file);\n \n void calculate();\n \n void get_device_spline(std::vector &d_spline);\n \n void get_device_spline(std::vector &d_spline);\n \n};\n\ntemplate double f(double x, void *params) {\n cspline Pow = *(cspline *)params;\n return Pow.evaluate(x);\n}\n\ntemplate void pkSlope::get_pk_spline() {\n pkSlope::power.initialize(pkSlope::k, pkSlope::Pk);\n}\n\ntemplate void pkSlope::calculate_n() {\n gsl_function F;\n double result, err;\n \n F.function = &f;\n F.params = &power;\n \n for (int i = 0; i < pkSlope::N; ++i) {\n if (i == 0) {\n gsl_deriv_forward(&F, pkSlope::k[i], 1e-8, &result, &err);\n } else if (i == pkSlope::N - 1) {\n gsl_deriv_backward(&F, pkSlope::k[i], 1e-8, &result, &err);\n } else {\n gsl_deriv_central(&F, pkSlope::k[i], 1e-8, &result, &err);\n }\n pkSlope::n.push_back(result);\n }\n}\n\ntemplate void pkSlope::get_n_spline() {\n pkSlope::slope.initialize(pkSlope::k, pkSlope::n);\n}\n\ntemplate pkSlope::pkSlope() {\n pkSlope::N = 0;\n}\n\ntemplate pkSlope::pkSlope(std::string in_pk_file) {\n pkSlope::initialize(in_pk_file);\n}\n \ntemplate void pkSlope::initialize(std::string in_pk_file) {\n if (check_file_exists(in_pk_file)) {\n std::ifstream fin(in_pk_file);\n while(!fin.eof()) {\n T kt, pt;\n fin >> kt >> pt;\n if (!fin.eof()) {\n pkSlope::k.push_back(log10(kt));\n pkSlope::Pk.push_back(log10(pt));\n }\n }\n fin.close();\n \n pkSlope::N = pkSlope::k.size();\n }\n}\n\ntemplate void pkSlope::calculate() {\n pkSlope::get_pk_spline();\n pkSlope::calculate_n();\n pkSlope::get_n_spline();\n}\n\ntemplate void pkSlope::get_device_spline(std::vector &d_spline) {\n pkSlope::slope.set_pointer_for_device(d_spline);\n}\n\ntemplate void pkSlope::get_device_spline(std::vector &d_spline) {\n pkSlope::slope.set_pointer_for_device(d_spline);\n}\n\n#endif\n", "meta": {"hexsha": "f1544062afe6fb29aa52bdaa74d33d496871f421", "size": 2848, "ext": "h", "lang": "C", "max_stars_repo_path": "include/pk_slope.h", "max_stars_repo_name": "dpearson1983/BIMODAL", "max_stars_repo_head_hexsha": "6fd93c1f75c190629ec272786c46ff46d9d7bd98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/pk_slope.h", "max_issues_repo_name": "dpearson1983/BIMODAL", "max_issues_repo_head_hexsha": "6fd93c1f75c190629ec272786c46ff46d9d7bd98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/pk_slope.h", "max_forks_repo_name": "dpearson1983/BIMODAL", "max_forks_repo_head_hexsha": "6fd93c1f75c190629ec272786c46ff46d9d7bd98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.203539823, "max_line_length": 90, "alphanum_fraction": 0.5821629213, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4339122709457716}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"ray.h\"\n\n#define pi M_PI\n\n\n//#############################################################################\n//#############################################################################\n//Mode finder\n\n//Data structure for julia cavity data and mode parameters\ntypedef struct {\n //Julia cavity info and functions -----------------------------------------\n //pointer to Boundary object\n void *bnd;\n //pointer to radius function\n double (*rfunc_p)(void *bnd,double theta);\n //pointer to (mutating) radius and normal vector angle function\n void (*rsys_p)(void *bnd, double theta, double results[]);\n //pointer to RefractiveIndex object\n void *idx;\n //pointer to refractive index value function\n double (*nfunc_p)(void *idx, double r, double theta);\n //pointer to (mutating) refractive index value and derivative function\n void (*nderiv_p)(void *idx, double r, double theta, double results[]);\n \n //mode-specific parameters ------------------------------------------------\n long order; //number of bounces in a period\n double rtol; //stopping criterion tolerance\n \n //preallocated arrays -----------------------------------------------------\n double *raypath_r;\n double *raypath_theta;\n long *bounceindices;\n double *bouncepts_chi;\n long *lengths;\n double *modebounces;\n} modeinfo;\n\n\n//#############################################################################\n//Function for rootfinding\nint rootfunc(const gsl_vector *x, void *params, gsl_vector *f){\n \n //params is pointer to modeinfo struct containing both cavity info and \n //simulation parameters\n modeinfo *mip = (modeinfo *)params;\n const long order = (*mip).order;\n double *raypath_r = (double *)(*mip).raypath_r;\n double *raypath_theta = (double *)(*mip).raypath_theta;\n long *bounceindices = (long *)(*mip).bounceindices;\n double *bouncepts_chi = (double *)(*mip).bouncepts_chi;\n long *lengths = (long *)(*mip).lengths;\n \n //Extract initial condition data (print for debugging)\n const double theta0 = gsl_vector_get(x,0), chi0 = gsl_vector_get(x,1);\n //printf(\"theta0 = %.8f, chi0 = %.8f\\n\",theta0,chi0);\n \n //Check for sensible values\n if(fabs(chi0) > pi/2){\n //Out of domain\n return GSL_EDOM;\n }\n \n //Setup initial ODE coordinate vector components\n double results[2];\n (*(*mip).rsys_p)((*mip).bnd,theta0,results);\n //result[0] = r0, results[1] = normang0\n const double n = (*(*mip).nfunc_p)((*mip).idx,results[0],theta0);\n const double phi0 = results[1] + chi0;\n const double pr0 = n*cos(phi0-theta0);\n const double ptheta0 = n*results[0]*sin(phi0-theta0);\n \n //Compute ray\n rayevolve(\n //Storage arrays\n raypath_r,raypath_theta,bounceindices,bouncepts_chi,lengths,\n //Initial conditions\n results[0],theta0,pr0,ptheta0,\n //Simulation parameters\n 200.0,order+1,1e-12,1e-12,\n //Cavity parameters\n (*mip).bnd,(*mip).rfunc_p,(*mip).rsys_p,\n (*mip).idx,(*mip).nfunc_p,(*mip).nderiv_p);\n \n //Store difference in initial and final bounce locations (print for debugging)\n const double dtheta = fmod(raypath_theta[bounceindices[order]-1] - raypath_theta[bounceindices[0]-1] + pi, 2*pi) - pi;\n const double dchi = bouncepts_chi[order] - bouncepts_chi[0];\n gsl_vector_set(f,0,dtheta);\n gsl_vector_set(f,1,dchi);\n //printf(\"dtheta = %.8f, dchi = %.8f\\n\",dtheta,dchi);\n \n //Test stopping criterion\n if(gsl_multiroot_test_residual(f,(*mip).rtol) != GSL_CONTINUE){\n //Record mode bounce data in results array (to avoid running simulation again)\n double *modebounces = (double *)(*mip).modebounces;\n //theta values stored in first half of array (first column after reshaping)\n //chi values stored in second half of array (second column after reshaping)\n int i;\n for(i=0; i\n\n#include \n#include \n\n#include \n#include \n#include \n\n\n#define COUNT(arr) (sizeof(arr) / sizeof(arr[0]))\n\ntypedef enum result_t {\n RESULT_OK = 0,\n RESULT_LAMBDA_FAILED = 1,\n RESULT_X_FAILED = 2,\n RESULT_GSL_ERROR = 3,\n RESULT_HIT_CRITICAL_POINT = 4,\n} result_t;\n\n\ntypedef enum handedness_t {\n R_MODE = 1,\n L_MODE = -1,\n} handedness_t;\n\n\ntypedef enum wave_filtering_t {\n WF_ALL_WAVES = 0,\n WF_NO_FORWARD_MODES = 1 << 0,\n WF_NO_BACKWARD_MODES = 1 << 1,\n} wave_filtering_t;\n\n\ntypedef enum integration_type_t {\n ITYPE_BOUNCE_AVERAGED,\n ITYPE_LOCAL,\n} integration_type_t;\n\n\ntypedef struct parameters_t {\n double E; /* dimensionless kinetic energy */\n double sin_alpha; /* sine of the pitch angle */\n double Omega_e; /* local electron gyrofrequency in rad/s */\n handedness_t handedness; /* handedness of wave; `s` in Summers/Shprits notation */\n double alpha_star; /* (cyclotron freq / plasma freq)**2 */\n double R; /* magnetic wave energy perturbation: (delta B / B)**2 */\n double x_m; /* center of wave frequency spectrum in units of cyclotron freq */\n double delta_x; /* width of wave frequency spectrum in units of cyclotron freq */\n double max_wave_latitude; /* maximum latitude at which waves are found, in radians */\n wave_filtering_t wave_filtering; /* which kinds of waves to filter out */\n} parameters_t;\n\n\ntypedef struct state_t {\n parameters_t p;\n integration_type_t itype;\n result_t last_error;\n\n double gamma; /* Lorentz factor */\n double a; /* See Summers 2005, just after Eqn 24 */\n double b; /* See Summers 2005, just after Eqn 25 */\n double beta; /* velocity over speed of light */\n\n double latitude; /* current magnetic latitude, radians */\n double sin_alpha; /* current sin(alpha); varies since mu is conserved */\n double mu; /* current cos(alpha) */\n double Omega_e; /* current Omega_e; varies with latitude since it scales as B */\n\n int n_xy; /* Number of resonances encountered */\n double x[3]; /* x values of resonances */\n double y[3]; /* y values of resonances */\n double Q[3]; /* (1 - x cos alpha / y beta) */\n double R[3]; /* complex expression in summand */\n} state_t;\n\n\ntypedef struct coefficients_t {\n double dimensionless_p; /* momentum over (m_0 * c) */\n double Daa;\n double err_Daa;\n double Dap_on_p;\n double err_Dpp_on_p2;\n double Dpp_on_p2;\n double err_Dap_on_p;\n} coefficients_t;\n\n\nstatic state_t *global_context = NULL;\nstatic char global_err_msg[1024] = \"\";\n\nstatic void\ns05_error_handler(const char *reason, const char *file, int line, int gsl_errno)\n{\n /* Go ahead and segfault if global_context is NULL. */\n\n int n;\n\n n = snprintf(global_err_msg, COUNT(global_err_msg),\n \"%s (%s:%d; %d = %s)\", reason, file, line, gsl_errno, gsl_strerror(gsl_errno));\n if ((size_t) n > COUNT(global_err_msg))\n n = COUNT(global_err_msg) - 1;\n global_err_msg[n] = '\\0';\n\n global_context->last_error = RESULT_GSL_ERROR;\n}\n\nvoid\nsummers2005_debug_hook(void)\n{\n printf(\"Debug hook called.\\n\");\n}\n\nstatic gsl_integration_workspace *integ_workspace = NULL; /* We're lame and leak these */\nstatic gsl_poly_complex_workspace *poly5_workspace = NULL;\nstatic gsl_poly_complex_workspace *poly7_workspace = NULL;\n\nconst size_t INTEG_WS_SIZE = 512;\nconst double integ_abs_tol = 0.0;\nconst double integ_rel_tol = 1e-6;\n\n\nconst int lambda = -1; /* signifies that we're looking at electrons */\nconst double epsilon = 0.0005446; /* electron-to-proton mass ratio */\nconst double epsm1 = -0.9994554; /* epsilon - 1; C is lame and can't do the math with consts! */\nconst double sigma = 2.; /* range of `x` that we consider */\nconst double pi_on_2nu = 0.89039; /* pi/2nu, nu = sqrt(pi)erf(sigma); see after Shprits 06 Eqn 5 */\n\n\nstatic inline result_t\napply_latitude(double latitude, state_t *state)\n{\n int i;\n\n if (state->last_error != RESULT_OK)\n return state->last_error;\n\n state->latitude = latitude;\n\n double scl = cos(latitude); /* sin of colatitude = cos of latitude */\n double r = sqrt(4 - 3 * scl * scl) / pow(scl, 6); /* B(lam) / B_eq */\n\n state->Omega_e = state->p.Omega_e * r;\n state->sin_alpha = state->p.sin_alpha * sqrt(r);\n state->mu = sqrt(1 - state->sin_alpha * state->sin_alpha); /* cos(alpha) */\n\n if (state->mu == 0.) /* happens at the very top of our bounce trajectory */\n state->mu = 1e-20;\n\n /* Find the critical `x` and `y` values. We do this following Appendix A\n * and Equation 24 of Summers 2005. */\n\n state->n_xy = 0;\n\n double c[5] = { 0 };\n double z[8] = { 0 };\n\n const int s = state->p.handedness;\n const double a = state->a;\n const double a2 = a * a;\n const double bm2 = pow(state->beta * state->mu, 2);\n\n c[0] = -a2 * epsilon;\n c[1] = a2 * s * epsm1 - 2 * a * epsilon;\n c[2] = a2 + 2 * a * s * epsm1 - epsilon + bm2 * (state->b + epsilon);\n c[3] = 2 * a + s * epsm1 - bm2 * s * epsm1;\n c[4] = 1 - bm2;\n\n gsl_poly_complex_solve(c, 5, poly5_workspace, z);\n\n if (state->last_error != RESULT_OK) {\n strncat(global_err_msg, \" (while finding x/y roots)\", COUNT(global_err_msg) - 1);\n return state->last_error;\n }\n\n for (i = 0; i < 4; i++) {\n if (z[2*i + 1] != 0.) /* Imaginary root? */\n continue;\n\n double x = z[2*i];\n\n if (x < 0) /* Non-physical root? */\n continue;\n\n if (x < state->p.x_m - sigma * state->p.delta_x || x > state->p.x_m + sigma * state->p.delta_x)\n continue; /* Out of waveband? */\n\n double y = (x + state->a) / (state->beta * state->mu);\n\n if ((state->p.wave_filtering & WF_NO_FORWARD_MODES) && y > 0)\n continue;\n\n if ((state->p.wave_filtering & WF_NO_BACKWARD_MODES) && y < 0)\n continue;\n\n state->x[state->n_xy] = x;\n state->y[state->n_xy] = y;\n state->n_xy++;\n }\n\n if (state->n_xy > 3) {\n snprintf(global_err_msg, COUNT(global_err_msg), \"expect 0 to 3 X/Y solutions; got %d\", state->n_xy);\n return RESULT_X_FAILED;\n }\n\n /* Now we calculate F(x,y) = dx/dy, following Appendix C of Summers 2005,\n * and related values that contribute to the sums in the integrands. `Q`\n * is `1 - x cosa / y beta` and `R` is the factor that is in common\n * between all three calculations. */\n\n for (i = 0; i < state->n_xy; i++) {\n double x = state->x[i];\n double y = state->y[i];\n\n c[0] = epsilon * (state->b + epsilon);\n c[1] = -0.5 * s * epsm1 * (state->b + 4 * epsilon);\n c[2] = 1 - 4 * epsilon + epsilon * epsilon;\n c[3] = 2 * s * epsm1;\n c[4] = 1.;\n\n double g = gsl_poly_eval(c, 5, x);\n double F = y * pow((x - s) * (x + s * epsilon), 2) / (x * g);\n\n state->Q[i] = 1 - x * state->mu / (y * state->beta);\n\n double k0 = pow((x - state->p.x_m) / state->p.delta_x, 2);\n double k1 = fabs(state->beta * state->mu - F);\n\n if (k1 < 1e-5) {\n snprintf(global_err_msg, COUNT(global_err_msg), \"hit a critical point (%f, %f, %f)\",\n state->sin_alpha, x, y);\n return RESULT_HIT_CRITICAL_POINT;\n }\n\n state->R[i] = state->p.R * fabs(F) * exp(-k0) / (state->p.delta_x * k1);\n }\n\n return RESULT_OK;\n}\n\n\ntypedef double (*gsl_signature)(double, void *);\n\nstatic double\ndaa_integrand(double latitude, state_t *state)\n{\n result_t r;\n\n if (state->last_error != RESULT_OK)\n return 0;\n\n if ((r = apply_latitude(latitude, state)) != RESULT_OK) {\n state->last_error = r;\n return 0;\n }\n\n int i;\n double v = 0;\n\n for (i = 0; i < state->n_xy; i++)\n v += state->R[i] * pow(state->Q[i], 2);\n\n if (state->itype == ITYPE_BOUNCE_AVERAGED)\n v *= state->mu * pow(cos(state->latitude), 7);\n\n return v * state->Omega_e;\n}\n\n\nstatic double\ndap_on_p_integrand(double latitude, state_t *state)\n{\n result_t r;\n\n if (state->last_error != RESULT_OK)\n return 0;\n\n if ((r = apply_latitude(latitude, state)) != RESULT_OK) {\n state->last_error = r;\n return 0;\n }\n\n int i;\n double v = 0;\n\n for (i = 0; i < state->n_xy; i++)\n v += state->R[i] * state->Q[i] * state->x[i] / state->y[i];\n\n /* Here we transform the sqrt(1 + 3 sin^2 lambda) term to use the cos\n * instead */\n\n double cos_lam = cos(state->latitude);\n double sa = state->sin_alpha;\n\n if (state->itype == ITYPE_BOUNCE_AVERAGED)\n v *= state->mu * cos_lam * sqrt(4 - 3 * cos_lam * cos_lam) / sa;\n\n return v * state->Omega_e * sa;\n}\n\n\nstatic double\ndpp_on_p2_integrand(double latitude, state_t *state)\n{\n result_t r;\n\n if (state->last_error != RESULT_OK)\n return 0;\n\n if ((r = apply_latitude(latitude, state)) != RESULT_OK) {\n state->last_error = r;\n return 0;\n }\n\n int i;\n double v = 0;\n\n for (i = 0; i < state->n_xy; i++)\n v += state->R[i] * pow(state->x[i] / state->y[i], 2);\n\n /* Same transform as in dap_on_p. */\n\n double cos_lam = cos(state->latitude);\n double sa = state->sin_alpha;\n\n if (state->itype == ITYPE_BOUNCE_AVERAGED)\n v *= cos_lam * sqrt(4 - 3 * cos_lam * cos_lam) / state->mu;\n\n return v * state->Omega_e * sa * sa;\n}\n\n\nstatic result_t\ncalc_coefficients(parameters_t *params, coefficients_t *coeffs)\n{\n gsl_error_handler_t *prev_handler;\n gsl_function integrand;\n state_t state;\n double c[7] = { 0 };\n double z[12] = { 0 };\n double lambda_m = -1;\n double result, abserr, k;\n int i;\n\n if (params->sin_alpha > 0.99985) /* ~= 89 degrees */\n params->sin_alpha = 0.99985;\n\n global_context = &state;\n prev_handler = gsl_set_error_handler(s05_error_handler);\n\n if (integ_workspace == NULL) {\n integ_workspace = gsl_integration_workspace_alloc(INTEG_WS_SIZE);\n poly5_workspace = gsl_poly_complex_workspace_alloc(5);\n poly7_workspace = gsl_poly_complex_workspace_alloc(7);\n }\n\n state.p = *params;\n state.itype = ITYPE_BOUNCE_AVERAGED;\n state.last_error = RESULT_OK;\n\n /* Figure out the mirroring latitude; Shprits (2006) equation 10. */\n\n double f0 = pow(state.p.sin_alpha, 4);\n c[0] = -4 * f0;\n c[1] = 3 * f0;\n c[6] = 1.;\n\n gsl_poly_complex_solve(c, 7, poly7_workspace, z);\n\n if (state.last_error != RESULT_OK) {\n strncat(global_err_msg, \" (while finding lambda_m)\", COUNT(global_err_msg) - 1);\n return state.last_error;\n }\n\n for (i = 0; i < 6; i++) {\n if (z[2*i + 1] == 0. && z[2*i] > 0) {\n lambda_m = acos(sqrt(z[2*i]));\n break;\n }\n }\n\n if (!(lambda_m >= 0 && lambda_m <= M_PI_2)) {\n gsl_set_error_handler(prev_handler);\n global_context = NULL;\n snprintf(global_err_msg, COUNT(global_err_msg), \"failed to compute lambda_m (%.16lf)\", lambda_m);\n return RESULT_LAMBDA_FAILED;\n }\n\n /* It can happen that lambda_m is just a tiiiiiny bit too large such that\n * when we compute the sine of the pitch angle at lambda_m, we get\n * something bigger than one. Witness our beautiful workaround.\n */\n\n double cos_lat = cos(lambda_m);\n\n if (sqrt(4 - 3 * cos_lat * cos_lat) / (pow(cos_lat, 6) * state.p.sin_alpha * state.p.sin_alpha) > 1.)\n lambda_m -= 1e-7;\n\n /* If a latitude limit on waves is imposed, truncate lambda_m further. */\n\n if (lambda_m > state.p.max_wave_latitude)\n lambda_m = state.p.max_wave_latitude;\n\n /* Pre-compute quantities that do not depend on lambda. When lambda\n * changes, B and alpha change. Consequently Omega_e changes too. In our\n * model the other parameters stay fixed.\n */\n\n state.gamma = state.p.E + 1;\n state.a = ((int) state.p.handedness) * lambda / state.gamma;\n state.b = (1 + epsilon) / state.p.alpha_star;\n state.beta = sqrt(state.p.E * (state.p.E + 2)) / (state.p.E + 1);\n coeffs->dimensionless_p = state.gamma * state.beta;\n\n /* Shprits 2006 eqn 9, credited to Lencheck+ 1971 and Shultz & Lanzerotti 1974: */\n\n double s0 = 1.38 - 0.32 * (params->sin_alpha + sqrt(params->sin_alpha));\n double f1 = pi_on_2nu / (pow(state.p.E + 1, 2) * s0);\n\n /* Let's integrate! First, D_aa. */\n\n integrand.function = (gsl_signature) daa_integrand;\n integrand.params = &state;\n\n gsl_integration_qag(\n &integrand,\n 0., /* lower limit */\n lambda_m, /* upper limit */\n integ_abs_tol,\n integ_rel_tol,\n INTEG_WS_SIZE, /* allocated workspace size */\n GSL_INTEG_GAUSS51, /* integration rule */\n integ_workspace, /* workspace */\n &result, /* output: value of the integral */\n &abserr /* estimated absolute error */\n );\n\n if (state.last_error != RESULT_OK) {\n strncat(global_err_msg, \" (while computing Daa)\", COUNT(global_err_msg) - 1);\n gsl_set_error_handler(prev_handler);\n global_context = NULL;\n return state.last_error;\n }\n\n k = f1 / (1 - state.p.sin_alpha * state.p.sin_alpha);\n coeffs->Daa = result * k;\n coeffs->err_Daa = abserr * k;\n\n /* D_ap/p. */\n\n integrand.function = (gsl_signature) dap_on_p_integrand;\n\n gsl_integration_qag(\n &integrand,\n 0., /* lower limit */\n lambda_m, /* upper limit */\n integ_abs_tol,\n integ_rel_tol,\n INTEG_WS_SIZE, /* allocated workspace size */\n GSL_INTEG_GAUSS51, /* integration rule */\n integ_workspace, /* workspace */\n &result, /* output: value of the integral */\n &abserr /* estimated absolute error */\n );\n\n if (state.last_error != RESULT_OK) {\n strncat(global_err_msg, \" (while computing Dap)\", COUNT(global_err_msg) - 1);\n gsl_set_error_handler(prev_handler);\n global_context = NULL;\n return state.last_error;\n }\n\n k = -f1 * state.p.sin_alpha / (state.beta * sqrt(1 - state.p.sin_alpha * state.p.sin_alpha));\n coeffs->Dap_on_p = result * k;\n coeffs->err_Dap_on_p = abserr * fabs(k);\n\n /* D_pp/p^2. */\n\n integrand.function = (gsl_signature) dpp_on_p2_integrand;\n\n gsl_integration_qag(\n &integrand,\n 0., /* lower limit */\n lambda_m, /* upper limit */\n integ_abs_tol,\n integ_rel_tol,\n INTEG_WS_SIZE, /* allocated workspace size */\n GSL_INTEG_GAUSS51, /* integration rule */\n integ_workspace, /* workspace */\n &result, /* output: value of the integral */\n &abserr /* estimated absolute error */\n );\n\n if (state.last_error != RESULT_OK) {\n strncat(global_err_msg, \" (while computing Dpp)\", COUNT(global_err_msg) - 1);\n gsl_set_error_handler(prev_handler);\n global_context = NULL;\n return state.last_error;\n }\n\n k = f1 * pow(state.beta, -2);\n coeffs->Dpp_on_p2 = result * k;\n coeffs->err_Dpp_on_p2 = abserr * k;\n\n /* Huzzah, all done. */\n\n gsl_set_error_handler(prev_handler);\n global_context = NULL;\n return RESULT_OK;\n}\n\n\nstatic result_t\ncalc_unaveraged_coefficients(parameters_t *params, coefficients_t *coeffs)\n{\n gsl_error_handler_t *prev_handler;\n state_t state;\n\n global_context = &state;\n prev_handler = gsl_set_error_handler(s05_error_handler);\n\n if (integ_workspace == NULL) {\n integ_workspace = gsl_integration_workspace_alloc(INTEG_WS_SIZE);\n poly5_workspace = gsl_poly_complex_workspace_alloc(5);\n poly7_workspace = gsl_poly_complex_workspace_alloc(7);\n }\n\n state.p = *params;\n state.itype = ITYPE_LOCAL;\n state.last_error = RESULT_OK;\n\n /* The structure here is paralleling calc_coefficients for maintainability. */\n\n state.gamma = state.p.E + 1;\n state.a = ((int) state.p.handedness) * lambda / state.gamma;\n state.b = (1 + epsilon) / state.p.alpha_star;\n state.beta = sqrt(state.p.E * (state.p.E + 2)) / (state.p.E + 1);\n coeffs->dimensionless_p = state.gamma * state.beta;\n\n double f1 = pi_on_2nu / pow(state.p.E + 1, 2);\n\n /* Compute! It all works if we pretend latitude = 0 and set `itype` to LOCAL. */\n\n coeffs->Daa = daa_integrand(0., &state);\n\n if (state.last_error != RESULT_OK) {\n strncat(global_err_msg, \" (while computing Daa)\", COUNT(global_err_msg) - 1);\n gsl_set_error_handler(prev_handler);\n global_context = NULL;\n return state.last_error;\n }\n\n coeffs->Daa *= f1;\n coeffs->err_Daa = 0;\n\n /* D_ap/p. */\n\n coeffs->Dap_on_p = dap_on_p_integrand(0., &state);\n\n if (state.last_error != RESULT_OK) {\n strncat(global_err_msg, \" (while computing Dap)\", COUNT(global_err_msg) - 1);\n gsl_set_error_handler(prev_handler);\n global_context = NULL;\n return state.last_error;\n }\n\n coeffs->Dap_on_p *= f1 / state.beta;\n coeffs->err_Dap_on_p = 0;\n\n /* D_pp/p^2. */\n\n coeffs->Dpp_on_p2 = dpp_on_p2_integrand(0., &state);\n\n if (state.last_error != RESULT_OK) {\n strncat(global_err_msg, \" (while computing Dpp)\", COUNT(global_err_msg) - 1);\n gsl_set_error_handler(prev_handler);\n global_context = NULL;\n return state.last_error;\n }\n\n coeffs->Dpp_on_p2 *= f1 * pow(state.beta, -2);\n coeffs->err_Dpp_on_p2 = 0.;\n\n /* Huzzah, all done. */\n\n gsl_set_error_handler(prev_handler);\n global_context = NULL;\n return RESULT_OK;\n}\n\n\nstatic PyObject*\nget_coeffs(PyObject *self, PyObject* args)\n{\n int modespec, handspec, wave_filtering;\n parameters_t params;\n coefficients_t coeffs = { 0 };\n result_t r;\n\n if (!PyArg_ParseTuple(args, \"iiidddddddd\", &modespec, &handspec, &wave_filtering,\n ¶ms.E,\n ¶ms.sin_alpha,\n ¶ms.Omega_e,\n ¶ms.alpha_star,\n ¶ms.R,\n ¶ms.x_m,\n ¶ms.delta_x,\n ¶ms.max_wave_latitude))\n return NULL;\n\n if (handspec == 0)\n params.handedness = R_MODE;\n else if (handspec == 1)\n params.handedness = L_MODE;\n else {\n PyErr_SetString(PyExc_RuntimeError, \"unexpected handedness magic constant\");\n return NULL;\n }\n\n params.wave_filtering = (wave_filtering_t) wave_filtering;\n\n if (modespec == 0)\n r = calc_coefficients(¶ms, &coeffs);\n else if (modespec == 1)\n r = calc_unaveraged_coefficients(¶ms, &coeffs);\n else {\n PyErr_SetString(PyExc_RuntimeError, \"unexpected mode magic constant\");\n return NULL;\n }\n\n if (r != RESULT_OK) {\n PyErr_SetString(PyExc_RuntimeError, global_err_msg);\n return NULL;\n }\n\n return Py_BuildValue(\"ddddddd\", coeffs.dimensionless_p,\n coeffs.Daa, coeffs.err_Daa,\n coeffs.Dap_on_p, coeffs.err_Dap_on_p,\n coeffs.Dpp_on_p2, coeffs.err_Dpp_on_p2);\n}\n\n\nstatic PyMethodDef methods[] = {\n { \"get_coeffs\", get_coeffs, METH_VARARGS|METH_KEYWORDS,\n \"(mode, handedness, wfilt, E, sa, Oe, a*, R, xm, dx, mwl) -> \"\n \"(dp, daa, udaa, dap/p, udap/p, dpp/p2, udpp/p2)\" },\n { NULL, NULL, METH_NOARGS, NULL },\n};\n\n\n#if PY_MAJOR_VERSION >= 3\nstatic struct PyModuleDef module_def = {\n PyModuleDef_HEAD_INIT,\n \"_summers2005\",\n NULL,\n 0,\n methods,\n NULL,\n NULL,\n NULL,\n NULL\n};\n\n# define INIT_RET_TYPE PyObject *\n#else\n# define INIT_RET_TYPE void\n#endif\n\nINIT_RET_TYPE\nPyInit__summers2005(void)\n{\n#if PY_MAJOR_VERSION >= 3\n return PyModule_Create(&module_def);\n#else\n PyImport_AddModule(\"_summers2005\");\n Py_InitModule(\"_summers2005\", methods);\n#endif\n}\n", "meta": {"hexsha": "33a149683ae98ed9c65c3181c891a085ef15d340", "size": 19825, "ext": "c", "lang": "C", "max_stars_repo_path": "vernon/summers2005/impl.c", "max_stars_repo_name": "pkgw/vernon", "max_stars_repo_head_hexsha": "9dd52d813722d0932195723cf8c37a5dd2fd0d25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vernon/summers2005/impl.c", "max_issues_repo_name": "pkgw/vernon", "max_issues_repo_head_hexsha": "9dd52d813722d0932195723cf8c37a5dd2fd0d25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vernon/summers2005/impl.c", "max_forks_repo_name": "pkgw/vernon", "max_forks_repo_head_hexsha": "9dd52d813722d0932195723cf8c37a5dd2fd0d25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-05T06:05:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T06:05:40.000Z", "avg_line_length": 29.0263543192, "max_line_length": 108, "alphanum_fraction": 0.6116519546, "num_tokens": 5561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629214, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.43305913743796265}} {"text": "/* ============================================================ *\n * decomp_eb.c\t\t\t\t\t\t\t*\n * Martin Kilbinger, Liping Fu 2008, 2009\t\t\t*\n * ============================================================ */\n#include \"decomp_eb.h\"\n#include \n\n/* === CFHTLS Wide 3rd data release, Fu&Kilbinger (2010) === */\n\n/* S/N, Psi=19' eta=1/50 */\nconst double a_FK10_SN[N_FK10] = {0.1197730890, -0.3881211865, 0.5212557875, -0.3440507036, 0.2761305382, -0.07286690971};\n\n/* FoM, Psi=222', eta=1/10 */\nconst double a_FK10_FoM_eta10[N_FK10] = {0.009877788826, 0.1061397843, -0.4300211814, 0.5451016406, -0.3372272549, 0.1716983151};\n\n/* FoM, Psi=222', eta=1/50 */\nconst double a_FK10_FoM_eta50[N_FK10] = {0.1239456383, -0.3881431858, 0.5579593467, -0.3679282338, 0.1540941993, 0.01293361618};\n\n\n/* First-kind Chebyshev polynomial of order n */\n#define EPS 1.0e-10\ndouble Cheby(double x, int n, error **err)\n{\n double Cn;\n\n testErrorRetVA(x<-1-EPS || x>1+EPS, mr_range, \"x = %g out of range\", *err, __LINE__, -1, x);\n\n if (x<-1) x = -1.0;\n if (x>1) x = 1.0;\n\n Cn = cos (n * acos (x));\n return Cn;\n}\n#undef EPS\n\n/* Second-kind Chebyshev polynomial of order n */\n#define EPS 1.0e-10\ndouble Cheby2(double x, int n, error **err)\n{\n double Un;\n\n testErrorRetVA(x<-1-EPS || x>1+EPS, mr_range, \"x = %g out of range\", *err, __LINE__, -1, x);\n\n if (x<-1) x = -1.0;\n if (x>1) x = 1.0;\n\n if (x == 1) {\n Un = n + 1;\n } else if (x == -1) {\n Un = pow(-1.0, n) * (n + 1.0);\n } else {\n Un = sin((n+1.0)*acos(x))/sin(acos (x));\n }\n\n return Un;\n}\n#undef EPS\n\n/* Legendre polynomial of order n */\ndouble Legen(double x, int n)\n{\n\n switch (n) {\n case 0:\n\t return 1.0;\n case 1:\n\t return x;\n default:\n\t return (2.0*n-1.0)/(double)n*x*Legen(x,n-1)-(n-1.0)/(double)n*Legen(x,n-2); \n }\n}\n\n/* General basis function of order n */\n#define EPS 1.0e-10\ndouble C(double x, int n, poly_t poly, error **err)\n{\n double c;\n\n testErrorRetVA(x<-1-EPS || x>1+EPS, mr_range, \"x = %g out of range\", *err, __LINE__, -1, x);\n\n if (x<-1) x = -1.0;\n if (x>1) x = 1.0;\n\n switch (poly) {\n case cheby :\n\t c = Cheby(x, n, err);\n\t forwardError(*err, __LINE__, -1.0);\n\t break;\n case cheby2 :\n\t c = Cheby2(x, n, err);\n\t forwardError(*err, __LINE__, -1.0);\n\t break;\n case legen :\n\t c = Legen(x, n);\n\t break;\n default :\n\t *err = addErrorVA(mr_poly, \"Unknown polynomial type %d\", *err, __LINE__, poly);\n\t return -1.0;\n }\n\n return c;\n}\n#undef EPS\n\n\n/* ============================================================ *\n * The filter function for the generalised ring statistics.\t*\n * FK09 (11).\t\t\t\t\t\t\t*\n * ============================================================ */\n#define\t EPS 1.0e-6\ndouble Tp(double x, const double *a, int N, poly_t poly, error **err)\n{\n int n;\n double res, Cn, Cnm1=0.0, Cnm2; \n\n if (x<-1-EPS || x>+1+EPS) return 0;\n\n /* NEW! */\n //if (x<-1) x = -1;\n //if (x>+1) x = +1;\n\n\n testErrorRetVA(N<=0, mr_range, \"N has to be larger than zero but is %d\", *err, __LINE__, 0.0, N);\n\n testErrorRetVA(x>+1+EPS, mr_range, \"x=%.10f out of range\", *err, __LINE__, 0.0, x);\n testErrorRetVA(x<-1-EPS, mr_range, \"x=%.10f out of range\", *err, __LINE__, 0.0, x);\n\n if (poly==cheby || poly==cheby2) {\n\n Cnm2 = 1.0;\n if (poly==cheby) Cnm1 = x;\n else if (poly==cheby2) Cnm1 = 2.0*x;\n\n res = 0.0;\n res += a[0] * Cnm2;\n if (N==1) return res;\n res += a[1] * Cnm1;\n if (N==2) return res;\n\t\n for (n=2; n-1.0);\n\n r = 3.0/dsqr(x + R);\n Fnnu(x, n, poly, Fn, err);\n forwardError(*err, __LINE__, 0.0);\n\n alpha = R*(1.0-r*R*R)*Fn[0];\n alpha += (1.0 - 3.0*r*R*R)*Fn[1];\n alpha += -3.0*r*R*Fn[2];\n alpha += -r*Fn[3];\n alpha *= 4.0/3.0*r;\n\n return alpha;\n}\n\n/* ============================================================ *\n * The filter function T_- obtained from T_+, FK09 (20).\t*\n * ============================================================ */\n#define EPS 1.0e-10\ndouble Tm(double x, const double *a, int N, poly_t poly, double R, error **err)\n{\n double tm, c, alph;\n int n;\n\n testErrorRetVA(x<-1-EPS, mr_range, \"x=%.20f smaller than -1\", *err, __LINE__, 0.0, x);\n\n for (n=0,tm=0.0; nth[Nxi-1], mr_range,\n\t\t \"THETA_MAX=%g' is larger than maximum angular scale for xi+-, %g'\",\n\t\t *err, __LINE__, 0.0, THETA_MAX/arcmin, th[Nxi-1]/arcmin);\n\n if (a==NULL) {\n *err = addError(mr_null, \"Coefficients a=NULL\", *err, __LINE__);\n return 0.0;\n }\n\n\n /* FK09 (8) */\n A = (THETA_MAX - THETA_MIN)/2.0;\n B = (THETA_MAX + THETA_MIN)/2.0;\n\n for (i=0,res=0.0; i THETA_MAX) break;\n\n /* theta[i] is the bin center */\n\n if (i==0) {\n\t dt1 = (th[i+1] - th[i])/2.;\n\t dtheta = 2*dt1;\n } else if (i==Nxi-1) {\n\t dt2 = (th[i] - th[i-1])/2.;\n\t dtheta = 2*dt2;\n } else { \n\t dt1 = (th[i+1] - th[i])/2.;\n\t dt2 = (th[i] - th[i-1])/2.;\n\t dtheta = dt2 + dt1;\n }\n x = (theta-B)/A;\n \n if (pm==+1) { \n\t summand = xip[i]*theta/dsqr(THETA_MAX);\n\t summand *= Tp(x, a, N, poly, err);\n\t forwardError(*err, __LINE__, -1.0);\n } else if (pm==-1) {\n\t summand = xim[i]*theta/dsqr(THETA_MAX);\n\t summand *= Tm(x, a, N, poly, B/A, err);\n\t forwardError(*err, __LINE__, -1.0);\n } else {\n\t summand = 0.0;\n }\t \n\n res += summand*dtheta;\n }\n\n testErrorRet(!finite(res), math_infnan, \"R is not finite\", *err, __LINE__,\n\t\t 0.0);\n\n return res;\n}\n\n\n/* If cov_mode=outer, n, m are not used. For cov_mode=inner, a, N are not used. *\n * If cov_mode=fromZ, the covariance using Z+ is returned and a, N are not used. */\n#define EPS 1.0e-5\ndouble cov_RR(const double *THETA_MIN, const double *THETA_MAX, const double *a, int N, poly_t poly,\n\t const double *theta, const double *cov_xi, int Ntheta, \n\t cov_mode_t cov_mode, int n, int m, double fac, error **err)\n{\n double sum, dlogtheta, tmp, A[2], B[2], xi, xj, yi, yj, thetai, thetaj;\n int i, j;\n static double **Cov_xi = NULL;\n\n\n /* Testing for a==NULL not possible because cov_RR is also called from get_cov_RR_inner_array */\n if (cov_mode==fromZ) {\n#ifdef __MRING_H\n sum = cov_RR_Z(THETA_MIN, THETA_MAX, theta, cov_xi, Ntheta, err);\n forwardError(*err, __LINE__, 0.0);\n return sum;\n#else\n *err = addError(mr_type, \"cov_mode 'fromZ' not supported here\", *err, __LINE__);\n return 0.0;\n#endif\n }\n\n for (i=0; i<2; i++) {\n A[i] = (THETA_MAX[i] - THETA_MIN[i])/2.0;\n B[i] = (THETA_MAX[i] + THETA_MIN[i])/2.0;\n }\n\n dlogtheta = log(theta[1]) - log(theta[0]);\n\n for (i=0; i<2; i++) {\n testErrorRetVA(theta[0]>THETA_MIN[i], mr_range,\n\t\t \"Minumum of xi-covariance (%g=%g') larger than THETA_MIN (%g=%g')\",\n\t\t *err, __LINE__, -1, theta[0], theta[0]/arcmin, THETA_MIN[i], THETA_MIN[i]/arcmin);\n testErrorRetVA(theta[Ntheta-1]THETA_MAX[0]) continue;\n xi = (thetai-B[0])/A[0];\n yi = thetai/THETA_MAX[0];\n \n //for (j=0; jTHETA_MAX[1]) continue;\n\t xj = (thetaj-B[1])/A[1];\n\t yj = thetaj/THETA_MAX[1];\n\n\t tmp = dsqr(dlogtheta);\n\n\t if (cov_mode==outer) {\n\t tmp *= Tp(xi, a, N, poly, err);\n\t forwardError(*err, __LINE__, -1);\n\t tmp *= Tp(xj, a, N, poly, err);\n\t forwardError(*err, __LINE__, -1);\n\t } else {\n\t tmp *= C(xi, n, poly, err); \t forwardError(*err, __LINE__, -1);\n\t tmp *= C(xj, m, poly, err); \t forwardError(*err, __LINE__, -1);\n\t }\n\n\t tmp *= dsqr(yi*yj);\n\n\t //tmp *= cov_xi[i*Ntheta+j];\n\t tmp *= sm2_interpol2d(Cov_xi, Ntheta, log(theta[0]), log(theta[Ntheta-1]), dlogtheta, log(thetai),\n\t \t\t Ntheta, log(theta[0]), log(theta[Ntheta-1]), dlogtheta, log(thetaj), 0.0, 0.0, err);\n\t forwardError(*err, __LINE__, -1.0);\n\n\t sum += tmp;\n\n }\n \n }\n\n /* Comment the following two lines for faster code, but be aware that no check is done\n * whether the input covariance changes! */\n sm2_free_matrix(Cov_xi, 0, Ntheta-1, 0, Ntheta-1);\n Cov_xi = NULL;\n\n return sum;\n}\n#undef EPS\n\n/* RR-Covariance using a diagonal xi-covariance.\t\t\t\t *\n * If cov_mode=outer, n, m are not used. For cov_mode=inner, a, N are not used. *\n * If cov_mode=fromZ, the covariance using Z+ is returned and a, N are not used. */\n#define EPS 1.0e-5\ndouble cov_RR_diag_xi(const double *THETA_MIN, const double *THETA_MAX, const double *a, int N, poly_t poly,\n\t\t const double *theta, const double *var_xi, int Ntheta, \n\t\t int islog, error **err)\n{\n double sum, dlogtheta, dtheta, tmp, A[2], B[2], xi, xj, yi, yj, thetai, thetaj;\n int i;\n\n for (i=0; i<2; i++) {\n A[i] = (THETA_MAX[i] - THETA_MIN[i])/2.0;\n B[i] = (THETA_MAX[i] + THETA_MIN[i])/2.0;\n }\n\n if (islog==0) {\n dtheta = theta[1] - theta[0];\n dlogtheta = 0.0;\n } else if (islog==1) {\n dlogtheta = log(theta[1]) - log(theta[0]);\n dtheta = 0.0;\n } else {\n *err = addErrorVA(mr_type, \"Invalid flag islog = %d\\n\", *err, __LINE__, islog);\n return 0.0;\n }\n\n for (i=0; i<2; i++) {\n testErrorRetVA(theta[0]>THETA_MIN[i], mr_range,\n\t\t \"Minumum of xi-covariance (%g=%g') larger than THETA_MIN (%g=%g')\",\n\t\t *err, __LINE__, -1, theta[0], theta[0]/arcmin, THETA_MIN[i], THETA_MIN[i]/arcmin);\n testErrorRetVA(theta[Ntheta-1]THETA_MAX[0]) continue;\n xi = (thetai-B[0])/A[0];\n yi = thetai/THETA_MAX[0];\n \n xj = (thetaj-B[1])/A[1];\n yj = thetaj/THETA_MAX[1];\n\n if (islog==0) {\n\t //\t tmp = dsqr(dtheta) /thetai/thetai;\n\t tmp = dsqr(dtheta)*yi*yj/THETA_MAX[0]/THETA_MAX[1];\n\n } else {\n\t\n\t tmp = dsqr(dlogtheta);\n\t tmp *= dsqr(yi*yj);\n }\n\n tmp *= Tp(xi, a, N, poly, err);\n forwardError(*err, __LINE__, -1);\n tmp *= Tp(xj, a, N, poly, err);\n forwardError(*err, __LINE__, -1);\n\n\n tmp *= var_xi[i];\n // tmp *= dsqr(yi*yj);\n\n sum += tmp; \n }\n\n return sum;\n}\n#undef EPS\n\n/* ============================================================ *\n * Returns the chi^2 for a null test (RR=0).\t\t\t*\n * ============================================================ */\ndouble chi2_RB_null(const double *RB, const double *covRB, int NRB)\n{\n int i, j;\n double c2;\n\n for (i=0,c2=0.0; iEPSILON, mr_file,\n\t\t \"Inconsistent file %s, psimin=%g should be %g according to the file name\",\n\t\t *err, __LINE__, NULL, rname, psimin, Psimin/arcmin);\n testErrorRetVA(fabs(psimax-Psimax/arcmin)>EPSILON, mr_file,\n\t\t \"Inconsistent file %s, psimax=%g should be %g according to the file name\",\n\t\t *err, __LINE__, NULL, rname, psimax, Psimax/arcmin);\n\n return c_cosebi;\n}\n\n/* ============================================================ *\n * Reads COSEBIs zeros and normalisation coefficients from file *\n * and sets corresponding min and max scales.\t\t\t*\n * Calculates polynomial coefficients c and returns them. *\n * ============================================================ */\ndouble *read_zeros_norm_cosebi(const char *rname, double *psimin, double *psimax, error **err)\n{\n FILE *F;\n int Nzeros, Ncoeff, k, n, off_c, off_R, nmax;\n ssize_t nread;\n double *Rn, *Norm, *c;\n char *str, *line=NULL;\n\n\n F = fopen_err(rname, \"r\", err); forwardError(*err, __LINE__, NULL);\n\n /* Read two header lines */\n line = malloc_err(1024*sizeof(char), err); forwardError(*err, __LINE__, NULL);\n str = fgets(line, 1024, F);\n str = fgets(line, 1024, F);\n free(line);\n\n nread = fscanf(F, \"%d %lg %lg\\n\", &nmax, psimin, psimax);\n testErrorRet(nread != 3, mr_file, \"File has wrong format.\", *err, __LINE__, NULL);\n\n testErrorRetVA(nmax > NMAX_COSEBI, mr_range,\n\t\t \"COSEBI number of modes n=%d read from file %s cannot be larger than NMAX_COSEBI=%d\",\n\t\t *err, __LINE__, NULL, nmax, rname, NMAX_COSEBI);\n\n\n /* Number of zeros for nmax polynomials, *\n * sum_{i=1}^{nmax+1} (i+1) = sum_{i=0}^{nmax+1} i - 1 */\n Nzeros = (nmax+1) * (nmax+2) / 2 - 1;\n\n //fprintf(stderr, \"nmax = %d , Psi = [%g, %g]\\n\", nmax, *psimin, *psimax);\n //fprintf(stderr, \"Reading %d Rn, %d Norm, from %s\\n\", Nzeros, nmax, rname);\n\n Rn = malloc_err(sizeof(double)*Nzeros, err); forwardError(*err, __LINE__, NULL);\n Norm = malloc_err(sizeof(double)*nmax, err); forwardError(*err, __LINE__, NULL);\n\n /* Read zeros */\n for (k=0; k\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"funcsfa.h\"\n\n#define min(x, y) ((x)>(y)?(y):(x))\n#define max(x, y) ((x)>(y)?(x):(y))\n\n#define DEBUG 0\n#define debug_print(fmt, ...) \\\n do { if (DEBUG) fprintf(stderr, \"%s:%4d:%25s(): \" fmt, __FILE__, \\\n __LINE__, __func__, __VA_ARGS__); } while (0)\n\ndouble eps_ev = 1e-20;\n\n// **************************************\n// Lapack\n// **************************************\n\n// Lapack Fortran DGESV interface\nvoid\ndgesv_(int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb,\n int *info);\n// DGESV wrapper, for solving linear equations.\nstatic int\ndgesv(int n, int nrhs, double *a, int lda, int *ipiv, double *b, int ldb)\n{\n int info = -1;\n dgesv_(&n, &nrhs, a, &lda, ipiv, b, &ldb, &info);\n return info;\n}\n\n// Lapack Fortran DGESVD interface\nvoid\ndgesvd_(char *jobu, char *jobvt, int *m, int *n, double *a, int *lda,\n double *s, double *u, int *ldu, double *vt, int *ldvt, double *work,\n int *lwork, int *info);\n// DGESVD wrapper, for Singular Value Decomposition.\nstatic int\ndgesvd(char jobu, char jobvt, int m, int n, double *a, int lda, double *s,\n double *u, int ldu, double *vt, int ldvt)\n{\n int info = -1;\n int lwork = -1;\n double optimal_lwork;\n double *work;\n // Query optimal work size\n dgesvd_(&jobu, &jobvt, &m, &n, a, &lda,\n s, u, &ldu, vt, &ldvt, &optimal_lwork,\n &lwork, &info);\n if (info != 0) {\n return info;\n }\n lwork = (int) optimal_lwork;\n\n work = malloc(sizeof(double)*lwork);\n\n dgesvd_(&jobu, &jobvt, &m, &n, a, &lda,\n s, u, &ldu, vt, &ldvt, work,\n &lwork, &info);\n\n free(work);\n return info;\n}\n\n// **************************************\n// Objects\n// **************************************\n\nfuncsfa_Factorization*\nfuncsfa_Factorization_alloc(size_t n_features, size_t n_factors,\n size_t n_samples, size_t n_datatypes,\n size_t *n_features_split, double *data)\n{\n size_t i;\n funcsfa_Factorization *m;\n size_t sum_n_features_split = 0;\n\n debug_print(\"%s\\n\", \"Allocating SFA object\");\n\n m = malloc(sizeof(funcsfa_Factorization));\n m->n_features = n_features;\n m->n_factors = n_factors;\n m->n_samples = n_samples;\n m->n_datatypes = n_datatypes;\n m->n_features_split = malloc(sizeof(size_t)*n_datatypes);\n for(i=0; in_features_split[i] = n_features_split[i];\n sum_n_features_split += n_features_split[i];\n }\n if (sum_n_features_split != n_features)\n {\n debug_print(\"Total number of features (%zd) does not match sum (%zd)\\n\",\n n_features, sum_n_features_split);\n free(m->n_features_split);\n free(m);\n return NULL;\n }\n m->data = data;\n m->coefficients = malloc(sizeof(double)*n_features*n_factors);\n m->factors = malloc(sizeof(double)*n_factors*n_samples);\n m->factor_cov = malloc(sizeof(double)*n_factors*n_factors);\n m->residual_var = malloc(sizeof(double)*n_features);\n\n return(m);\n}\n\nvoid\nfuncsfa_Factorization_free(funcsfa_Factorization *m)\n{\n debug_print(\"%s\\n\", \"Freeing SFA object\");\n\n if (m != NULL)\n {\n free(m->n_features_split);\n free(m->coefficients);\n free(m->factors);\n free(m->factor_cov);\n free(m->residual_var);\n }\n free(m);\n}\n\nfuncsfa_Monitor*\nfuncsfa_Monitor_alloc(int max_iter)\n{\n funcsfa_Monitor *mon;\n int i;\n\n debug_print(\"%s\\n\", \"Allocating Monitor object\");\n\n mon = malloc(sizeof(funcsfa_Monitor));\n if (mon == NULL) {\n return NULL;\n }\n mon->n_iter = 0;\n mon->reconstruction_error = malloc(sizeof(double)*(max_iter+1));\n mon->max_diff_factors = malloc(sizeof(double)*(max_iter+1));\n mon->max_diff_coefficients = malloc(sizeof(double)*(max_iter+1));\n if ((mon->reconstruction_error == NULL) ||\n (mon->max_diff_factors == NULL) ||\n (mon->max_diff_coefficients == NULL))\n {\n funcsfa_Monitor_free(mon);\n return NULL;\n }\n for (i = 0; i < max_iter+1; i++)\n {\n mon->reconstruction_error[i] = NAN;\n mon->max_diff_factors[i] = NAN;\n mon->max_diff_coefficients[i] = NAN;\n }\n\n return mon;\n}\n\nvoid\nfuncsfa_Monitor_free(funcsfa_Monitor *mon)\n{\n debug_print(\"%s\\n\", \"Freeing Monitor object\");\n\n if (mon != NULL)\n {\n free(mon->reconstruction_error);\n free(mon->max_diff_factors);\n free(mon->max_diff_coefficients);\n }\n free(mon);\n}\n\n/** Bunch of memory for temporary matrices.\n * @private\n */\ntypedef struct\n{\n /** Integer vector n_factors long */\n int *factors_int;\n /** Double vector n_features long */\n double *features_double;\n /** Double matrix n_features x n_factors 1 */\n double *features_factors_double_a;\n /** Double matrix n_features x n_factors 2 */\n double *features_factors_double_b;\n /** Double matrix n_factors x n_factors 1 */\n double *factors_factors_double_a;\n /** Double matrix n_factors x n_factors 2 */\n double *factors_factors_double_b;\n\n /** Precomputed value of diag(data * t(data)) */\n double *diag_data_square;\n /** Precomputed value of sum(diag(data * t(data))) per data type */\n double *dt_var;\n /** Factors of previous iteration */\n double *prev_factors;\n /** Coefficients of previous iteration */\n double *prev_coefficients;\n} Workspace;\n\nstatic Workspace*\nws_alloc(funcsfa_Factorization *m)\n{\n Workspace *ws;\n\n debug_print(\"%s\\n\", \"Allocating Workspace\");\n\n ws = malloc(sizeof(Workspace));\n ws->factors_int = malloc(sizeof(int)*m->n_factors);\n ws->features_double = malloc(sizeof(double)*m->n_features);\n\n ws->features_factors_double_a = malloc(sizeof(double)*m->n_features*m->n_factors);\n ws->features_factors_double_b = malloc(sizeof(double)*m->n_features*m->n_factors);\n ws->factors_factors_double_a = malloc(sizeof(double)*m->n_factors*m->n_factors);\n ws->factors_factors_double_b = malloc(sizeof(double)*m->n_factors*m->n_factors);\n\n ws->diag_data_square = malloc(sizeof(double)*m->n_features);\n ws->dt_var = malloc(sizeof(double)*m->n_factors);\n ws->prev_factors = malloc(sizeof(double)*m->n_factors*m->n_samples);\n ws->prev_coefficients = malloc(sizeof(double)*m->n_features*m->n_factors);\n\n return ws;\n}\n\nstatic void\nws_init(Workspace *ws, funcsfa_Factorization *m)\n{\n double *d_d;\n size_t dt_i, feature_start, n_features, i;\n\n debug_print(\"%s\\n\", \"Initializing Workspace\");\n\n d_d = malloc(sizeof(double)*m->n_features*m->n_features);\n\n cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans,\n m->n_features, m->n_features, m->n_samples, 1,\n m->data, m->n_samples,\n m->data, m->n_samples,\n 0, d_d, m->n_features);\n\n for (i = 0; i < m->n_features; i++)\n {\n ws->diag_data_square[i] = d_d[i*m->n_features + i];\n }\n feature_start = 0;\n for(dt_i = 0; dt_i < m->n_datatypes; dt_i++)\n {\n ws->dt_var[dt_i] = 0;\n n_features = m->n_features_split[dt_i];\n for(i = feature_start; i < (feature_start + n_features); i++)\n {\n ws->dt_var[dt_i] += ws->diag_data_square[i];\n }\n ws->dt_var[dt_i] /= n_features;\n feature_start = feature_start + n_features;\n }\n\n free(d_d);\n}\n\nstatic void\nws_free(Workspace *ws)\n{\n debug_print(\"%s\\n\", \"Freeing Workspace\");\n\n free(ws->factors_int);\n free(ws->features_double);\n free(ws->features_factors_double_a);\n free(ws->features_factors_double_b);\n free(ws->factors_factors_double_a);\n free(ws->factors_factors_double_b);\n\n free(ws->diag_data_square);\n free(ws->dt_var);\n free(ws->prev_factors);\n free(ws->prev_coefficients);\n\n free(ws);\n}\n\n// **************************************\n// Utility Functions\n// **************************************\n\nstatic double\nmax_diff(double *a, double *b, size_t length)\n{\n size_t i;\n double md, d;\n\n md = 0;\n for (i = 0; i < length; i++)\n {\n d = fabs(a[i] - b[i]);\n if (d > md)\n {\n md = d;\n }\n }\n return md;\n}\n\nstatic bool\nfinite_array(double *a, size_t length)\n{\n for (size_t i=0; i 0.0))\n {\n return false;\n }\n }\n return true;\n}\n\n#define check_finite(a, length) \\\n if (DEBUG && !finite_array(a, length)) {\\\n debug_print(\"%s\\n\", \"Error, non-finite values in matrix\");}\n\n#define check_positive(a, length) \\\n if (DEBUG && !positive_array(a, length)) {\\\n debug_print(\"%s\\n\", \"Error, non-positive values in matrix\");}\n\n// **************************************\n// Algorithm\n// **************************************\n\nstatic int\nexpectation_factors(funcsfa_Factorization *m, Workspace *ws)\n{\n size_t i, j;\n double *r_c, *c_r_c, *c_r_c_i, *o, *c_o;\n double factor_mean, factor_var, factor_sd, deviance;\n int *ipiv;\n int info;\n\n debug_print(\"%s\\n\", \"Computing Expectation and Covariance of Factors\");\n check_finite(m->coefficients, m->n_features*m->n_factors);\n check_finite(m->residual_var, m->n_features);\n check_positive(m->residual_var, m->n_features);\n\n /* Compute $\\Psi^{-1} B$\n * r_c = diag(1/residual_var) * coefficients */\n r_c = ws->features_factors_double_a;\n for (i=0; i < m->n_features; i++)\n {\n for (j=0; j < m->n_factors; j++)\n {\n r_c[j * m->n_features + i] =\n m->coefficients[j * m->n_features + i] / m->residual_var[i];\n }\n }\n\n /* Compute $B^T \\Psi^{-1} B + I$\n * c_r_c = t(coefficients) * r_c + I */\n c_r_c = ws->factors_factors_double_a;\n cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans,\n m->n_factors, m->n_factors, m->n_features, 1,\n m->coefficients, m->n_features,\n r_c, m->n_features,\n 0, c_r_c, m->n_factors);\n for (i = 0; i < m->n_factors; i++)\n {\n c_r_c[i*m->n_factors + i] += 1;\n }\n\n /* Compute $O = \\Psi^{-1}B(B^T \\Psi^{-1} B + I)^{-1}$\n * o = r_c*solve(c_r_c) */\n c_r_c_i = ws->factors_factors_double_b;\n ipiv = ws->factors_int;\n for (i = 0; i < m->n_factors; i++)\n {\n for (j = 0; j < m->n_factors; j++)\n {\n c_r_c_i[j * m->n_factors + i] = (i == j);\n }\n }\n\n info = dgesv(m->n_factors, m->n_factors,\n c_r_c, m->n_factors, ipiv,\n c_r_c_i, m->n_factors);\n if (info != 0) {\n debug_print(\"Lapack error: %d\\n\", info);\n return -1;\n }\n c_r_c = NULL;\n o = ws->features_factors_double_b;\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n m->n_features, m->n_factors, m->n_factors, 1,\n r_c, m->n_features,\n c_r_c_i, m->n_factors,\n 0, o, m->n_features);\n\n /* Compute $E[Z|X] = (\\Psi^{-1}B(B^T\\Psi^{-1}B+I)^{-1})^TX$\n * factors = t(o) * t(X)\n */\n cblas_dgemm(CblasColMajor, CblasTrans, CblasTrans,\n m->n_factors, m->n_samples, m->n_features, 1,\n o, m->n_features,\n m->data, m->n_samples,\n 0, m->factors, m->n_factors);\n\n /* Compute $B^T\\Psi^{-1}B(B^T\\Psi^{-1}B+I)^{-1}$\n * c_o = t(coefficients) * o\n */\n c_o = ws->factors_factors_double_a;\n cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans,\n m->n_factors, m->n_factors, m->n_features, 1,\n m->coefficients, m->n_features,\n o, m->n_features,\n 0, c_o, m->n_factors);\n\n /*\n * Compute $E[ZZ^T|X] = I - (B^T\\Psi^{-1}B(B^T\\Psi^{-1}B+I)^{-1})^T + E[Z|X]E[Z|X]^T$\n * factor_cov = factors * t(factors) + I - c_o\n */\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,\n m->n_factors, m->n_factors, m->n_samples, 1,\n m->factors, m->n_factors,\n m->factors, m->n_factors,\n 0, m->factor_cov, m->n_factors);\n\n for (i = 0; i < m->n_factors; i++)\n {\n for (j = 0; j < m->n_factors; j++)\n {\n m->factor_cov[j * m->n_factors + i] += (i==j) - c_o[j * m->n_factors + i];\n }\n }\n\n debug_print(\"Factor value: %g\\n\", m->factors[0]);\n\n // Rescale factors\n for (i = 0; i < m->n_factors; i++)\n {\n factor_mean = 0;\n for (j = 0; j < m->n_samples; j++)\n {\n factor_mean += m->factors[i + j*m->n_factors];\n }\n factor_mean /= m->n_samples;\n debug_print(\" Factor mean %zd: %g\\n\", i, factor_mean);\n factor_var = 0;\n for (j = 0; j < m->n_samples; j++)\n {\n deviance = m->factors[i + j*m->n_factors] - factor_mean;\n factor_var += deviance*deviance;\n }\n factor_var /= m->n_samples;\n debug_print(\" Factor variation %zd: %g\\n\", i, factor_var);\n for (j = 0; j < m->n_factors; j++)\n {\n m->factor_cov[i + j*m->n_factors] /= factor_var;\n }\n factor_sd = sqrt(factor_var);\n for (j = 0; j < m->n_samples; j++)\n {\n m->factors[i + j * m->n_factors] /= factor_sd;\n }\n }\n\n return 0;\n}\n\nstatic int\nmaximize(funcsfa_Factorization *m, double *lambdas, Workspace *ws)\n{\n const size_t n_lambda = 2;\n size_t dt_i, f_i, lambda_i, k;\n double *ZXt, *BZZt;\n double unpenalized_coeff, l1, l2, dt_var;\n size_t n_features, feature_start;\n\n debug_print(\"%s\\n\", \"Estimating Coefficients\");\n\n check_finite(m->factor_cov, m->n_factors*m->n_factors);\n check_finite(m->factors, m->n_factors*m->n_samples);\n\n ZXt = ws->features_factors_double_a;\n BZZt = ws->features_double;\n // Compute E[Z|X]X^T\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n m->n_factors, m->n_features, m->n_samples, 1,\n m->factors, m->n_factors,\n m->data, m->n_samples,\n 0, ZXt, m->n_factors);\n\n // Coordinate Descent over factors\n for(k = 0; k < m->n_factors; k++)\n {\n debug_print(\"\\tCoordinate descent for factor: %zd\\n\", k);\n // Compute $BE[ZZ^T|X]_(\\cdot k)$\n cblas_dgemv(CblasColMajor, CblasNoTrans,\n m->n_features, m->n_factors, 1.0,\n m->coefficients, m->n_features,\n m->factor_cov+(k*m->n_factors), 1,\n 0.0, BZZt, 1);\n\n lambda_i = 0;\n feature_start = 0;\n for(dt_i = 0; dt_i < m->n_datatypes; dt_i++)\n {\n n_features = m->n_features_split[dt_i];\n l1 = lambdas[lambda_i];\n l2 = lambdas[lambda_i+1];\n for(f_i = feature_start; f_i < (feature_start + n_features); f_i++)\n {\n // Compute: $$\n // \\hat B_{(ij)} \\leftarrow \\frac\n // {\\operatorname{S}(\n // \\hat B_{(ij)} + E[Z|X]_{(j \\cdot)} X_{(i \\cdot)}^T -\n // \\hat B_{(i\\cdot)} \\operatorname{E}[ZZ^T|X]_{(\\cdot j)},\n // l_1)}\n // {1+l_2}\n // $$\n unpenalized_coeff = m->coefficients[f_i + (k * m->n_features)] +\n ((ZXt[k + (f_i * m->n_factors)] - BZZt[f_i])\n / m->n_samples);\n m->coefficients[f_i + (k * m->n_features)] =\n copysign(fmax(0.0, fabs(unpenalized_coeff) - l1),\n unpenalized_coeff) /\n (1 + l2);\n }\n feature_start = feature_start + n_features;\n lambda_i = lambda_i + n_lambda;\n }\n }\n\n debug_print(\"%s\\n\", \"Estimating Residual Variance\");\n \n // Residual variance per data type\n feature_start = 0;\n for(dt_i = 0; dt_i < m->n_datatypes; dt_i++)\n {\n dt_var = 0;\n n_features = m->n_features_split[dt_i];\n for(f_i = feature_start; f_i < (feature_start + n_features); f_i++)\n {\n for(k = 0; k < m->n_factors; k++)\n {\n dt_var += (ZXt[k + (f_i * m->n_factors)] *\n m->coefficients[f_i + (k * m->n_features)]);\n }\n }\n dt_var = (ws->dt_var[dt_i] - (dt_var / n_features)) / m->n_samples;\n for(f_i = feature_start; f_i < (feature_start + n_features); f_i++)\n {\n if (dt_var > eps_ev) {\n m->residual_var[f_i] = dt_var;\n } else {\n m->residual_var[f_i] = eps_ev;\n }\n }\n debug_print(\"\\tResidual Variance %zd: %g\\n\", dt_i, dt_var);\n feature_start = feature_start + n_features;\n }\n return 0;\n}\n\nstatic int\ninit_svd(funcsfa_Factorization *m, Workspace *ws)\n{\n int info;\n size_t i, j;\n double *x, *s, *vt, *u;\n double scale, f, explained_var, data_var;\n size_t total_n_factors;\n\n debug_print(\"%s\\n\", \"Initializing with SVD\");\n\n total_n_factors = min(m->n_features, m->n_samples);\n\n x = malloc(sizeof(double) * m->n_features * m->n_samples);\n s = malloc(sizeof(double) * total_n_factors);\n vt = malloc(sizeof(double) * total_n_factors * m->n_features);\n u = malloc(sizeof(double) * total_n_factors * m->n_samples);\n if (x == NULL || s == NULL || vt == NULL)\n {\n free(x);\n free(vt);\n free(s);\n free(u);\n return -1;\n }\n\n for (i=0; i < m->n_features * m->n_samples; i++)\n {\n x[i] = m->data[i];\n }\n\n /* vt = svd(X).V.t */\n debug_print(\"%s\\n\", \"\\tStarting Lapack SVD\");\n info = dgesvd('S', 'S',\n m->n_samples, m->n_features,\n x, m->n_samples,\n s, u, m->n_samples,\n vt, total_n_factors);\n if (info != 0) {\n debug_print(\"Lapack error: %d\\n\", info);\n free(x);\n free(vt);\n free(u);\n free(s);\n return -1;\n }\n debug_print(\"%s\\n\", \"\\tDone Lapack SVD\");\n\n scale = 0;\n for (i=0; i < m->n_factors; i++)\n {\n for (j=0; j < m->n_samples; j++)\n {\n f = u[j + i*m->n_samples] * s[i];\n m->factors[i + j*m->n_factors] = f;\n scale += f*f;\n }\n }\n scale /= m->n_factors * m->n_samples;\n scale = sqrt(scale);\n for (i=0; i < m->n_factors; i++)\n {\n for (j=0; j < m->n_features; j++)\n {\n m->coefficients[j + i*m->n_features] = vt[i + j*total_n_factors] * scale;\n }\n }\n for (i=0; i < m->n_factors; i++)\n {\n for (j=0; j < m->n_samples; j++)\n {\n m->factors[i + j*m->n_factors] /= scale;\n }\n }\n\n explained_var = 0;\n for (i=0; i < m->n_factors; i++)\n {\n explained_var += s[i]*s[i];\n }\n explained_var /= m->n_samples * m->n_features;\n data_var = 0;\n for (i=0; i < m->n_features; i++)\n {\n data_var += ws->diag_data_square[i];\n }\n data_var /= m->n_samples * m->n_features;\n debug_print(\"\\tData Var: %g\\n\", data_var);\n explained_var = data_var - explained_var;\n explained_var = fmax(0, explained_var) + eps_ev;\n for (i = 0; i < m->n_features; i++) {\n m->residual_var[i] = explained_var;\n }\n debug_print(\"\\tResidual Variance: %g\\n\", explained_var);\n\n free(x);\n free(vt);\n free(u);\n free(s);\n return 0;\n}\n\ndouble\ncalc_reconstruction_error(funcsfa_Factorization *m, Workspace *ws)\n{\n int i, j;\n double error, e;\n double *prediction;\n\n error = 0.0;\n for (i = 0; i < m->n_samples; i++)\n {\n prediction = ws->features_double;\n cblas_dgemv(CblasColMajor, CblasNoTrans,\n m->n_features, m->n_factors,\n 1.0, m->coefficients, m->n_features,\n m->factors + (i*m->n_factors), 1,\n 0.0, prediction, 1);\n for (j = 0; j < m->n_features; j++)\n {\n e = m->data[i + (j * m->n_samples)] - prediction[j];\n error += e*e;\n }\n }\n return error;\n}\n\nint\nfuncsfa(funcsfa_Factorization *m, double eps, int max_iter,\n char regularizations[], double *lambdas, funcsfa_Monitor *mon)\n{\n int iter = 0;\n int err = 0;\n size_t i;\n double diff = DBL_MAX;\n double diff_f, diff_c;\n double rec_error;\n int const LEN_PREV_REC_ERROR = 10;\n double prev_rec_error[LEN_PREV_REC_ERROR];\n int prev_rec_error_i=0;\n\n Workspace *ws;\n\n for (i=0; in_datatypes; i++)\n {\n if (regularizations[i] != 'e')\n {\n debug_print(\"%s\\n\", \"Only elastic net regularization is supported\");\n return -4;\n }\n }\n\n ws = ws_alloc(m);\n ws_init(ws, m);\n\n debug_print(\"%s\\n\", \"Starting Factorization\");\n\n err = init_svd(m, ws);\n if (err != 0)\n {\n return(1);\n }\n\n rec_error = calc_reconstruction_error(m, ws);\n if (mon != NULL)\n {\n mon->reconstruction_error[0] = rec_error;\n mon->max_diff_factors[0] = 0;\n mon->max_diff_coefficients[0] = 0;\n }\n for (i=0; i eps) {\n debug_print(\"Iteration %d\\n\", iter);\n memcpy(ws->prev_factors, m->factors,\n sizeof(double)*m->n_factors*m->n_samples);\n memcpy(ws->prev_coefficients, m->coefficients,\n sizeof(double)*m->n_features*m->n_factors);\n err = expectation_factors(m, ws);\n if (err != 0)\n {\n debug_print(\"Error in computing expectation of factors: %d\\n\", err);\n ws_free(ws);\n return(2);\n }\n err = maximize(m, lambdas, ws);\n if (err != 0)\n {\n debug_print(\"Error in maximization: %d\\n\", err);\n ws_free(ws);\n return(3);\n }\n\n diff_f = max_diff(m->factors,\n ws->prev_factors, m->n_factors*m->n_samples);\n diff_c = max_diff(m->coefficients, ws->prev_coefficients,\n m->n_features*m->n_factors);\n debug_print(\"Diff (factor/coefficients): %g; %g\\n\", diff_f, diff_c);\n prev_rec_error[prev_rec_error_i] = rec_error;\n prev_rec_error_i += 1;\n if (prev_rec_error_i > LEN_PREV_REC_ERROR) {\n prev_rec_error_i = 0;\n }\n rec_error = calc_reconstruction_error(m, ws);\n debug_print(\"Reconstruction Error: %g\\n\", rec_error);\n diff = 0.0;\n for (i=0; ireconstruction_error[iter+1] = rec_error;\n mon->max_diff_factors[iter+1] = diff_f;\n mon->max_diff_coefficients[iter+1] = diff_c;\n mon->n_iter = iter;\n }\n iter = iter + 1;\n }\n ws_free(ws);\n\n return 0;\n}\n", "meta": {"hexsha": "b71e9da8c2d226c9e7f0e9fe1afc3c9fab547a4a", "size": 21024, "ext": "c", "lang": "C", "max_stars_repo_path": "funcsfa-c/src/funcsfa.c", "max_stars_repo_name": "NKI-CCB/funcsfa", "max_stars_repo_head_hexsha": "336655531f08aeec0077a443eeb76b92d6677b3a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-28T11:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-28T11:47:21.000Z", "max_issues_repo_path": "funcsfa-c/src/funcsfa.c", "max_issues_repo_name": "NKI-CCB/funcsfa", "max_issues_repo_head_hexsha": "336655531f08aeec0077a443eeb76b92d6677b3a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-21T09:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-21T15:39:27.000Z", "max_forks_repo_path": "funcsfa-c/src/funcsfa.c", "max_forks_repo_name": "NKI-CCB/funcsfa", "max_forks_repo_head_hexsha": "336655531f08aeec0077a443eeb76b92d6677b3a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0843672457, "max_line_length": 87, "alphanum_fraction": 0.5956525875, "num_tokens": 6732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.43259439369371155}} {"text": "/*\n** Implementation of LISA algorithm\n** for statistical inference of fMRI images\n**\n** 2nd level inference (one-sample test)\n**\n** G.Lohmann, 2017\n*/\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _OPENMP\n#include \n#endif /*_OPENMP*/\n\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\nextern void VIsolatedVoxels(VImage src,float threshold);\nextern void VHistogram(gsl_histogram *histogram,VString filename);\nextern void VCheckImage(VImage src);\nextern void FDR(VImage src,VImage dest,gsl_histogram *nullhist,gsl_histogram *realhist,double);\nextern double ttest1(double *data1,int n);\nextern void ImageStats(VImage src,double *,double *,double *hmin,double *hmax);\nextern void VBilateralFilter(VImage src,VImage dest,int radius,double var1,double var2,int);\nextern double VImageVar(VImage src);\nextern void VImageCount(VImage src);\nextern void VGetHistRange(VImage src,double *hmin,double *hmax);\nextern void VZScale(VImage src,float mode,float stddev);\nextern float VGetMode(VImage src);\nextern double t2z(double,double);\nextern void HistoUpdate(VImage,gsl_histogram *);\n\n/* generate permutation table */\nint **genperm(gsl_rng *rx,int n,int numperm)\n{\n int i,j;\n int **table = (int **) VCalloc(numperm,sizeof(int *));\n for (i = 0; i < numperm; i++) {\n table[i] = (int *) VCalloc(n,sizeof(int));\n for (j=0; j tiny) {\n\t if (permtable[i] > 0) u = -u;\n\t data[k] = u;\n\t k++;\n\t }\n\t}\n\tif (k < n-2) continue;\n\tavevar(data,k,&ave,&var);\n\tif (var < tiny) continue;\n\tnx = (double)k;\n\tt = sqrt(nx) * ave/sqrt(var);\n\tdf = nx - 1.0;\n\tz = t2z(t,df);\n\tif (t < 0) z = -z;\n\tVPixel(dest,b,r,c,VFloat) = z;\n }\n }\n }\n VFree(data);\n}\n\n\n\nint main (int argc, char *argv[])\n{\n static VArgVector in_files1;\n static VString out_filename=\"\";\n static VString mask_filename=\"\";\n static VFloat alpha = 0.05;\n static VShort radius = 2;\n static VFloat rvar = 2.0;\n static VFloat svar = 2.0;\n static VShort numiter = 2;\n static VShort numperm = 5000;\n static VLong seed = 99402622;\n static VBoolean centering = FALSE;\n static VBoolean cleanup = TRUE;\n static VShort nproc = 0;\n static VOptionDescRec options[] = {\n {\"in\", VStringRepn, 0, & in_files1, VRequiredOpt, NULL,\"Input files\" },\n {\"out\", VStringRepn, 1, & out_filename, VRequiredOpt, NULL,\"Output file\" },\n {\"alpha\",VFloatRepn,1,(VPointer) &alpha,VOptionalOpt,NULL,\"FDR significance level\"},\n {\"perm\",VShortRepn,1,(VPointer) &numperm,VOptionalOpt,NULL,\"Number of permutations\"},\n {\"mask\", VStringRepn, 1, (VPointer) &mask_filename, VRequiredOpt, NULL, \"Mask\"},\n {\"seed\",VLongRepn,1,(VPointer) &seed,VOptionalOpt,NULL,\"Seed for random number generation\"},\n {\"radius\",VShortRepn,1,(VPointer) &radius,VOptionalOpt,NULL,\"Bilateral parameter (radius in voxels)\"},\n {\"rvar\",VFloatRepn,1,(VPointer) &rvar,VOptionalOpt,NULL,\"Bilateral parameter (radiometric)\"},\n {\"svar\",VFloatRepn,1,(VPointer) &svar,VOptionalOpt,NULL,\"Bilateral parameter (spatial)\"},\n {\"filteriterations\",VShortRepn,1,(VPointer) &numiter,VOptionalOpt,NULL,\"Bilateral parameter (number of iterations)\"},\n {\"cleanup\",VBooleanRepn,1,(VPointer) &cleanup,VOptionalOpt,NULL,\"Whether to remove isloated voxels\"},\n {\"j\",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,\"Number of processors to use, '0' to use all\"},\n };\n\n FILE *fp=NULL;\n VString in_filename;\n VAttrList list1=NULL,out_list=NULL,geolist=NULL;\n VImage *src1;\n int i,nimages,npix=0;\n char *prg_name=GetLipsiaName(\"vlisa_onesample\");\n fprintf (stderr, \"%s\\n\", prg_name);\n\n\n /* parse command line */\n if (! VParseCommand (VNumber (options), options, & argc, argv)) {\n VReportUsage (argv[0], VNumber (options), options, NULL);\n exit (EXIT_FAILURE);\n }\n if (argc > 1) {\n VReportBadArgs (argc, argv);\n exit (EXIT_FAILURE);\n }\n\n\n /* omp-stuff */\n#ifdef _OPENMP\n int num_procs=omp_get_num_procs();\n if (nproc > 0 && nproc < num_procs) num_procs = nproc;\n fprintf(stderr,\" using %d cores\\n\",(int)num_procs);\n omp_set_num_threads(num_procs);\n#endif /* _OPENMP */\n\n\n /* images */\n VImage mask = VReadImageFile(mask_filename);\n if (mask==NULL) VError(\"Error reading mask file %s\",mask_filename);\n \n nimages = in_files1.number;\n src1 = (VImage *) VCalloc(nimages,sizeof(VImage));\n for (i = 0; i < nimages; i++) {\n in_filename = ((VString *) in_files1.vector)[i];\n list1 = VReadAttrList(in_filename,0L,TRUE,FALSE);\n VMaskMinval(list1,mask,0.0);\n \n src1[i] = VReadImage(list1);\n if (src1[i] == NULL) VError(\" no input image found\");\n if (VPixelRepn(src1[i]) != VFloatRepn) VError(\" input pixel repn must be float\");\n if (i == 0) npix = VImageNPixels(src1[i]);\n else if (npix != VImageNPixels(src1[i])) VError(\" inconsistent image dimensions\");\n\n /* use geometry info from 1st file */\n if (geolist == NULL) {\n geolist = VGetGeoInfo(list1);\n double *D = VGetGeoPixdim(geolist,NULL);\n if (fabs(D[0]-4.0) < TINY) VError(\" The input must be a list of separate 3D images, not one 4D file\");\n }\n }\n\n \n\n\n /* ini random permutations */\n size_t n = nimages;\n gsl_rng_env_setup();\n const gsl_rng_type *T = gsl_rng_default;\n gsl_rng *rx = gsl_rng_alloc(T);\n gsl_rng_set(rx,(unsigned long int)seed);\n int nperm=0;\n int **permtable = genperm(rx,(int)n,(int)numperm);\n\n\n /* estimate null variance based on first 30 permutations */\n double hmin=0,hmax=0;\n float stddev=1.0;\n if (numperm > 0) {\n int tstperm = 30;\n if (tstperm > numperm) tstperm = numperm;\n double varsum=0,nx=0;\n\n#pragma omp parallel for shared(src1,permtable) schedule(dynamic)\n for (nperm = 0; nperm < tstperm; nperm++) {\n VImage zmap = VCreateImageLike(src1[0]);\n OnesampleTest(src1,zmap,permtable[nperm],nimages);\n#pragma omp critical\n {\n\tvarsum += VImageVar(zmap);\n\tnx++;\n }\n VDestroyImage(zmap);\n }\n double meanvar = varsum/nx;\n stddev = sqrt(meanvar);\n }\n\n\n\n /* no permutation */\n int *nopermtable = (int *) VCalloc(n,sizeof(int));\n VImage dst1 = VCreateImageLike (src1[0]);\n VImage zmap1 = VCreateImageLike(src1[0]);\n OnesampleTest(src1,zmap1,nopermtable,nimages);\n\n if (numperm == 0) {\n double z = VImageVar(zmap1);\n stddev = (float)(sqrt(z)); /* update stddev */\n }\n float mode=0;\n if (centering) mode = VGetMode(zmap1);\n if (numperm > 0) VZScale(zmap1,mode,stddev);\n VBilateralFilter(zmap1,dst1,(int)radius,(double)(rvar),(double)svar,(int)numiter);\n\n\n /* ini histograms */\n VGetHistRange(dst1,&hmin,&hmax);\n size_t nbins = 20000;\n gsl_histogram *hist0 = gsl_histogram_alloc (nbins);\n gsl_histogram_set_ranges_uniform (hist0,hmin,hmax);\n gsl_histogram *histz = gsl_histogram_alloc (nbins);\n gsl_histogram_set_ranges_uniform (histz,hmin,hmax);\n HistoUpdate(dst1,histz);\n\n\n\n /* random permutations */\n#pragma omp parallel for shared(src1,permtable) schedule(dynamic)\n for (nperm = 0; nperm < numperm; nperm++) {\n if (nperm%20 == 0) fprintf(stderr,\" perm %4d of %d\\r\",nperm,(int)numperm);\n\n VImage zmap = VCreateImageLike(src1[0]);\n VImage dst = VCreateImageLike (zmap);\n OnesampleTest(src1,zmap,permtable[nperm],nimages);\n float mode=0;\n if (centering) mode = VGetMode(zmap);\n VZScale(zmap,mode,stddev);\n VBilateralFilter(zmap,dst,(int)radius,(double)(rvar),(double)svar,(int)numiter);\n\n#pragma omp critical\n {\n HistoUpdate(dst,hist0);\n }\n VDestroyImage(dst);\n VDestroyImage(zmap);\n }\n\n\n /* apply fdr */\n VImage fdrimage = VCopyImage (dst1,NULL,VAllBands);\n if (numperm > 0) {\n FDR(dst1,fdrimage,hist0,histz,(double)alpha);\n\n if (cleanup && alpha < 1.0) {\n VIsolatedVoxels(fdrimage,(float)(1.0-alpha));\n }\n if (alpha < 1.0) VImageCount(fdrimage);\n }\n\n\n\n /* write output to disk */\n out_list = VCreateAttrList ();\n VHistory(VNumber(options),options,prg_name,&list1,&out_list);\n VSetGeoInfo(geolist,out_list);\n VAppendAttr (out_list,\"image\",NULL,VImageRepn,fdrimage);\n fp = VOpenOutputFile (out_filename, TRUE);\n if (! VWriteFile (fp, out_list)) exit (1);\n fclose(fp);\n fprintf (stderr, \"\\n%s: done.\\n\", argv[0]);\n exit(0);\n}\n", "meta": {"hexsha": "00f5db5e2f8350e4983370ca33aacaab71a29ba3", "size": 9177, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_onesample/vlisa_onesample.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_onesample/vlisa_onesample.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_onesample/vlisa_onesample.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 30.2871287129, "max_line_length": 121, "alphanum_fraction": 0.6632886564, "num_tokens": 2927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.43247080693229945}} {"text": "/*\n * Copyright 2016 Maikel Nadolski\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef HIDDEN_MARKOV_MODEL_H_\n#define HIDDEN_MARKOV_MODEL_H_\n\n#include \n#include \n\n#include \"maikel/hmm/stochastical_conditions.h\"\n\nnamespace maikel { namespace hmm {\n\n struct hmm_errors: public std::runtime_error {\n hmm_errors(std::string s): std::runtime_error(s) {}\n };\n\n struct dimensions_not_consistent: public hmm_errors {\n dimensions_not_consistent(const std::string& a): hmm_errors(a) {}\n };\n\n template \n class hidden_markov_model\n {\n public:\n using matrix = typename Eigen::Matrix;\n using row_vector = typename Eigen::Matrix;\n using size_type = typename matrix::Index;\n\n struct arguments_not_probability_arrays: public hmm_errors {\n matrix A;\n matrix B;\n row_vector pi;\n arguments_not_probability_arrays(\n const matrix& A_,\n const matrix& B_,\n const row_vector& pi_,\n const std::string& a): hmm_errors(a), A{A_}, B{B_}, pi{pi_} {}\n };\n\n hidden_markov_model(\n const matrix& transition_matrix,\n const matrix& symbol_matrix,\n const row_vector& initial_dist )\n : A { transition_matrix },\n B { symbol_matrix },\n pi{ initial_dist },\n num_states { B.rows() },\n num_symbols { B.cols() }\n {\n if (!rows_are_probability_arrays(A) || !rows_are_probability_arrays(B)\n || !is_probability_array(pi.array()))\n throw arguments_not_probability_arrays\n { A, B, pi, \"Some inputs in constructor do not have the stochastical property.\" };\n if (A.rows() != A.cols() || A.rows() != B.rows() || A.rows() != pi.cols())\n throw dimensions_not_consistent\n { \"Dimensions of input matrices are not consistent with each other.\" };\n }\n\n inline size_type states() const noexcept { return num_states; }\n inline size_type symbols() const noexcept { return num_symbols; }\n\n inline const matrix& transition_matrix() const noexcept { return A; }\n inline const matrix& symbol_probabilities() const noexcept { return B; }\n inline const row_vector& initial_distribution() const noexcept { return pi; }\n\n private:\n matrix A;\n matrix B;\n row_vector pi;\n size_type num_states;\n size_type num_symbols;\n };\n\n} // namespace hmm\n} // namespace maikel\n\n#endif /* HIDDEN_MARKOV_MODEL_H_ */\n", "meta": {"hexsha": "5324a9848f106308ab45c80cb687fa40b22a6ffb", "size": 3284, "ext": "h", "lang": "C", "max_stars_repo_path": "include/maikel/hmm/hidden_markov_model.h", "max_stars_repo_name": "maikel/hidden-markov-model", "max_stars_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T07:16:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:16:01.000Z", "max_issues_repo_path": "include/maikel/hmm/hidden_markov_model.h", "max_issues_repo_name": "maikel/Hidden-Markov-Model", "max_issues_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/maikel/hmm/hidden_markov_model.h", "max_forks_repo_name": "maikel/Hidden-Markov-Model", "max_forks_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6956521739, "max_line_length": 98, "alphanum_fraction": 0.6147990256, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.43211769877709383}} {"text": "/* rng/ranmar.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n\n/* This is the RANMAR lagged fibonacci generator of Marsaglia, Zaman\n and Tsang. The sequence is a series of 24-bit integers, x_n,\n\n x_n = (y_n - c_n + 2^24) mod 2^24\n\n where,\n\n y_n = (y_{n-97) - y_{n-33} + 2^24) mod 2^24\n c_n = (c_{n-1} - 7654321 + 2^24 - 3) mod (2^24 - 3)\n\n The period of this generator is 2^144.\n\n The generator provides about 900 million different subsequences\n each of length O(10^30). Thus each seed up to 900,000,000 gives an\n independent sequence.\n\n Although it was good in its day this generator now has known\n statistical defects and has been superseded by RANLUX.\n\n From: F. James, \"A Review of Pseudorandom number generators\",\n Computer Physics Communications 60, 329 (1990).\n\n G. Marsaglia, A. Zaman and W.W. Tsang, Stat. Prob. Lett. 9, 35 (1990) */\n\nstatic inline unsigned long int ranmar_get (void *vstate);\nstatic double ranmar_get_double (void *vstate);\nstatic void ranmar_set (void *state, unsigned long int s);\n\nstatic const unsigned long int two24 = 16777216;\t/* 2^24 */\n\ntypedef struct\n {\n unsigned int i;\n unsigned int j;\n long int carry;\n unsigned long int u[97];\n }\nranmar_state_t;\n\nstatic inline unsigned long int\nranmar_get (void *vstate)\n{\n ranmar_state_t *state = (ranmar_state_t *) vstate;\n\n unsigned int i = state->i;\n unsigned int j = state->j;\n long int carry = state->carry;\n\n long int delta = state->u[i] - state->u[j];\n\n if (delta < 0)\n delta += two24 ;\n \n state->u[i] = delta;\n\n if (i == 0)\n {\n i = 96;\n }\n else\n {\n i--;\n }\n\n state->i = i;\n\n if (j == 0)\n {\n j = 96;\n }\n else\n {\n j--;\n }\n\n state->j = j;\n\n carry += - 7654321 ;\n \n if (carry < 0)\n carry += two24 - 3;\n \n state->carry = carry ;\n\n delta += - carry ;\n \n if (delta < 0)\n delta += two24 ;\n\n return delta;\n}\n\nstatic double\nranmar_get_double (void *vstate)\n{\n return ranmar_get (vstate) / 16777216.0 ;\n}\n\nstatic void\nranmar_set (void *vstate, unsigned long int s)\n{\n ranmar_state_t *state = (ranmar_state_t *) vstate;\n \n unsigned long int ij = s / 30082 ;\n unsigned long int kl = s % 30082 ;\n \n int i = (ij / 177) % 177 + 2 ;\n int j = (ij % 177) + 2 ;\n int k = (kl / 169) % 178 + 1 ;\n int l = (kl % 169) ;\n\n int a, b;\n \n for (a = 0; a < 97; a++)\n {\n unsigned long int sum = 0 ;\n unsigned long int t = two24 ;\n\n for (b = 0; b < 24; b++)\n\t{\n\t unsigned long int m = (((i * j) % 179) * k) % 179 ;\n\t i = j ;\n\t j = k ;\n\t k = m ;\n\t l = (53 * l + 1) % 169 ;\n\t t >>= 1 ;\n\t \n\t if ((l * m) % 64 >= 32)\n\t sum += t ;\n\t}\n\n state->u[a] = sum ;\n }\n\n state->i = 96;\n state->j = 32;\n state->carry = 362436 ;\n\n}\n\nstatic const gsl_rng_type ranmar_type =\n{\"ranmar\",\t\t\t/* name */\n 0x00ffffffUL,\t\t\t/* RAND_MAX */\n 0,\t\t\t\t/* RAND_MIN */\n sizeof (ranmar_state_t),\n &ranmar_set,\n &ranmar_get,\n &ranmar_get_double};\n\nconst gsl_rng_type *gsl_rng_ranmar = &ranmar_type;\n", "meta": {"hexsha": "81c1f1e4e665b30aa055e0cca4dd58c7d4edef00", "size": 3790, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/ranmar.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/rng/ranmar.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/rng/ranmar.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 21.7816091954, "max_line_length": 76, "alphanum_fraction": 0.6166226913, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4320058536611051}} {"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C header for the computation of the Fourier-domain overlaps, likelihoods.\n *\n *\n */\n\n#ifndef _LIKELIHOOD_H\n#define _LIKELIHOOD_H\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n#include \"struct.h\"\n#include \"waveform.h\"\n#include \"wip.h\"\n\n\n#if defined(__cplusplus)\nextern \"C\" {\n#elif 0\n} /* so that editors will match preceding brace */\n#endif\n\n/****** Prototypes: utilities *******/\n\n/* Function to evaluate a Noise function */\nvoid EvaluateNoise(\n gsl_vector* noisevalues, /* Output: vector of the noise values */\n gsl_vector* freq, /* Input: vector of frequencies on which to evaluate */\n ObjectFunction * Snoise, /* Noise function */\n double fLow, /* Lower bound of the frequency window for the detector */\n double fHigh); /* Upper bound of the frequency window for the detector */\n\n/* Function building a frequency vector with logarithmic sampling */\nvoid SetLogFrequencies(\n gsl_vector* freqvector, /* Output pointer to gsl_vector, already allocated */\n const double fmin, /* Lower bound of the frequency interval */\n const double fmax, /* Upper bound of the frequency interval */\n const int nbpts); /* Number of points */\n/* Function building a frequency vector with linear sampling */\nvoid SetLinearFrequencies(\n gsl_vector* freqvector, /* Output pointer to gsl_vector, already allocated */\n const double fmin, /* Lower bound of the frequency interval */\n const double fmax, /* Upper bound of the frequency interval */\n const int nbpts); /* Number of points */\n\n/* Function determining logarithmically spaced frequencies from a waveform given as a list of modes, a minimal frequency and a number of points */\nvoid ListmodesSetFrequencies(\n struct tagListmodesCAmpPhaseFrequencySeries *list, /* Waveform, list of modes in amplitude/phase form */\n double fLow, /* Additional lower frequency limit */\n double fHigh, /* Additional upper frequency limit */\n int nbpts, /* Number of frequency samples */\n int tagsampling, /* Tag for linear (0) or logarithmic (1) sampling */\n gsl_vector* freqvector); /* Output: vector of frequencies, already allocated with nbpts */\n\n/****** Prototypes: overlaps and likelihood computation *******/\n\n/***************************** Functions for overlaps using linear integration ******************************/\n\n/* Function computing the overlap (h1|h2) between two given modes, for a given noise function - uses simple trapeze integration on logarithmically sampled frequencies */\ndouble FDSinglemodeLogLinearOverlap(\n struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */\n struct tagCAmpPhaseFrequencySeries *freqseries2, /* Second mode h2, in amplitude/phase form */\n ObjectFunction * Snoise, /* Noise function */\n double fLow, /* Lower bound of the frequency window for the detector */\n double fHigh); /* Upper bound of the frequency window for the detector */\n\n/* Function computing the overlap (h1|h2) between two waveforms given as lists of mode contributions (factos sYlm already included), for a given noise function - uses simple trapeze integration on logarithmically sampled frequencies - generates the frequency series in Re/Im form by summing the mode contributions first, then computes the overlap */\ndouble FDListmodesLogLinearOverlap(\n struct tagListmodesCAmpPhaseFrequencySeries *list1, /* First waveform, list of modes in amplitude/phase form */\n struct tagListmodesCAmpPhaseFrequencySeries *list2, /* First waveform, list of modes in amplitude/phase form */\n ObjectFunction * Snoise, /* Noise function */\n double fLow, /* Lower bound of the frequency window for the detector */\n double fHigh, /* Upper bound of the frequency window for the detector */\n double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */\n double fstartobs2); /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n\n/* Function computing the overlap (h1|h2) between h1 given in Re/Im form and h2 given as a list of mode contributions (factos sYlm already included), for a given vector of noise values - uses simple trapeze integration - generates the frequency series of h2 in Re/Im form by summing the mode contributions first, then computes the overlap */\ndouble FDOverlapReImvsListmodesCAmpPhase(\n struct tagReImFrequencySeries *freqseries1, /* First waveform, in Re/Im form */\n struct tagListmodesCAmpPhaseFrequencySeries *list2, /* Second waveform, list of modes in amplitude/phase form */\n gsl_vector* noisevalues, /* Vector for the noise values on the freq of h1 */\n double fLow, /* Minimal frequency - set to 0 to ignore */\n double fHigh, /* Maximal frequency - set to 0 to ignore */\n double fstartobs2); /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n\n\n/* Function computing the overlap (h1|h2) between two waveforms given as Re/Im frequency series (common freq values), for a given vector of noise values - uses simple trapeze integration */\ndouble FDOverlapReImvsReIm(\n struct tagReImFrequencySeries *h1, /* First waveform, frequency series in Re/Im form */\n struct tagReImFrequencySeries *h2, /* Second waveform, frequency series in Re/Im form */\n gsl_vector* noisevalues); /* Vector for the noise values on common freq of the freqseries */\n\n/***************************** Functions for overlaps using amplitude/phase (wip) ******************************/\n\n/* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form, for a given noise function - uses the amplitude/phase representation (wip) */\ndouble FDSinglemodeWIPOverlap(\n struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */\n struct tagCAmpPhaseFrequencySeries *freqseries2, /* Second mode h2, in amplitude/phase form */\n ObjectFunction * Snoise, /* Noise function */\n double fLow, /* Lower bound of the frequency window for the detector */\n double fHigh); /* Upper bound of the frequency window for the detector */\n\n/* Function computing the overlap (h1|h2) between two waveforms given as list of modes, for a given noise function - no cross-products between modes are taken into account - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */\ndouble FDListmodesWIPOverlap(\n struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First waveform, list of modes in amplitude/phase form */\n struct tagListmodesCAmpPhaseFrequencySeries *listh2, /* Second waveform, list of modes in amplitude/phase form */\n ObjectFunction * Snoise, /* Noise function */\n double fLow, /* Lower bound of the frequency window for the detector */\n double fHigh, /* Upper bound of the frequency window for the detector */\n double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */\n double fstartobs2); /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n\n/************** Functions for overlap/likelihood allowing to switch between wip and loglinear integration *****************/\n\n/* Wrapping of FDListmodesWIPOverlap or FDListmodesLogLinearOverlap according to tagint */\ndouble FDListmodesOverlap(\n struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First mode h1, list of modes in amplitude/phase form */\n struct tagListmodesCAmpPhaseFrequencySeries *listh2, /* Second mode h2, list of modes in amplitude/phase form */\n ObjectFunction * Snoise, /* Noise function */\n double fLow, /* Lower bound of the frequency window for the detector */\n double fHigh, /* Upper bound of the frequency window for the detector */\n double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */\n double fstartobs2, /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n int tagint); /* Tag choosing the integrator: 0 for wip, 1 for log linear integration */\n\n/* Function computing the log likelihood (h|s) - 1/2 (h|h) - 1/2 (s|s), with s the signal, h the template, and where we keep the constant term (s|s) - passed to the function as a parameter - all the cross-products between modes are taken into account - two additionals parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */\ndouble FDLogLikelihood(\n struct tagListmodesCAmpPhaseFrequencySeries *lists, /* Input: list of modes for the signal s, in Frequency-domain amplitude and phase form */\n struct tagListmodesCAmpPhaseFrequencySeries *listh, /* Input: list of modes for the template, in Frequency-domain amplitude and phase form */\n ObjectFunction * Snoise, /* Noise function */\n double fLow, /* Lower bound of the frequency window for the detector */\n double fHigh, /* Upper bound of the frequency window for the detector */\n double ss, /* Inner product (s|s), constant to be computed elsewhere and passed as an argument */\n double hh, /* Inner product (h|h), constant to be computed elsewhere and passed as an argument */\n double fstartobss, /* Starting frequency for the 22 mode of s - as determined from a limited duration of the observation - set to 0 to ignore */\n double fstartobsh, /* Starting frequency for the 22 mode of h - as determined from a limited duration of the observation - set to 0 to ignore */\n int tagint); /* Tag choosing the integrator: 0 for wip, 1 for log linear integration */\n\n/************** Functions for overlap/likelihood specific to loglinear integration *****************/\n\n/* Function computing the log likelihood -1/2(h-s|h-s), with s the signal, h the template (both given as frequency series in Re/Im form) - h, s assumed to be given on the same set of frequencies - same for the vector of noise values - fstartobs for s, h has already been taken into account */\ndouble FDLogLikelihoodReIm(\n struct tagReImFrequencySeries *s, /* First waveform (injection), frequency series in Re/Im form */\n struct tagReImFrequencySeries *h, /* Second waveform (template), frequency series in Re/Im form */\n gsl_vector* noisevalues); /* Vector for the noise values on common freq of the freqseries */\n\n/***************************** Functions for overlaps using amplitude/phase (Fresnel) ******************************/\n\nvoid ComputeIntegrandValues(\n CAmpPhaseFrequencySeries** integrand, /* Output: values of the integrand on common frequencies (initialized in the function) */\n CAmpPhaseFrequencySeries* freqseries1, /* Input: frequency series for wf 1 */\n CAmpPhaseSpline* splines2, /* Input: splines in matrix form for wf 2 */\n ObjectFunction * Snoise, /* Noise function */\n double fLow, /* Lower bound of the frequency - 0 to ignore */\n double fHigh); /* Upper bound of the frequency - 0 to ignore */\n/* Function computing the integrand values, combining the three channels A, E and T */\nint ComputeIntegrandValues3Chan(\n CAmpPhaseFrequencySeries** integrand, /* Output: values of the integrand on common frequencies (initialized in the function) */\n CAmpPhaseFrequencySeries* freqseries1chan1, /* Input: frequency series for wf 1, channel 1 */\n CAmpPhaseFrequencySeries* freqseries1chan2, /* Input: frequency series for wf 1, channel 2 */\n CAmpPhaseFrequencySeries* freqseries1chan3, /* Input: frequency series for wf 1, channel 3 */\n CAmpPhaseSpline* splines2chan1, /* Input: splines in matrix form for wf 2, channel 1 */\n CAmpPhaseSpline* splines2chan2, /* Input: splines in matrix form for wf 2, channel 2 */\n CAmpPhaseSpline* splines2chan3, /* Input: splines in matrix form for wf 2, channel 3 */\n ObjectFunction * Snoise1, /* Noise function */\n ObjectFunction * Snoise2, /* Noise function */\n ObjectFunction * Snoise3, /* Noise function */\n double fLow, /* Lower bound of the frequency - 0 to ignore */\n double fHigh); /* Upper bound of the frequency - 0 to ignore */\n\n/* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form, one being already interpolated, for a given noise function - uses the amplitude/phase representation (Fresnel) */\ndouble FDSinglemodeFresnelOverlap(\n struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */\n struct tagCAmpPhaseSpline *splines2, /* Second mode h2, already interpolated in matrix form */\n ObjectFunction * Snoise, /* Noise function */\n double fLow, /* Lower bound of the frequency window for the detector */\n double fHigh); /* Upper bound of the frequency window for the detector */\n/* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form for each channel A, E, T, one being already interpolated, for a given noise function - uses the amplitude/phase representation (Fresnel) */\ndouble FDSinglemodeFresnelOverlap3Chan(\n struct tagCAmpPhaseFrequencySeries *freqseries1chan1, /* First mode h1 for channel 1, in amplitude/phase form */\n struct tagCAmpPhaseFrequencySeries *freqseries1chan2, /* First mode h1 for channel 2, in amplitude/phase form */\n struct tagCAmpPhaseFrequencySeries *freqseries1chan3, /* First mode h1 for channel 3, in amplitude/phase form */\n struct tagCAmpPhaseSpline *splines2chan1, /* Second mode h2 for channel 1, already interpolated in matrix form */\n struct tagCAmpPhaseSpline *splines2chan2, /* Second mode h2 for channel 2, already interpolated in matrix form */\n struct tagCAmpPhaseSpline *splines2chan3, /* Second mode h2 for channel 3, already interpolated in matrix form */\n ObjectFunction * Snoise1, /* Noise function */\n ObjectFunction * Snoise2, /* Noise function */\n ObjectFunction * Snoise3, /* Noise function */\n double fLow, /* Lower bound of the frequency window for the detector */\n double fHigh); /* Upper bound of the frequency window for the detector */\n\n/* Function computing the overlap (h1|h2) between two waveforms given as list of modes, one being already interpolated, for a given noise function - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */\ndouble FDListmodesFresnelOverlap(\n struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First waveform, list of modes in amplitude/phase form */\n struct tagListmodesCAmpPhaseSpline *listsplines2, /* Second waveform, list of modes already interpolated in matrix form */\n ObjectFunction * Snoise, /* Noise function */\n double fLow, /* Lower bound of the frequency window for the detector */\n double fHigh, /* Upper bound of the frequency window for the detector */\n double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */\n double fstartobs2); /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n/* Function computing the overlap (h1|h2) between two waveforms given as list of modes for each non-correlated channel 1,2,3, one being already interpolated, for a given noise function - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */\ndouble FDListmodesFresnelOverlap3Chan(\n struct tagListmodesCAmpPhaseFrequencySeries *listh1chan1, /* First waveform channel channel 1, list of modes in amplitude/phase form */\n struct tagListmodesCAmpPhaseFrequencySeries *listh1chan2, /* First waveform channel channel 2, list of modes in amplitude/phase form */\n struct tagListmodesCAmpPhaseFrequencySeries *listh1chan3, /* First waveform channel channel 3, list of modes in amplitude/phase form */\n struct tagListmodesCAmpPhaseSpline *listsplines2chan1, /* Second waveform channel channel 1, list of modes already interpolated in matrix form */\n struct tagListmodesCAmpPhaseSpline *listsplines2chan2, /* Second waveform channel channel 2, list of modes already interpolated in matrix form */\n struct tagListmodesCAmpPhaseSpline *listsplines2chan3, /* Second waveform channel channel 3, list of modes already interpolated in matrix form */\n ObjectFunction * Snoise1, /* Noise function */\n ObjectFunction * Snoise2, /* Noise function */\n ObjectFunction * Snoise3, /* Noise function */\n double fLow, /* Lower bound of the frequency window for the detector */\n double fHigh, /* Upper bound of the frequency window for the detector */\n double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */\n double fstartobs2); /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _LIKELIHOOD_H */\n", "meta": {"hexsha": "8228133b207e020c54e55d90c6d4bd36f2dec797", "size": 20235, "ext": "h", "lang": "C", "max_stars_repo_path": "tools/likelihood.h", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/likelihood.h", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/likelihood.h", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.94, "max_line_length": 405, "alphanum_fraction": 0.6528292562, "num_tokens": 4249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.43193356322224874}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include /* pow */\n#include \n#include \n#include \n\n\n/* Conversion constants */\n// megaparsec to km\nconst double mptkm = 3.086e19;\n// kg to Gev\nconst double kgtgev = 5.62e26;\n// Gev to kg\nconst double gevtkg = 1.78e-27;\n//// 1/seconds to GeV\nconst double dstgev = 6.58e-25;\n// Gev to 1/seconds\nconst double gevtds = 1.52e24;\n// Kelvin to 1/s\nconst double keltds = 8.62e-14;\n// Solar mass in kg\nconst double msol = 1.989e30;\n// 1/m to GeV\nconst double dmtgev = 1.98e-16;\n// Kelvin to Gev\nconst double keltgev = 8.62e-14;\n\n\n/* LCDM constants and yield from Planck 2018 1807.06209 */\n// Hubble constant in inverse seconds\nconst double h0 = 67.32/mptkm;\n// Cold dark matter fraction from Planck 2018\nconst double oc = 0.265;\n// Baryonic matter fraction from Planck 2018\nconst double ob = 0.0494;\n// Total matter fraction from Planck 2018\nconst double om = oc+ob;\n// Radiation fraction from Planck 2018 + massless neutrinos\nconst double orad = 9.2367e-5;//0.00006;\n// Yield of B-L = n_B-L/ entropy density\nconst double yield = 1e-10;\n// Hooks value for yield 1404.0113\nconst double yieldhook = 9e-11;\n\n/* Scale factors */\nconst double ai = 1e-30; // starting factor ~ end of inflation \nconst double arad = 0.000264; // dm-rad equality\nconst double acmb = 9e-4; // CMB\nconst double alam = 0.5; // DM - Lambda equality\n\n/* Mass constants */\n// Planck mass in kg\nconst double mplanck = 2.176e-8;\n// log10 of planck mass (in kg)\nconst double lgmp = -7.66234;\n// log10 of maximum mass used in integrations in kg\nconst double lgmax =36.;\n// horizon mass in kg at time of radiation-matter equality --- 2001.04371\nconst double meq = 2.8e17;\n// Horizon mass when shortest wavelength reenters horizon - choice\nconst double ms = 1e-7;\n// log of 5 times ms\nconst double lgmf = -6.301;\n// proton mass in kg\nconst double protonm = 1.672621e-27;\n\n\n/* Decay constants */\n// Sum of degrees of freedom of standard model -- see 1404.0113 or our draft\nconst double gstar = 106.75;\n\n// sum of qi^2 gi\nconst double sumq2g = 13.;\n\n// 3 x gstar / (30720 pi) * Mplanck^4 in kg^4\nconst double cc = 7.4397e-34;\n\n// 3 x gstar / (30720 pi) * Mplanck^4 in kg^3/s\nconst double decfac = 6.35e17; // = cc*gevtds/gevtkg\n\n/* Newton's G in m^3 /kg / s^2 */\nconst double gnewton = 6.67e-11;\n\n/* Speeed of light in m/s */\nconst double sofl = 2.99792e8;\n\n// conversion factor from dM to dlog10[M]\nconst double intf = 2.30259;\n\n/* All parameters should be given in SI base units - conversions are handled in the functions*/\n\n// structure to hold relevant parameters\nstruct myparam_type2{\n\tdouble lambda; // coupling constant\n \tdouble lgn0; // log10 of final total number density of bh in 1/m^3\n\tdouble peakm; // log10 of mass spectrum peak in kg\n\tdouble Trh; // reheating Temperature in Kelvin\n\tdouble trh; // time of reheatting in s\n\tdouble aval; // scale factor\n\tbool rem; // remnants or not\n\tgsl_spline *spline;\n\tgsl_interp_accel *acc;\n\tbool mono; // monochromatic spectrum (true) or broad (false)\n} ;\n\n// Reduced structure for epoch/approximate calculations\nstruct myparam_type{\n\tdouble peakm; // mass spectrum peak\n\tdouble trh; // time of reheating\n\tdouble aval; // scale factor\n\tbool rem; // remnants or not\n};\n\n// structure for creating a(t) object\ntypedef struct arrays{\n int count;\n double xx[1002];\n double yy[1002]; } *arrays_T;\n", "meta": {"hexsha": "89c5bdef39a7be49c4896a162278c1581054aeec", "size": 3631, "ext": "h", "lang": "C", "max_stars_repo_path": "constants.h", "max_stars_repo_name": "nebblu/PBH", "max_stars_repo_head_hexsha": "b896bb65d0f204603e26b3579265d4cd613c48e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "constants.h", "max_issues_repo_name": "nebblu/PBH", "max_issues_repo_head_hexsha": "b896bb65d0f204603e26b3579265d4cd613c48e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "constants.h", "max_forks_repo_name": "nebblu/PBH", "max_forks_repo_head_hexsha": "b896bb65d0f204603e26b3579265d4cd613c48e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5075757576, "max_line_length": 95, "alphanum_fraction": 0.7066923712, "num_tokens": 1158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.43180273854450324}} {"text": "#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"ccl.h\"\n#include \"ccl_f2d.h\"\n#include \"ccl_emu17.h\"\n#include \"ccl_emu17_params.h\"\n\n// helper functions for BBKS and EH98\nstatic double bbks_power(ccl_parameters *params, void *p, double k) {\n return ccl_bbks_power(params, k);\n}\n\nstatic double eh_power(ccl_parameters *params, void *p, double k) {\n return ccl_eh_power(params, (eh_struct*)p, k);\n}\n\n/*------ ROUTINE: ccl_cosmology_compute_power_analytic -----\nINPUT: cosmology\nTASK: provide spline for an analytic power spectrum with baryonic correction\n*/\n\nstatic ccl_f2d_t *ccl_compute_linpower_analytic(ccl_cosmology* cosmo, void* par,\n double (*pk)(ccl_parameters* params,\n void* p, double k),\n int* status) {\n ccl_f2d_t *psp_out = NULL;\n double sigma8,log_sigma8;\n //These are the limits of the splining range\n double kmin = cosmo->spline_params.K_MIN;\n double kmax = cosmo->spline_params.K_MAX;\n //Compute nk from number of decades and N_K = # k per decade\n double ndecades = log10(kmax) - log10(kmin);\n int nk = (int)ceil(ndecades*cosmo->spline_params.N_K);\n // Compute na using predefined spline spacing\n double amin = cosmo->spline_params.A_SPLINE_MINLOG_PK;\n double amax = cosmo->spline_params.A_SPLINE_MAX;\n int na = cosmo->spline_params.A_SPLINE_NA_PK+cosmo->spline_params.A_SPLINE_NLOG_PK-1;\n\n // Exit if sigma8 wasn't specified\n if (isnan(cosmo->params.sigma8)) {\n *status = CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_linpower_analytic(): \"\n \"sigma8 not set, required for analytic power spectra\\n\");\n return NULL;\n }\n\n // The x array is initially k, but will later\n // be overwritten with log(k)\n double *x=NULL, *y=NULL, *z=NULL, *y2d=NULL;\n x=ccl_log_spacing(kmin, kmax, nk);\n if(x==NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_linpower_analytic(): \"\n \"memory allocation\\n\");\n }\n if(*status==0) {\n y=malloc(sizeof(double)*nk);\n if(y==NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_linpower_analytic(): \"\n \"memory allocation\\n\");\n }\n }\n if(*status==0) {\n z=ccl_linlog_spacing(amin, cosmo->spline_params.A_SPLINE_MIN_PK,\n amax, cosmo->spline_params.A_SPLINE_NLOG_PK,\n cosmo->spline_params.A_SPLINE_NA_PK);\n if(z==NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_linpower_analytic(): \"\n \"memory allocation\\n\");\n }\n }\n\n if(*status==0) {\n y2d = malloc(nk * na * sizeof(double));\n if(y2d==NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_linpower_analytic(): \"\n \"memory allocation\\n\");\n }\n }\n\n if(*status==0) {\n // Calculate P(k) on k grid. After this loop, x will contain log(k) and y\n // will contain log(pk) [which has not yet been normalized]\n // After this loop x will contain log(k)\n for (int i=0; iparams, par, x[i]));\n x[i] = log(x[i]);\n }\n }\n\n if(*status==0) {\n for (int j = 0; j < na; j++) {\n double gfac = ccl_growth_factor(cosmo,z[j], status);\n double g2 = 2.*log(gfac);\n for (int i=0; iparams.sigma8) - log(sigma8));\n for(int j=0;jparams),wiggled);\n if (eh != NULL) {\n psp=ccl_compute_linpower_analytic(cosmo, eh,\n eh_power,\n status);\n }\n else\n *status = CCL_ERROR_MEMORY;\n free(eh);\n return psp;\n}\n\n/*------ ROUTINE: ccl_compute_power_emu -----\nINPUT: cosmology\nTASK: provide spline for the emulated power spectrum from Cosmic EMU\n*/\n\nccl_f2d_t *ccl_compute_power_emu(ccl_cosmology * cosmo, int * status)\n{\n double Omeganuh2_eq;\n ccl_f2d_t *psp_out=NULL;\n\n // Check ranges to see if the cosmology is valid\n if(*status==0) {\n if((cosmo->params.h<0.55) || (cosmo->params.h>0.85)){\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_power_emu(): \"\n \"h is outside allowed range\\n\");\n }\n }\n\n if(*status==0) {\n // Check if the cosmology has been set up with equal neutrino masses for the emulator\n // If not, check if the user has forced redistribution of masses and if so do this.\n if(cosmo->params.N_nu_mass>0) {\n if (cosmo->config.emulator_neutrinos_method == ccl_emu_strict){\n if (cosmo->params.N_nu_mass==3){\n if (cosmo->params.m_nu[0] != cosmo->params.m_nu[1] ||\n cosmo->params.m_nu[0] != cosmo->params.m_nu[2] ||\n cosmo->params.m_nu[1] != cosmo->params.m_nu[2]){\n *status = CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_power_emu(): \"\n \"In the default configuration, you must pass a list of 3 \"\n \"equal neutrino masses or pass a sum and set \"\n \"m_nu_type = 'equal'. If you wish to over-ride this, \"\n \"set config->emulator_neutrinos_method = \"\n \"'ccl_emu_equalize'. This will force the neutrinos to \"\n \"be of equal mass but will result in \"\n \"internal inconsistencies.\\n\");\n }\n }else if (cosmo->params.N_nu_mass!=3){\n *status = CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_power_emu(): \"\n \"In the default configuration, you must pass a list of 3 \"\n \"equal neutrino masses or pass a sum and set \"\n \"m_nu_type = 'equal'. If you wish to over-ride this, \"\n \"set config->emulator_neutrinos_method = \"\n \"'ccl_emu_equalize'. This will force the neutrinos to \"\n \"be of equal mass but will result in \"\n \"internal inconsistencies.\\n\");\n }\n }else if (cosmo->config.emulator_neutrinos_method == ccl_emu_equalize){\n // Reset the masses to equal\n double mnu_eq[3] = {cosmo->params.sum_nu_masses / 3.,\n cosmo->params.sum_nu_masses / 3.,\n cosmo->params.sum_nu_masses / 3.};\n Omeganuh2_eq = ccl_Omeganuh2(1.0, 3, mnu_eq, cosmo->params.T_CMB, status);\n }\n } else {\n if(fabs(cosmo->params.N_nu_rel - 3.04)>1.e-6){\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_power_emu(): \"\n \"Set Neff = 3.04 for cosmic emulator predictions in \"\n \"absence of massive neutrinos.\\n\");\n }\n }\n }\n\n if(*status==0) {\n double w0wacomb = -cosmo->params.w0 - cosmo->params.wa;\n if(w0wacomb<8.1e-3){ //0.3^4\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_power_emu(): \"\n \"w0 and wa do not satisfy the emulator bound\\n\");\n }\n }\n\n if(*status==0) {\n if(cosmo->params.Omega_nu_mass*cosmo->params.h*cosmo->params.h>0.01){\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_power_emu(): \"\n \"Omega_nu does not satisfy the emulator bound\\n\");\n }\n }\n\n if(*status==0) {\n // Check to see if sigma8 was defined\n if(isnan(cosmo->params.sigma8)){\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_power_emu(): \"\n \"sigma8 is not defined; specify sigma8 instead of A_s\\n\");\n }\n }\n\n int na=cosmo->spline_params.A_SPLINE_NA_PK;\n double *lpk_1a=NULL,*lk=NULL,*aemu=NULL,*lpk_nl=NULL;\n if (*status == 0) {\n //Now start the NL computation with the emulator\n //These are the limits of the splining range\n aemu = ccl_linear_spacing(A_MIN_EMU,cosmo->spline_params.A_SPLINE_MAX, na);\n if(aemu==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_power_emu(): \"\n \"memory allocation error\\n\");\n }\n }\n if (*status == 0) {\n lk=malloc(NK_EMU*sizeof(double));\n if(lk==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_power_emu(): \"\n \"memory allocation error\\n\");\n }\n }\n if (*status == 0) {\n //The emulator only computes power spectra at fixed nodes in k,\n //given by the global variable \"mode\"\n for (int i=0; iparams.N_nu_mass>0) &&\n (cosmo->config.emulator_neutrinos_method == ccl_emu_equalize)){\n emu_par[0] = (cosmo->params.Omega_c+cosmo->params.Omega_b)*cosmo->params.h*cosmo->params.h + Omeganuh2_eq;\n }else{\n emu_par[0] = (cosmo->params.Omega_c+cosmo->params.Omega_b+cosmo->params.Omega_nu_mass)*cosmo->params.h*cosmo->params.h;\n }\n emu_par[1] = cosmo->params.Omega_b*cosmo->params.h*cosmo->params.h;\n emu_par[2] = cosmo->params.sigma8;\n emu_par[3] = cosmo->params.h;\n emu_par[4] = cosmo->params.n_s;\n emu_par[5] = cosmo->params.w0;\n emu_par[6] = cosmo->params.wa;\n if ((cosmo->params.N_nu_mass>0) &&\n (cosmo->config.emulator_neutrinos_method == ccl_emu_equalize)){\n emu_par[7] = Omeganuh2_eq;\n }else{\n emu_par[7] = cosmo->params.Omega_nu_mass*cosmo->params.h*cosmo->params.h;\n }\n emu_par[8] = 1./aemu[j]-1;\n //Need to have this here because otherwise overwritten by emu in each loop\n\n //Call emulator at this redshift\n ccl_pkemu(emu_par,NK_EMU,lpk_1a, status, cosmo);\n if (*status) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_compute_power_emu(): \"\n \"memory allocation error\\n\");\n break;\n }\n for (int i=0; ifk != NULL) {\n nk = plin->fk->size;\n x = plin->fk->x;\n }\n else {\n nk = plin->fka->interp_object.xsize;\n x = plin->fka->xarr;\n }\n\n //Find a array\n if(plin->fa != NULL) {\n na = plin->fa->size;\n z = plin->fa->x;\n }\n else {\n na = plin->fka->interp_object.ysize;\n z = plin->fka->yarr;\n }\n\n //Allocate pka array\n y2d = malloc(nk * na * sizeof(double));\n if (y2d == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_power.c: ccl_apply_halofit(): memory allocation\\n\");\n }\n }\n\n if (*status == 0) {\n // Calculate P(k) on a, k grid. After this loop, x will contain log(k) and y\n // will contain log(pk) [which has not yet been normalized]\n for (int j = 0; jpsp, lk * M_LN10, par->a,\n par->cosmo, par->status);\n double kR=k*par->R;\n double w = w_tophat_2d(kR);\n\n return pk*k*k*w*w;\n}\n\n/* --------- ROUTINE: ccl_sigmaB ---------\nINPUT: cosmology, comoving smoothing radius, scale factor\nTASK: compute sigmaB, the variance in the projected *linear* density field\nsmoothed with a 2D tophat filter of comoving size R\n*/\ndouble ccl_sigma2B(ccl_cosmology *cosmo,double R,double a,ccl_f2d_t *psp, int *status)\n{\n SigmaR_pars par;\n par.status = status;\n\n par.cosmo=cosmo;\n par.R=R;\n par.a=a;\n par.psp=psp;\n\n gsl_integration_cquad_workspace *workspace = NULL;\n gsl_function F;\n F.function=&sigma2B_integrand;\n F.params=∥\n double sigma_B;\n\n workspace = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n if (workspace == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n if (*status == 0) {\n int gslstatus = gsl_integration_cquad(&F,\n log10(cosmo->spline_params.K_MIN),\n log10(cosmo->spline_params.K_MAX),\n 0.0, cosmo->gsl_params.INTEGRATION_SIGMAR_EPSREL,\n workspace,&sigma_B,NULL,NULL);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_sigma2B():\");\n *status |= gslstatus;\n }\n }\n gsl_integration_cquad_workspace_free(workspace);\n\n return sigma_B*M_LN10/(2*M_PI);\n}\n\nvoid ccl_sigma2Bs(ccl_cosmology *cosmo,int na, double *a, double *R,\n double *sigma2B_out, ccl_f2d_t *psp, int *status) {\n#pragma omp parallel default(none) \\\n shared(cosmo, na, a, R, psp, sigma2B_out, status)\n {\n int ia;\n int local_status=*status;\n\n #pragma omp for\n for(ia=0; iapsp, lk * M_LN10, par->a,\n par->cosmo, par->status);\n double kR=k*par->R;\n double w = w_tophat(kR);\n\n return pk*k*k*k*w*w;\n}\n\n// Integrand for sigmaV integral\nstatic double sigmaV_integrand(double lk,void *params) {\n SigmaV_pars *par=(SigmaV_pars *)params;\n\n double k=pow(10.,lk);\n double pk=ccl_f2d_t_eval(par->psp, lk * M_LN10, par->a,\n par->cosmo, par->status);\n double kR=k*par->R;\n double w = w_tophat(kR);\n\n return pk*k*w*w/3.0;\n}\n\n/* --------- ROUTINE: ccl_sigmaR ---------\nINPUT: cosmology, comoving smoothing radius, scale factor\nTASK: compute sigmaR, the variance in the *linear* density field\nsmoothed with a tophat filter of comoving size R\n*/\ndouble ccl_sigmaR(ccl_cosmology *cosmo,double R,double a,ccl_f2d_t *psp, int *status) {\n\n SigmaR_pars par;\n par.status = status;\n\n par.cosmo=cosmo;\n par.R=R;\n par.a=a;\n par.psp=psp;\n\n gsl_integration_cquad_workspace *workspace = NULL;\n gsl_function F;\n F.function=&sigmaR_integrand;\n F.params=∥\n double sigma_R;\n\n workspace = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n if (workspace == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n if (*status == 0) {\n int gslstatus = gsl_integration_cquad(&F,\n log10(cosmo->spline_params.K_MIN),\n log10(cosmo->spline_params.K_MAX),\n 0.0, cosmo->gsl_params.INTEGRATION_SIGMAR_EPSREL,\n workspace,&sigma_R,NULL,NULL);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_sigmaR():\");\n *status |= gslstatus;\n }\n }\n gsl_integration_cquad_workspace_free(workspace);\n\n return sqrt(sigma_R*M_LN10/(2*M_PI*M_PI));\n}\n\n/* --------- ROUTINE: ccl_sigmaV ---------\nINPUT: cosmology, comoving smoothing radius, scale factor\nTASK: compute sigmaV, the variance in the *linear* displacement field\nsmoothed with a tophat filter of comoving size R\nThe linear displacement field is the gradient of the linear density field\n*/\ndouble ccl_sigmaV(ccl_cosmology *cosmo,double R,double a,ccl_f2d_t *psp, int *status) {\n\n SigmaV_pars par;\n par.status = status;\n\n par.cosmo=cosmo;\n par.R=R;\n par.a=a;\n par.psp=psp;\n\n gsl_integration_cquad_workspace *workspace = NULL;\n gsl_function F;\n F.function=&sigmaV_integrand;\n F.params=∥\n double sigma_V;\n\n workspace = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n\n if (workspace == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n\n if (*status == 0) {\n int gslstatus = gsl_integration_cquad(&F,\n log10(cosmo->spline_params.K_MIN),\n log10(cosmo->spline_params.K_MAX),\n 0.0, cosmo->gsl_params.INTEGRATION_SIGMAR_EPSREL,\n workspace,&sigma_V,NULL,NULL);\n\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_sigmaV():\");\n *status |= gslstatus;\n }\n }\n\n gsl_integration_cquad_workspace_free(workspace);\n\n return sqrt(sigma_V*M_LN10/(2*M_PI*M_PI));\n}\n\n/* --------- ROUTINE: ccl_sigma8 ---------\nINPUT: cosmology\nTASK: compute sigma8, the variance in the *linear* density field at a=1\nsmoothed with a tophat filter of comoving size 8 Mpc/h\n*/\n\ndouble ccl_sigma8(ccl_cosmology *cosmo, ccl_f2d_t *psp, int *status) {\n return ccl_sigmaR(cosmo, 8/cosmo->params.h, 1., psp, status);\n}\n\n// Integrand for kNL integral\nstatic double kNL_integrand(double k,void *params) {\n KNL_pars *par=(KNL_pars *)params;\n\n double pk=ccl_f2d_t_eval(par->psp, log(k), par->a,\n par->cosmo, par->status);\n\n return pk;\n}\n\n/* --------- ROUTINE: ccl_kNL ---------\nINPUT: cosmology, scale factor\nTASK: compute kNL, the scale for the non-linear cut\n*/\ndouble ccl_kNL(ccl_cosmology *cosmo,double a,ccl_f2d_t *psp, int *status) {\n\n KNL_pars par;\n par.status = status;\n par.a = a;\n par.psp=psp;\n\n par.cosmo=cosmo;\n gsl_integration_cquad_workspace *workspace = NULL;\n gsl_function F;\n F.function=&kNL_integrand;\n F.params=∥\n double PL_integral;\n\n workspace = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n if (workspace == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n if (*status == 0) {\n int gslstatus = gsl_integration_cquad(&F, cosmo->spline_params.K_MIN, cosmo->spline_params.K_MAX,\n 0.0, cosmo->gsl_params.INTEGRATION_KNL_EPSREL,\n workspace,&PL_integral,NULL,NULL);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_kNL():\");\n *status |= gslstatus;\n }\n }\n gsl_integration_cquad_workspace_free(workspace);\n double sigma_eta = sqrt(PL_integral/(6*M_PI*M_PI));\n return pow(sigma_eta, -1);\n}\n", "meta": {"hexsha": "ca91600d2160790566fb7f1b42376de22cc5cc83", "size": 24700, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_power.c", "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_issues_repo_path": "src/ccl_power.c", "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 703.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_forks_repo_path": "src/ccl_power.c", "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "avg_line_length": 32.5857519789, "max_line_length": 129, "alphanum_fraction": 0.5892307692, "num_tokens": 7233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.5, "lm_q1q2_score": 0.431695808501971}} {"text": "#include \n#include \n#include \"wf.h\"\n#include \"alphas.h\"\n#include \"glasma.h\"\n#include \n#include \n#include \n\n//workspace and global variables for integration\nstatic double abserr = 1.e-200;\nstatic double relerr = 1.e-20;\n\ndouble phiKernel(double x, void *params);\n\nstatic double result,error;\nstatic size_t neval;\nstatic gsl_function phiIntKernel;\n\ndouble d2Nglasma0(double pT, double qT, double phipq, double yp, double yq, double rts)\n{\n static struct glasma_params params;\n params.pT = pT;\n params.qT = qT;\n params.yp = yp;\n params.yq = yq;\n params.rts = rts;\n params.phipq = phipq;\n phiIntKernel.function = &phiKernel; \n (params.Kernel).function = &doubleKernel;\n\n phiIntKernel.params = ¶ms;\n gsl_integration_qng(&phiIntKernel, -M_PI, M_PI, abserr, relerr,\\\n &result, &error, &neval);\n\n double norm = (Nc*Nc)/gsl_pow_3(Nc*Nc-1.)/(4.*pow(M_PI,10.))/gsl_pow_2(pT*\n qT)*alpha(pT)*alpha(qT);\n\n return norm*result;\n}\n\ndouble d2Nglasma1(double pT, double yp, double yq, double rts)\n{\n double sinres, cosres;\n static struct glasma_params params;\n params.pT = pT;\n params.yp = yp;\n params.yq = yq;\n params.rts = rts;\n\n phiIntKernel.function = &phiKernel; \n (params.Kernel).function = &cosKernel;\n phiIntKernel.params = ¶ms;\n gsl_integration_qng(&phiIntKernel, -M_PI, M_PI, abserr, relerr, &cosres, &error, &neval);\n \n (params.Kernel).function = &sinKernel;\n phiIntKernel.params = ¶ms;\n gsl_integration_qng(&phiIntKernel, -M_PI, M_PI, abserr, relerr, &sinres, &error, &neval);\n\n double norm = (Nc*Nc)/gsl_pow_3(Nc*Nc-1.)/(4.*pow(M_PI,10.))/gsl_pow_2(pT*pT)*alpha(pT)*alpha(pT) ;\n\n return norm*(cosres*cosres + sinres*sinres);\n}\n\n\ndouble doubleKernel(double x, void *p)\n{\n struct glasma_params params = *(struct glasma_params *)p;\n \n double rts = params.rts;\n double pT, qT, yp, yq;\n double x1p, x2p, x1q, x2q, x1max, x2max;\n\n double phi = params.phi;\n double phipq = params.phipq;\n double kT = x;\n \n pT = params.pT;\n qT = params.qT;\n yp = params.yp;\n yq = params.yq;\n\n x1p = pT/rts*exp(+yp);\n x2p = pT/rts*exp(-yp);\n x1q = qT/rts*exp(+yq);\n x2q = qT/rts*exp(-yq);\n\n x1max = gsl_max(x1p,x1q);\n x2max = gsl_max(x2p,x2q);\n \n double qTmkT = sqrt( qT*qT + kT*kT - 2.0*qT*kT*cos(phipq-phi) );\n double qTpkT = sqrt( qT*qT + kT*kT + 2.0*qT*kT*cos(phipq-phi) );\n double pTmkT = sqrt( pT*pT + kT*kT - 2.0*pT*kT*cos(phi) );\n double pTpkT = sqrt( pT*pT + kT*kT + 2.0*pT*kT*cos(phi) );\n \n double pTmkTmqT = sqrt( pT*pT + kT*kT + qT*qT \\\n -2.0*pT*qT*cos(phipq) \\\n -2.0*pT*kT*cos(phi) \\\n +2.0*qT*kT*cos(phipq-phi)\\\n );\n\n double pTmkTpqT = sqrt( pT*pT + kT*kT + qT*qT \\\n +2.0*pT*qT*cos(phipq) \\\n -2.0*pT*kT*cos(phi) \\\n -2.0*qT*kT*cos(phipq-phi)\\\n );\n\n //diagram A & E\n //this factor of 0.5 is from\n //symmetrizing wrt pTmkT\n double AE = 0.5*kT*pow(wf(1,x1max,kT),2.0)\\\n *( wf(2,x2p,pTmkT) + wf(2,x2p,pTpkT) )\\\n *( wf(2,x2q,qTmkT) + wf(2,x2q,qTpkT) );\n\n //diagram B & F\n double BF = 0.5*kT*pow(wf(2,x2max,kT),2.0)\\\n *( wf(1,x1p,pTmkT) + wf(1,x1p,pTpkT) )\\\n *( wf(1,x1q,qTmkT) + wf(1,x1q,qTpkT) );\n \n double T1D, T2D, T1H, T2H, denD, denH;\n T1D = ( kT*pT*cos(phi)-kT*kT )\\\n *( pT*pT - pT*qT*cos(phipq) - pT*kT*cos(phi) - pow(pTmkTmqT,2.0) ) \\\n - (pT*kT*sin(phi))*(pT*qT*sin(phipq) + pT*kT*sin(phi) ); \n \n T1H = ( kT*pT*cos(phi)-kT*kT )\\\n *( pT*pT + pT*qT*cos(phipq) - pT*kT*cos(phi) - pow(pTmkTpqT,2.0) ) \\\n - (pT*kT*sin(phi))*(-pT*qT*sin(phipq) + pT*kT*sin(phi) ); \n \n T2D = ( kT*qT*cos(phipq-phi)+kT*kT )\\\n *( -qT*qT + pT*qT*cos(phipq) - qT*kT*cos(phipq-phi) + pow(pTmkTmqT,2.0) ) \\\n + (qT*kT*sin(phipq-phi))*(pT*qT*sin(phipq) - qT*kT*sin(phipq-phi) ); \n \n T2H = ( -kT*qT*cos(phipq-phi)+kT*kT )\\\n *( -qT*qT - pT*qT*cos(phipq) + qT*kT*cos(phipq-phi) + pow(pTmkTpqT,2.0) ) \\\n + (qT*kT*sin(phipq-phi))*(pT*qT*sin(phipq) - qT*kT*sin(phipq-phi) ); \n \n denD = pow(kT*pTmkTmqT*pTmkT*qTpkT,2.0);\n \n denH = pow(kT*pTmkTpqT*pTmkT*qTmkT,2.0);\n \n //this factor of 0.5 is from the different f^4\\delta^4 structure\n double D = 0.5*kT*T1D*T2D/denD\\\n *wf(1,x1max,kT)*wf(1,x1max,pTmkTmqT)*wf(2,x2max,pTmkT)*wf(2,x2max,qTpkT);\n \n double H = 0.5*kT*T1H*T2H/denH\\\n *wf(1,x1max,kT)*wf(1,x1max,pTmkTpqT)*wf(2,x2max,pTmkT)*wf(2,x2max,qTmkT);\n \n return (AE + BF + D + H);\n}\n\n\ndouble cosKernel(double x, void *p)\n{\n struct glasma_params params = *(struct glasma_params *)p;\n \n double rts = params.rts;\n double pT, yp, yq;\n double x1p, x2p, x1q, x2q, x1max, x2max;\n\n double phi = params.phi;\n double kT = x;\n \n pT = params.pT;\n yp = params.yp;\n yq = params.yq;\n\n x1p = pT/rts*exp(+yp);\n x2p = pT/rts*exp(-yp);\n x1q = pT/rts*exp(+yq);\n x2q = pT/rts*exp(-yq);\n\n x1max = gsl_max(x1p,x1q);\n x2max = gsl_max(x2p,x2q);\n \n double pTmkT = sqrt( pT*pT + kT*kT - 2.0*pT*kT*cos(phi) );\n\n double num = pow( kT*pT*cos(phi)-kT*kT, 2.0); \t \n double den = pow(kT*pTmkT,2.); \n\n return kT*wf(1,x1p,kT)*wf(2,x2p,pTmkT)*num/den;\n}\n\ndouble sinKernel(double x, void *p)\n{\n struct glasma_params params = *(struct glasma_params *)p;\n \n double rts = params.rts;\n double pT, yp, yq;\n double x1p, x2p, x1q, x2q, x1max, x2max;\n\n double phi = params.phi;\n double kT = x;\n \n pT = params.pT;\n yp = params.yp;\n yq = params.yq;\n\n x1p = pT/rts*exp(+yp);\n x2p = pT/rts*exp(-yp);\n x1q = pT/rts*exp(+yq);\n x2q = pT/rts*exp(-yq);\n\n x1max = gsl_max(x1p,x1q);\n x2max = gsl_max(x2p,x2q);\n \n double pTmkT = sqrt( pT*pT + kT*kT - 2.0*pT*kT*cos(phi) );\n\n double num = pow( kT*pT*sin(phi), 2.0); \t \n double den = pow( kT*pTmkT ,2.0); \n\n return kT*wf(1,x1max,kT)*wf(2,x2max,pTmkT)*num/den;\n}\n\n//does phi integration over d^2k_\\perp\ndouble phiKernel(double x, void *p)\n{\n struct glasma_params params = *(struct glasma_params *)p;\n double result, error;\n params.phi = x;\n \n gsl_function F = params.Kernel;\n F.params = ¶ms;\n\n gsl_integration_qng(&F, kT_min, 2.0*kT_max, abserr, relerr,\\\n &result, &error, &neval);\n\nreturn result;\n}\n\nvoid TabulateGlasma(FILE *out, double rts)\n{\n //returns dN/d^2p_T d^2q_T dy_p dy_q / (S_\\perp) [GeV^-2]\n //this is the delta function contribution\n //of the glasma graphs\n\n double yp, yq, rtpT;\n //double yrange = 6.0;\n double dy = 0.25;\n double yrange = dy;\n \n for (yp = -yrange; yp <= yrange; yp += dy)\n for (yq = -yrange; yq <= yrange; yq += dy)\n for (rtpT = .1; rtpT <= 5.11; rtpT += .2){\n fprintf(out,\"%10.2f\\t%10.2f\\t%10.2f\\t%10.5e\\n\", yp, yq, rtpT,\\\n d2Nglasma1(pow(rtpT,2.),yp,yq,rts) );\n }\n fclose(out);\n\nreturn;\n}\n", "meta": {"hexsha": "9d5bf334ebf6fbc66097a93f89cefcc6d6c0ff81", "size": 7046, "ext": "c", "lang": "C", "max_stars_repo_path": "src/glasma.c", "max_stars_repo_name": "kdusling/mpc", "max_stars_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/glasma.c", "max_issues_repo_name": "kdusling/mpc", "max_issues_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/glasma.c", "max_forks_repo_name": "kdusling/mpc", "max_forks_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0717131474, "max_line_length": 104, "alphanum_fraction": 0.5759296054, "num_tokens": 2855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.43165757017089945}} {"text": "//This does CELL (~soma) stage of GRU (gated recurrent unit) model.\n//This requires each neuron to have 3 input time series, X, Xr, Xz,\n//where X is the usual input and Xr, Xz the inputs for the reset and update gates.\n//X, Xr, Xz are the output of a separate linear IN stage (weights and baises).\n\n//For dim=0, R[:,t] = sig{Xr[:,t] + Ur*Y[:,t-1]} \\n\";\n// Z[:,t] = sig{Xz[:,t] + Uz*Y[:,t-1]} \\n\";\n// H[:,t] = R[:,t].*Y[:,t-1] \\n\";\n// Y[:,t] = Z[:,t].*Y[:,t-1] + (1-Z[:,t]).*tanh{X[:,t] + U*H[:,t]} \\n\";\n//with sizes X, Xr, Xz: N x T \\n\";\n// U, Ur, Uz: N x N \\n\";\n// Y : N x T \\n\";\n//\n//For dim=1, R[t,:] = sig{Xr[t,:] + Y[t-1,:]*Ur} \\n\";\n// Z[t,:] = sig{Xz[t,:] + Y[t-1,:]*Uz} \\n\";\n// H[t,:] = R[t,:].*Y[t-1,:] \\n\";\n// Y[t,:] = Z[t,:].*Y[t-1,:] + (1-Z[t,:]).*tanh{X[t,:] + H[t,:]*U} \\n\";\n//with sizes X, Xr, Xz: T x N \\n\";\n// U, Ur, Uz: N x N \\n\";\n// Y : T x N \\n\";\n//\n//where sig is the logistic (sigmoid) nonlinearity = 1/(1+exp(-x)),\n//R is the reset gate, Z is the update gate, H is an intermediate (hidden) vector,\n//U, Ur, Uz are NxN matrices, and Y is the output.\n\n//Note that, the neurons of a layer are independent only if U, Ur, Uz are diagonal matrices.\n//This is only really a CELL (~soma) stage in that case.\n\n#include \n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint gru3_s (float *Y, const float *X, const float *Xr, const float *Xz, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\nint gru3_d (double *Y, const double *X, const double *Xr, const double *Xz, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\n\nint gru3_inplace_s (float *X, const float *Xr, const float *Xz, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\nint gru3_inplace_d (double *X, const double *Xr, const double *Xz, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\n\n\nint gru3_s (float *Y, const float *X, const float *Xr, const float *Xz, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim)\n{\n const float o = 1.0f;\n size_t nT, tN;\n \n float *R, *Z, *H;\n if (!(R=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in gru3_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(Z=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in gru3_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in gru3_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n if (N==1u)\n {\n //R[0] = 1.0f / (1.0f+expf(-Xr[0]));\n Z[0] = 1.0f / (1.0f+expf(-Xz[0]));\n Y[0] = (1.0f-Z[0]) * tanhf(X[0]);\n for (size_t t=1; t\n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic double scaled_infnorm(const gsl_vector *x, const gsl_vector *g);\n\n/*\ngsl_multilarge_nlinear_test()\n Convergence tests for nonlinear least squares minimization\n\n(1) |dx_i| <= xtol * (1 + |x_i|) for all i\n(2) || g .* x ||_inf <= gtol ||f||^2\n(3) ||f(x+dx) - f(x)|| <= ftol * max(||f(x)||, 1)\n\nInputs: xtol - tolerance for step size\n gtol - tolerance for gradient vector\n ftol - tolerance for residual vector\n info - (output)\n 1 - stopped by small x step\n 2 - stopped by small gradient\n 3 - stopped by small residual vector change\n w - workspace\n*/\n\nint\ngsl_multilarge_nlinear_test (const double xtol, const double gtol,\n const double ftol, int *info,\n const gsl_multilarge_nlinear_workspace * w)\n{\n int status;\n double gnorm, fnorm, phi;\n\n *info = 0;\n\n status = gsl_multifit_test_delta(w->dx, w->x, xtol*xtol, xtol);\n if (status == GSL_SUCCESS)\n {\n *info = 1;\n return GSL_SUCCESS;\n }\n\n /* compute gnorm = max_i( g_i * max(x_i, 1) ) */\n gnorm = scaled_infnorm(w->x, w->g);\n\n /* compute fnorm = ||f|| */\n fnorm = gsl_blas_dnrm2(w->f);\n phi = 0.5 * fnorm * fnorm;\n\n#if 0\n fprintf(stderr, \"gnorm = %.12e fnorm = %.12e gnorm/phi = %.12e\\n\", gnorm, fnorm, gnorm / phi);\n#endif\n\n if (gnorm <= gtol * GSL_MAX(phi, 1.0))\n {\n *info = 2;\n return GSL_SUCCESS;\n }\n\n#if 0\n if (dfnorm <= ftol * GSL_MAX(fnorm, 1.0))\n {\n *info = 3;\n return GSL_SUCCESS;\n }\n#endif\n\n return GSL_CONTINUE;\n}\n\nstatic double\nscaled_infnorm(const gsl_vector *x, const gsl_vector *g)\n{\n const size_t n = x->size;\n size_t i;\n double norm = 0.0;\n\n for (i = 0; i < n; ++i)\n {\n double xi = GSL_MAX(gsl_vector_get(x, i), 1.0);\n double gi = gsl_vector_get(g, i);\n double tmp = fabs(xi * gi);\n\n if (tmp > norm)\n norm = tmp;\n }\n\n return norm;\n}\n", "meta": {"hexsha": "d2d8d087d3564c9264903d81a2045ebec7bc1f6f", "size": 2936, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multilarge_nlinear/convergence.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multilarge_nlinear/convergence.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multilarge_nlinear/convergence.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.2142857143, "max_line_length": 96, "alphanum_fraction": 0.6304495913, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.43129198221659004}} {"text": "/* rng/ranf.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n/* This is the CRAY RANF generator. The generator returns the\n upper 32 bits from each term of the sequence,\n\n x_{n+1} = (a x_n) mod m \n\n using 48-bit unsigned arithmetic, with a = 0x2875A2E7B175 and m =\n 2^48. The seed specifies the lower 32 bits of the initial value,\n x_1, with the lowest bit set (to prevent the seed taking an even\n value), and the upper 16 bits set to 0.\n\n There is a subtlety in the implementation of the seed. The initial\n state is put one step back by multiplying by the modular inverse of\n a mod m. This is done for compatibility with the original CRAY\n implementation.\n\n Note, you can only seed the generator with integers up to 2^32,\n while the CRAY uses wide integers which can cover all 2^48 states\n of the generator.\n\n The theoretical value of x_{10001} is 141091827447341.\n\n The period of this generator is 2^{46}. */\n\nstatic inline void ranf_advance (void *vstate);\nstatic unsigned long int ranf_get (void *vstate);\nstatic double ranf_get_double (void *vstate);\nstatic void ranf_set (void *state, unsigned long int s);\n\nstatic const unsigned short int a0 = 0xB175 ;\nstatic const unsigned short int a1 = 0xA2E7 ;\nstatic const unsigned short int a2 = 0x2875 ;\n\ntypedef struct\n {\n unsigned short int x0, x1, x2;\n }\nranf_state_t;\n\nstatic inline void\nranf_advance (void *vstate)\n{\n ranf_state_t *state = (ranf_state_t *) vstate;\n\n const unsigned long int x0 = (unsigned long int) state->x0 ;\n const unsigned long int x1 = (unsigned long int) state->x1 ;\n const unsigned long int x2 = (unsigned long int) state->x2 ;\n\n unsigned long int r ;\n \n r = a0 * x0 ;\n state->x0 = (r & 0xFFFF) ;\n \n r >>= 16 ;\n r += a0 * x1 + a1 * x0 ;\n state->x1 = (r & 0xFFFF) ;\n \n r >>= 16 ;\n r += a0 * x2 + a1 * x1 + a2 * x0 ;\n state->x2 = (r & 0xFFFF) ;\n}\n\nstatic unsigned long int \nranf_get (void *vstate)\n{\n unsigned long int x1, x2;\n\n ranf_state_t *state = (ranf_state_t *) vstate;\n ranf_advance (state) ; \n\n x1 = (unsigned long int) state->x1;\n x2 = (unsigned long int) state->x2;\n \n return (x2 << 16) + x1;\n}\n\nstatic double\nranf_get_double (void * vstate)\n{\n ranf_state_t *state = (ranf_state_t *) vstate;\n\n ranf_advance (state) ; \n\n return (ldexp((double) state->x2, -16)\n + ldexp((double) state->x1, -32) \n + ldexp((double) state->x0, -48)) ;\n}\n\nstatic void\nranf_set (void *vstate, unsigned long int s)\n{\n ranf_state_t *state = (ranf_state_t *) vstate;\n\n unsigned short int x0, x1, x2 ;\n unsigned long int r ;\n\n unsigned long int b0 = 0xD6DD ;\n unsigned long int b1 = 0xB894 ;\n unsigned long int b2 = 0x5CEE ;\n\n if (s == 0) /* default seed */\n {\n x0 = 0x9CD1 ;\n x1 = 0x53FC ;\n x2 = 0x9482 ;\n }\n else \n {\n x0 = (s | 1) & 0xFFFF ;\n x1 = s >> 16 & 0xFFFF ;\n x2 = 0 ;\n }\n\n r = b0 * x0 ;\n state->x0 = (r & 0xFFFF) ;\n \n r >>= 16 ;\n r += b0 * x1 + b1 * x0 ;\n state->x1 = (r & 0xFFFF) ;\n \n r >>= 16 ;\n r += b0 * x2 + b1 * x1 + b2 * x0 ;\n state->x2 = (r & 0xFFFF) ;\n\n return;\n}\n\nstatic const gsl_rng_type ranf_type =\n{\"ranf\", /* name */\n 0xffffffffUL, /* RAND_MAX */\n 0, /* RAND_MIN */\n sizeof (ranf_state_t),\n &ranf_set,\n &ranf_get,\n &ranf_get_double\n};\n\nconst gsl_rng_type *gsl_rng_ranf = &ranf_type;\n", "meta": {"hexsha": "a35fdcac0870f6e350a1a32f874664575a2e7e90", "size": 4249, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/rng/ranf.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/ranf.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/ranf.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.0674846626, "max_line_length": 81, "alphanum_fraction": 0.6450929631, "num_tokens": 1348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4309397256395574}} {"text": "/* multiroots/convergence.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n#include \n\nint\ngsl_multiroot_test_delta (const gsl_vector * dx, const gsl_vector * x, \n double epsabs, double epsrel)\n{\n size_t i;\n int ok = 1;\n const size_t n = x->size ;\n\n if (epsrel < 0.0)\n {\n GSL_ERROR (\"relative tolerance is negative\", GSL_EBADTOL);\n }\n\n for (i = 0 ; i < n ; i++)\n {\n double xi = gsl_vector_get(x,i);\n double dxi = gsl_vector_get(dx,i);\n double tolerance = epsabs + epsrel * fabs(xi) ;\n\n if (fabs(dxi) < tolerance)\n {\n ok = 1;\n }\n else\n {\n ok = 0;\n break;\n }\n }\n\n if (ok)\n return GSL_SUCCESS ;\n\n return GSL_CONTINUE;\n}\n\nint\ngsl_multiroot_test_residual (const gsl_vector * f, double epsabs)\n{\n size_t i;\n\n double residual = 0;\n\n const size_t n = f->size;\n\n if (epsabs < 0.0)\n {\n GSL_ERROR (\"absolute tolerance is negative\", GSL_EBADTOL);\n }\n \n for (i = 0 ; i < n ; i++)\n {\n double fi = gsl_vector_get(f, i);\n \n residual += fabs(fi);\n }\n\n\n if (residual < epsabs)\n {\n return GSL_SUCCESS;\n }\n \n return GSL_CONTINUE ;\n}\n\n", "meta": {"hexsha": "82ef6976df6a13438181804e29587859da0a5ddb", "size": 2010, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/multiroots/convergence.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/multiroots/convergence.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/multiroots/convergence.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 22.0879120879, "max_line_length": 72, "alphanum_fraction": 0.6223880597, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.4307197844274874}} {"text": "/** Function for dealiasing weather radar radial velocities.\n * @file libdealias.c\n * @author Adriaan Dokter, adapted from dealias.c RAVE functions by Gunther Haase\n * @date 2016-09-22\n */\n\n#include \"libdealias.h\"\n#include \n#include \n#include \n\nvoid printDealias(const float *points, const int nDims, const float nyquist[], \n const float vradObs[], float vradDealias[], const int nPoints, const int iProfileType, const int iLayer, const int iPass){\n fprintf(stderr,\"#iProfile iLayer iPass azim elev nyquist vrad vradd\\n\");\n for(int i=0; ix, 0), \n gsl_vector_get (s->x, 1), \n s->fval, size);\n #endif\n\n u1=gsl_vector_get(s->x, 0);\n v1=gsl_vector_get(s->x, 1);\n \n gsl_vector_set(uv, 0, u1);\n gsl_vector_set(uv, 1, v1);\n }\n }\n while (status == GSL_CONTINUE && iter < 100);\n\n #ifdef FPRINTFON\n fprintf(stdout,\"Finished dealias at (x,y)=%f,%f at f()=%f ...\\n\",u1,v1,s->fval);\n #endif\n\n // clean up\n gsl_vector_free(ss);\n gsl_multimin_fminimizer_free (s);\n \n if (status != GSL_SUCCESS) return 0;\n return 1;\n}\n\n\nint dealias_points(const float *points, const int nDims, const float nyquist[], \n const double NI_MIN, const float vo[], float vradDealias[], const int nPoints){\n \n int i, j, n, m, eind, fitOk;\n double min1, esum, u1, v1, min2, dmy;\n \n // number of rows\n m = DEALIAS_VAF;\n // number of columns\n n = DEALIAS_NF;\n \n // max number of folds of nyquist interval to test for\n double MVA=2*ceil(DEALIAS_VMAX/(2*NI_MIN));\n\n // polarscan matrix, torus projected x coordinate, eq. 6 Haase et al. 2004 jaot\n double *x = RAVE_CALLOC ((size_t)nPoints, sizeof(double));\n // polarscan matrix, torus projected y coordinate, eq. 7 Haase et al. 2004 jaot\n double *y = RAVE_CALLOC ((size_t)nPoints, sizeof(double));\n // U-components of test velocity fields\n double *uh = RAVE_CALLOC ((size_t)(m*n), sizeof(double));\n // V-components of test velocity fields\n double *vh = RAVE_CALLOC ((size_t)(m*n), sizeof(double));\n // radial velocities of the best fitting test field\n double *vt1 = RAVE_CALLOC ((size_t)nPoints, sizeof(double));\n // array with trigonometric conversions of the points array\n float *pointsTrigon = RAVE_CALLOC ((size_t)(3*nPoints), sizeof(double));\n \n // map measured data to 3D\n for (i=0; i\n * \n * This file is part of Matrix Market Suite.\n *\n * Matrix Market Suite is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Matrix Market Suite is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Matrix Market Suite. If not, see .\n */\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"DMxV-MPI.h\"\n\nvoid usageDMxVMPI(){\n\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"Usage: MM-Suite DMxV [options] \\n\");\n\tfprintf(stderr, \"\\nInput/output options:\\n\\n\");\n\tfprintf(stderr, \" -o STR Output file name. Default: stdout\\n\");\n\tfprintf(stderr, \" -r Input format is row per line. Default: False\\n\");\n\tfprintf(stderr, \"\\nParameters options:\\n\\n\");\n\tfprintf(stderr, \" -a DOUBLE Alpha. Default: 1.0\\n\");\n\tfprintf(stderr, \" -b DOUBLE Beta. Default: 0.0\\n\");\n\tfprintf(stderr, \"\\nPerformance options:\\n\\n\");\n\tfprintf(stderr, \" -t INT Number of threads to use in OpenBLAS. Default: 1\\n\");\n\tfprintf(stderr, \"\\n\");\n\n}\n\nint DMxVMPI(int argc, char *argv[], int numProcs, int myid) {\n\n\tint \t\t\tret_code = 1;\n\tint\t\t\toption;\n\t\n\tunsigned long \t\t*II;\n\tunsigned long \t\t*J;\n\tdouble \t\t\t*values;\n\t\n\tunsigned long \t\tM;\n\tunsigned long \t\tlocal_M;\n\tunsigned long \t\tN;\n\tunsigned long \t\tlong nz;\n\t\n\t\n\tdouble \t\t\t*vectorValues;\n\tunsigned long \t\tM_Vector;\n\tunsigned long \t\tN_Vector;\n\tunsigned long long \tnz_vector;\n\t\n\tchar\t\t\t*outputFileName = NULL;\n\t\n\tchar\t\t\t*inputMatrixFile = NULL;\n\tchar\t\t\t*inputVectorFile = NULL;\n\tchar\t\t\t*outputVectorFile = NULL;\n\t\n\tint\t\t\tinputFormatRow = 0;\n\t\n\tdouble\t\t\talpha = 1.0;\n\tdouble\t\t\tbeta = 0.0;\n\t\n\tint \t\tnumThreads = 1;\n\t\n\tint\t\t\ti, j;\n\t\n\twhile ((option = getopt(argc, argv,\"ro:a:b:t:\")) >= 0) {\n\t\tswitch (option) {\n\t\t\tcase 'o' : \n\t\t\t\t//free(outputFileName);\n\t\t\t\t\n\t\t\t\toutputFileName = (char *) malloc(sizeof(char)*strlen(optarg)+1);\n\t\t\t\tstrcpy(outputFileName,optarg);\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'r':\n\t\t\t\tinputFormatRow = 1;\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'b':\n\t\t\t\tbeta = atof(optarg);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'a':\n\t\t\t\talpha = atof(optarg);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 't':\n\t\t\t\tnumThreads = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tdefault: break;\n\t\t}\n\t\n\t}\n\t\n\tif ((optind + 3 != argc) && (optind + 2 != argc)) {\n\t\tif (myid == 0) {\n\t\t\t//fprintf(stderr,\"[%s] Argc: %d, optind: %d\\n\",__func__, argc, optind);\n\t\t\tusageDMxVMPI();\n\t\t}\n\t\treturn 0;\n\t}\n\t\n\topenblas_set_num_threads(numThreads);\n\t\n\tif(optind + 3 == argc) { //We have an output vector\n\t\n\t\toutputVectorFile = (char *)malloc(sizeof(char)*strlen(argv[optind+2])+1);\n\t\tstrcpy(outputVectorFile,argv[optind+2]);\n\t}\n\t\n\tif(outputFileName == NULL) {\n\t\toutputFileName = (char *) malloc(sizeof(char)*6);\n\t\tsprintf(outputFileName,\"stdout\");\n\t}\n\t\n\tinputMatrixFile = (char *)malloc(sizeof(char)*strlen(argv[optind])+1);\n\tinputVectorFile = (char *)malloc(sizeof(char)*strlen(argv[optind+1])+1);\n\t\n\t\n\tstrcpy(inputMatrixFile,argv[optind]);\n\tstrcpy(inputVectorFile,argv[optind+1]);\n\t\n\t\n\t//Read matrix\n\tif(inputFormatRow) {\n\t\tif(!readDenseCoordinateMatrixMPIRowLine(inputMatrixFile,&II,&J,&values,&M,&local_M,&N,&nz,myid, numProcs)){\n\t\t\tfprintf(stderr, \"[%s] Can not read Matrix\\n\",__func__);\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse{\n\t\tif(!readDenseCoordinateMatrixMPI(inputMatrixFile,&II,&J,&values,&M,&local_M,&N,&nz,myid, numProcs)){\n\t\t\tfprintf(stderr, \"[%s] Can not read Matrix\\n\",__func__);\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\t//Read input vector\n\tif(!readDenseVector(inputVectorFile, &vectorValues,&M_Vector,&N_Vector,&nz_vector)){\n\t\tfprintf(stderr, \"[%s] Can not read Vector\\n\",__func__);\n\t\treturn 0;\n\t}\n\n\n\t/*\n\tvoid cblas_dgemv(const enum CBLAS_ORDER order,\n const enum CBLAS_TRANSPOSE TransA, const int M, const int N,\n const double alpha, const double *A, const int lda,\n const double *X, const int incX, const double beta,\n double *Y, const int incY);\n */\n \n double *partial_result=(double *) calloc(local_M,sizeof(double));\n double* y = (double*)calloc(N,sizeof(double));\n \n if(y == NULL){\n\t\tfprintf(stderr,\"[%s] Error reserving memory for final result vector in processor %d\\n\",__func__,myid);\n\t\treturn 0;\n\t}\n \n //Read output vector if any\n\tif(outputVectorFile != NULL) {\n\t\tif(!readDenseVector(outputVectorFile, &y,&M_Vector,&N_Vector,&nz_vector)){\n\t\t\tfprintf(stderr, \"[%s] Can not read Vector %s\\n\",__func__, outputVectorFile);\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tfor( i = (local_M * myid), j = 0; i< (local_M * myid + local_M) && j< local_M; i++, j++) {\n \t\tpartial_result[j] = y [i];\n \t}\n\t}\n \n \n \n double t_real = realtime();\n \n //y := alpha * A * x + beta * y\n\t\n\t//cblas_dgemv(CblasRowMajor,CblasNoTrans,local_M,N,1.0,values,N,vectorValues,1,0.0,partial_result,1);\n\tcblas_dgemv(CblasRowMajor,CblasNoTrans,local_M,N,alpha,values,N,vectorValues,1,beta,partial_result,1);\n\t\n\t\n\t\n\t\n\tMPI_Allgather (partial_result,local_M,MPI_DOUBLE,y,local_M,MPI_DOUBLE,MPI_COMM_WORLD);\n\tMPI_Barrier(MPI_COMM_WORLD);\n\t\n\t\n\tfprintf(stderr, \"\\n[%s] Time spent in DMxV: %.6f sec\\n\", __func__, realtime() - t_real);\n\t\n\tif (myid == 0){\n\n\t\twriteDenseVector(outputFileName, y,M_Vector,N_Vector,nz_vector);\n\n\t}\n\treturn ret_code;\n}\n\n", "meta": {"hexsha": "9e3f67cd317ccf44127abaca8690660b7041cb17", "size": 5788, "ext": "c", "lang": "C", "max_stars_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/MPI/operations/DMxV-MPI.c", "max_stars_repo_name": "vkeller/math-454", "max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z", "max_issues_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/MPI/operations/DMxV-MPI.c", "max_issues_repo_name": "vkeller/math-454", "max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/MPI/operations/DMxV-MPI.c", "max_forks_repo_name": "vkeller/math-454", "max_forks_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9209302326, "max_line_length": 109, "alphanum_fraction": 0.6394263994, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.4304715748969659}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \"Effective_Potential.h\"\r\n\r\n#define PI 3.14159265\r\n#define G 4.30091252525*pow(10,-3) //grav constant, in (parsec*km^2)/(Ms*sec^2)\r\n#define c 300000 //speed of light, km/sec\r\n\r\n\r\nvoid Geodesic_Orbit(int* time_size, double M, double periapsis, double e)\r\n{\r\n int dimension = 2;\t\t/* number of differential equations */\r\n\r\n double eps_abs = 1.e-8;\t/* absolute error requested */\r\n double eps_rel = 1.e-10;\t/* relative error requested */\r\n\r\n /* define the type of routine for making steps: */\r\n const gsl_odeiv_step_type *type_ptr = gsl_odeiv_step_rkf45;\r\n\r\n /*\r\n allocate/initialize the stepper, the control function, and the\r\n evolution function.\r\n */\r\n gsl_odeiv_step *step_ptr = gsl_odeiv_step_alloc (type_ptr, dimension);\r\n gsl_odeiv_control *control_ptr = gsl_odeiv_control_y_new (eps_abs, eps_rel);\r\n gsl_odeiv_evolve *evolve_ptr = gsl_odeiv_evolve_alloc (dimension);\r\n\r\n gsl_odeiv_system my_system;\t/* structure with the rhs function, etc. */\r\n\r\n double E = E_r(M, periapsis, e);\r\n double L = L_r(e,periapsis,M);\r\n double r[*time_size];\t\t\t/* current solution vector */\r\n\r\n double T, T_next;\t\t/* current and next independent variable */\r\n double Tmin, Tmax, delta_t;\t/* range of t and step size for output */\r\n\r\n double h = 1e-6;\t\t/* starting step size for ode solver */\r\n}\r\n", "meta": {"hexsha": "fb8bdc74b213bf59fa95d6e21737f4d590c14d67", "size": 1455, "ext": "c", "lang": "C", "max_stars_repo_path": "Geodesic_Orbit.c", "max_stars_repo_name": "ladanuzhna/Black-Holes-simulations", "max_stars_repo_head_hexsha": "5914c5120ff2340914641b3e475e33392eeb7cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Geodesic_Orbit.c", "max_issues_repo_name": "ladanuzhna/Black-Holes-simulations", "max_issues_repo_head_hexsha": "5914c5120ff2340914641b3e475e33392eeb7cbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Geodesic_Orbit.c", "max_forks_repo_name": "ladanuzhna/Black-Holes-simulations", "max_forks_repo_head_hexsha": "5914c5120ff2340914641b3e475e33392eeb7cbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.487804878, "max_line_length": 81, "alphanum_fraction": 0.676975945, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4302656442689631}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \"sacio.h\"\n#include \"parmt_utils.h\"\n#ifdef PARMT_USE_INTEL\n#include \n#include \n#include \n#else\n#include \n#include \n#endif\n#include \"parmt_mtsearch.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/random/random.h\"\n#include \"iscl/signal/convolve.h\"\n#include \"iscl/time/time.h\"\n\nint testBlockSize(void);\n\nint main()\n{\n char *ffList[10] = {\"rotation_data/B00103ZDS.sac\\0\",\n \"rotation_data/B00106ZSS.sac\\0\",\n \"rotation_data/B00101ZDD.sac\\0\",\n \"rotation_data/B00109ZEX.sac\\0\",\n \"rotation_data/B00104RDS.sac\\0\",\n \"rotation_data/B00107RSS.sac\\0\",\n \"rotation_data/B00102RDD.sac\\0\",\n \"rotation_data/B00110REX.sac\\0\",\n \"rotation_data/B00105TDS.sac\\0\",\n \"rotation_data/B00108TSS.sac\\0\"};\n struct parmtNoiseBasis_struct basis;\n struct sacData_struct sacZDS, sacZSS, sacZDD, sacZEX,\n sacRDS, sacRSS, sacRDD, sacREX,\n sacTDS, sacTSS, sac;\n double *CeInv, *CeInvDiag, *d, *dn, *G, *R, *X,\n *mts, *betas, *gammas, *kappas, *M0s,\n *phi, *sigmas, *thetas, *xrand, *var, *eye;\n double baz, betaMax, betaMin, gammaMax, gammaMin, kappaMin, kappaMax,\n m0Min, m0Max, sigmaMax, sigmaMin, thetaMax, thetaMin;\n double cmpaz, cmpinc, sigma, xnorm;\n int *lags, i, icomp, ierr, imt, imtopt, j, ldc, ldz, ng, nb, nk,\n nlags, ns, nt, nm, nmt, npgrns, npts, rank;\n bool lrescale = false;\n const double oneDeg = M_PI/180.0; // one degree for padding\n const double az = 25.0;\n const int ldm = 8;\n const int blockSize = 32;\n iscl_init();\n // Discretize the moment tensor space\n ng = 11; // longitudes\n nb = 11; // colatitudes\n nk = 11; // strike angles\n ns = 11; // rake\n nt = 11; // dip\n nm = 4; // magnitudes\n betaMin = 0.0 + oneDeg;\n betaMax = M_PI - oneDeg;\n gammaMin =-M_PI/6.0 + oneDeg;\n gammaMax = M_PI/6.0 - oneDeg;\n kappaMin = 0.0 + oneDeg;\n kappaMax = 2.0*M_PI - oneDeg;\n thetaMin = 0.0 + oneDeg;\n thetaMax = 0.5*M_PI - oneDeg;\n sigmaMin =-0.5*M_PI + oneDeg;\n sigmaMax = 0.5*M_PI - oneDeg;\n m0Min = 1.0/sqrt(2.0);\n m0Max = 2.0/sqrt(2.0);\n //m0Max = 1.e8/sqrt(2.0) + (double) (nm - 1)*1.e8/sqrt(2.0);\n //omp_set_num_threads(nthreads);\n mkl_set_num_threads(1);\n // Discretize the MT space\n M0s = array_linspace64f(m0Min, m0Max, nm, &ierr);\n betas = array_linspace64f(betaMin, betaMax, nb, &ierr);\n gammas = array_linspace64f(gammaMin, gammaMax, ng, &ierr);\n kappas = array_linspace64f(kappaMin, kappaMax, nk, &ierr);\n thetas = array_linspace64f(thetaMin, thetaMax, nt, &ierr);\n sigmas = array_linspace64f(sigmaMin, sigmaMax, ns, &ierr);\n nmt = ng*nb*nk*ns*nt*nm; \n mts = memory_calloc64f(nmt*ldm);\n ierr = parmt_discretizeMT64f(ng, gammas,\n nb, betas,\n nm, M0s,\n nk, kappas,\n nt, thetas,\n ns, sigmas,\n ldm, nmt, mts);\n if (ierr != 0)\n {\n printf(\"Failed to discretize MTs\\n\");\n return EXIT_FAILURE;\n }\n memory_free64f(&M0s);\n memory_free64f(&betas);\n memory_free64f(&gammas);\n memory_free64f(&kappas);\n memory_free64f(&thetas);\n memory_free64f(&sigmas);\n // Read the green's functions generated by CPS\n memset(&sacZDS, 0, sizeof(struct sacData_struct));\n memset(&sacZSS, 0, sizeof(struct sacData_struct));\n memset(&sacZDD, 0, sizeof(struct sacData_struct));\n memset(&sacZEX, 0, sizeof(struct sacData_struct));\n memset(&sacRDS, 0, sizeof(struct sacData_struct));\n memset(&sacRSS, 0, sizeof(struct sacData_struct));\n memset(&sacRDD, 0, sizeof(struct sacData_struct));\n memset(&sacREX, 0, sizeof(struct sacData_struct));\n memset(&sacTDS, 0, sizeof(struct sacData_struct));\n memset(&sacTSS, 0, sizeof(struct sacData_struct));\n ierr = sacio_readTimeSeriesFile(ffList[0], &sacZDS);\n ierr += sacio_readTimeSeriesFile(ffList[1], &sacZSS);\n ierr += sacio_readTimeSeriesFile(ffList[2], &sacZDD);\n ierr += sacio_readTimeSeriesFile(ffList[3], &sacZEX);\n ierr += sacio_readTimeSeriesFile(ffList[4], &sacRDS);\n ierr += sacio_readTimeSeriesFile(ffList[5], &sacRSS);\n ierr += sacio_readTimeSeriesFile(ffList[6], &sacRDD);\n ierr += sacio_readTimeSeriesFile(ffList[7], &sacREX);\n ierr += sacio_readTimeSeriesFile(ffList[8], &sacTDS);\n ierr += sacio_readTimeSeriesFile(ffList[9], &sacTSS);\n if (ierr != 0)\n {\n printf(\"Failed to load fundmaental faults\\n\");\n return EXIT_FAILURE;\n }\n // Set the green's functions\n npgrns = MIN(64, sacZDS.npts);\n npts = npgrns;\n icomp = 1; // vertical\n cmpaz = 0.0; // channel azimuth\n cmpinc =-90.0; // channel orientation (-90+ up 0 is horizontal)\n G = memory_calloc64f(6*npgrns);\n printf(\"Setting Green's functions...\\n\");\n baz = fmod(az + 180, 360.0);\n ierr = parmt_utils_ff2mtGreens64f(npgrns, icomp,\n az, baz,\n cmpaz, cmpinc,\n sacZDS.data, sacZSS.data,\n sacZDD.data, sacZEX.data,\n sacRDS.data, sacRSS.data,\n sacRDD.data, sacREX.data,\n sacTDS.data, sacTSS.data,\n &G[0*npgrns], &G[1*npgrns], &G[2*npgrns],\n &G[3*npgrns], &G[4*npgrns], &G[5*npgrns]);\n if (ierr != 0)\n {\n printf(\"Failed to set Green's functions\\n\");\n return EXIT_FAILURE;\n }\n // Free intermediate memory\n sacio_free(&sacZDS);\n sacio_free(&sacZSS);\n sacio_free(&sacZDD);\n sacio_free(&sacZEX);\n sacio_free(&sacRDS);\n sacio_free(&sacRSS);\n sacio_free(&sacRDD);\n sacio_free(&sacREX);\n sacio_free(&sacTDS);\n sacio_free(&sacTSS);\n // make a noise matrix \n ldc = npts;\n CeInv = memory_calloc64f(npts*ldc);\n R = memory_calloc64f(npts*ldc);\n X = memory_calloc64f((2*npts-1)*ldc);\n //xrand = random_randn64f(npts, 0.0, 0.01, &ierr); \n xrand = random_rand64f(npts, &ierr);\n xrand[0] = 0.0;\n xrand[npts-1] = 0.0;\n xnorm = cblas_dnrm2(npts, xrand, 1);\n cblas_dscal(npts, 1.0/xnorm, xrand, 1);\n ierr = convolve_corrmtx64f_work(npts, xrand,\n npts-1, ldc, X,\n CORRMTX_AUTOCORRELATION,\n true, ldc, R);\nFILE *fmat = fopen(\"xcmat.txt\", \"w\");\nfor (i=0; i 1.e-14)\n {\n printf(\"Failed to locate lrescaled script %e\\n\",\n fabs(phi[imtNew] - phi[imt]));\n return EXIT_FAILURE;\n }\n }\n printf(\"L1 rescaled lagged est + true optimal indices: %d %d %d %e %e\\n\",\n imt, imtopt, lags[imt], phi[imt], phi[imtopt]);\n printf(\"Rescaled lagged time: %f (s)\\n\", time_toc());\n\n // repeat with lags \n ierr = testBlockSize();\n/*\n nlags = 10;\n eye = array_set64f(npts, 1.0, &ierr);\n ierr = parmt_mtSearchL164f(ldm, nmt, npts, blockSize,\n nlags, true,\n &G[0*npgrns], &G[1*npgrns], &G[2*npgrns],\n &G[3*npgrns], &G[4*npgrns], &G[5*npgrns],\n eye, mts, d, phi, var, lags);\n imt = array_argmax64f(nmt, phi, &ierr);\n printf(\"L1 est + true optimal indices: %d %d %e %d\\n\", imt, imtopt, phi[imt], lags[imt]);\n printf(\"Unlagged general matrix time: %f (s)\\n\", time_toc());\n*/\n/*\n //------------------------------------------------------------------------//\n // unlagged kl //\n //------------------------------------------------------------------------//\n time_tic();\n ldz = basis.lde;\n ierr = parmt_mtSearchKL64f(nlags, nmt,\n npts, ldz,\n rank,\n sigma,\n &G[0*npgrns], &G[1*npgrns], &G[2*npgrns],\n &G[3*npgrns], &G[4*npgrns], &G[5*npgrns],\n basis.sqrtEvals,\n basis.evects,\n mts, dn, phi);\n if (ierr != 0)\n {\n printf(\"Failed calling mtSearchKL64f unlagged\\n\");\n return EXIT_FAILURE;\n }\n imt = array_argmax64f(nmt, phi, &ierr);\n*/\n/*\n if (imt != imtopt)\n {\n printf(\"Failed to locate unlagged kl optimum\\n\");\n return EXIT_FAILURE;\n }\n*/\n/*\n printf(\"est + true optimal indices: %d %d %e %e %e\\n\", imt, imtopt,\n phi[imt], phi[imtopt], phi[array_argmin64f(nmt, phi)]);\n printf(\"%e\\n\", array_sum64f(nmt, phi, &ierr));\n printf(\"Unlagged general kl time %f (s)\\n\", time_toc());\n*/\n//TEST:;\n/*\ndouble *est = memory_calloc64f(npts);\n cblas_dgemv(CblasColMajor, CblasNoTrans,\n npgrns, 6, 1.0, G, npgrns,\n &mts[ldm*imt], 1, 0.0, est, 1);\nFILE *fn = fopen(\"noise.txt\",\"w\");\nfor (i=0; i DBL_EPSILON*(double) nmt)\n {\n printf(\"Error computing blocksize\\n\");\n ierr = 1; \n goto ERROR;\n }\n imt = array_argmax64f(nmt, phi, &ierr);\n if (imt != imtopt)\n {\n printf(\"Failed to locate optimum\\n\");\n ierr = 1;\n goto ERROR;\n }\n }\n fclose(fout);\n }\nERROR:;\n // restore number of threads\n omp_set_num_threads(nt0);\n // clear memory\n memory_free64f(&d);\n memory_free64f(&phiOri);\n memory_free64f(&phi);\n memory_free64f(&eye);\n memory_free64f(&var);\n memory_free64f(&mts);\n memory_free64f(&G);\n return 0;\n}\n", "meta": {"hexsha": "bdd10a16277c45022a7248964d7bf0c27fc6e00e", "size": 23416, "ext": "c", "lang": "C", "max_stars_repo_path": "src/unit_tests.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/unit_tests.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unit_tests.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8755905512, "max_line_length": 93, "alphanum_fraction": 0.517851042, "num_tokens": 7396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4302092750014358}} {"text": "/******************************************************************************\nCosmoLike Configuration Space Covariances for Projected Galaxy 2-Point Statistics\nhttps://github.com/CosmoLike/CosmoCov\nby CosmoLike developers\n******************************************************************************/\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\nvoid cov_G_cl_cl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, double **cov_g_interp);\nvoid cov_NG_cl_cl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, double **cov_ng_interp);\nvoid cov_G_cl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int zl, int zs, double **cov_g_interp);\nvoid cov_NG_cl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int zl, int zs, double **cov_ng_interp);\nvoid cov_G_cl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm, double **cov_g_interp);\nvoid cov_NG_cl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm, double **cov_ng_interp);\nvoid cov_G_gl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl1, int zs1, int zl2, int zs2, double **cov_g_interp);\nvoid cov_NG_gl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl1, int zs1, int zl2, int zs2, double **cov_ng_interp);\nvoid cov_G_gl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl, int zs, int z3, int z4, int pm, double **cov_g_interp);\nvoid cov_NG_gl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl, int zs, int z3, int z4, int pm, double **cov_ng_interp);\nvoid cov_G_shear_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm1, int pm2, double **cov_g_interp);\nvoid cov_NG_shear_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm1, int pm2, double **cov_ng_interp);\n\nvoid cov_G_real_fft_bin_template(double *theta, int Ntheta, double **cov_g_interp, config my_config, double *N, int *array, double *task_type);\nvoid cov_NG_real_fft_bin_template(double *theta, int Ntheta, double **cov_ng_interp, config my_config, int *array, double *task_type);\n\ndouble func_for_cov_G_shear(double l, int *ar);\ndouble func_for_cov_NG_shear(double l1, double l2, int *ar);\ndouble func_for_cov_G_cl(double l, int *ar);\ndouble func_for_cov_NG_cl(double l1, double l2, int *ar);\ndouble func_for_cov_G_cl_gl(double l, int *ar);\ndouble func_for_cov_NG_cl_gl(double l1, double l2, int *ar);\ndouble func_for_cov_G_cl_shear(double l, int *ar);\ndouble func_for_cov_NG_cl_shear(double l1, double l2, int *ar);\ndouble func_for_cov_G_gl(double l, int *ar);\ndouble func_for_cov_NG_gl(double l1, double l2, int *ar);\ndouble func_for_cov_G_gl_shear(double l, int *ar);\ndouble func_for_cov_NG_gl_shear(double l1, double l2, int *ar);\n\nvoid cov_G_shear_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm1, int pm2, double **cov_g_interp) {\n\n // pure noise term\n double N[Ntheta],res = 0.;\n int array[5];\n array[1] = z1; array[2] = z2; array[3] = z3; array[4] = z4;\n \n int i,j;\n for(i=0;i\n#include \n#include \n#include \n#include \n#include \n\n#include \"SIMULATION/TOOLS/sim.h\"\n#include \"PHY/TOOLS/tools_defs.h\"\n#include \"assertions.h\"\n\n// NEW code with lookup table for sin/cos based on delay profile (TO BE TESTED)\n\ndouble **cos_lut = NULL, * *sin_lut = NULL;\n\n\n//#if 1\n\n\n\nint init_freq_channel(channel_desc_t *desc, uint16_t nb_rb, int16_t n_samples)\n{\n double delta_f, freq; // 90 kHz spacing\n double delay;\n int16_t f;\n uint8_t l;\n\n if((n_samples & 1) == 0)\n {\n fprintf(stderr, \"freq_channel_init: n_samples has to be odd\\n\");\n return(-1);\n }\n\n cos_lut = (double **)malloc(n_samples * sizeof(double *));\n sin_lut = (double **)malloc(n_samples * sizeof(double *));\n delta_f = nb_rb * 180000 / (n_samples - 1);\n\n for(f = -(n_samples >> 1); f <= (n_samples >> 1); f++)\n {\n freq = delta_f * (double)f * 1e-6; // due to the fact that delays is in mus\n cos_lut[f + (n_samples >> 1)] = (double *)malloc((int)desc->nb_taps * sizeof(double));\n sin_lut[f + (n_samples >> 1)] = (double *)malloc((int)desc->nb_taps * sizeof(double));\n\n for(l = 0; l < (int)desc->nb_taps; l++)\n {\n if(desc->nb_taps == 1)\n {\n delay = desc->delays[l];\n }\n else\n {\n delay = desc->delays[l] + NB_SAMPLES_CHANNEL_OFFSET / desc->sampling_rate;\n }\n\n cos_lut[f + (n_samples >> 1)][l] = cos(2 * M_PI * freq * delay);\n sin_lut[f + (n_samples >> 1)][l] = sin(2 * M_PI * freq * delay);\n //printf(\"values cos:%d, sin:%d\\n\", cos_lut[f][l], sin_lut[f][l]);\n }\n }\n\n return(0);\n}\n\nint freq_channel(channel_desc_t *desc, uint16_t nb_rb, int16_t n_samples)\n{\n int16_t f, f2, d;\n uint8_t aarx, aatx, l;\n double *clut, *slut;\n static int freq_channel_init = 0;\n static int n_samples_max = 0;\n\n // do some error checking\n // n_samples has to be a odd number because we assume the spectrum is symmetric around the DC and includes the DC\n if((n_samples & 1) == 0)\n {\n fprintf(stderr, \"freq_channel: n_samples has to be odd\\n\");\n return(-1);\n }\n\n // printf(\"no of taps:%d,\",(int)desc->nb_taps);\n\n if(freq_channel_init == 0)\n {\n // we are initializing the lut for the largets possible n_samples=12*nb_rb+1\n // if called with n_samples<12*nb_rb+1, we decimate the lut\n n_samples_max = 12 * nb_rb + 1;\n\n if(init_freq_channel(desc, nb_rb, n_samples_max) == 0)\n {\n freq_channel_init = 1;\n }\n else\n {\n return(-1);\n }\n }\n\n d = (n_samples_max - 1) / (n_samples - 1);\n //printf(\"no_samples=%d, n_samples_max=%d, d=%d\\n\",n_samples,n_samples_max,d);\n start_meas(&desc->interp_freq);\n\n for(f = -n_samples_max / 2, f2 = -n_samples / 2; f < n_samples_max / 2; f += d, f2++)\n {\n clut = cos_lut[n_samples_max / 2 + f];\n slut = sin_lut[n_samples_max / 2 + f];\n\n for(aarx = 0; aarx < desc->nb_rx; aarx++)\n {\n for(aatx = 0; aatx < desc->nb_tx; aatx++)\n {\n desc->chF[aarx + (aatx * desc->nb_rx)][n_samples / 2 + f2].x = 0.0;\n desc->chF[aarx + (aatx * desc->nb_rx)][n_samples / 2 + f2].y = 0.0;\n\n for(l = 0; l < (int)desc->nb_taps; l++)\n {\n desc->chF[aarx + (aatx * desc->nb_rx)][n_samples / 2 + f2].x += (desc->a[l][aarx + (aatx * desc->nb_rx)].x * clut[l] +\n desc->a[l][aarx + (aatx * desc->nb_rx)].y * slut[l]);\n desc->chF[aarx + (aatx * desc->nb_rx)][n_samples / 2 + f2].y += (-desc->a[l][aarx + (aatx * desc->nb_rx)].x * slut[l] +\n desc->a[l][aarx + (aatx * desc->nb_rx)].y * clut[l]);\n }\n }\n }\n }\n\n stop_meas(&desc->interp_freq);\n return(0);\n}\n\ndouble compute_pbch_sinr(channel_desc_t *desc,\n channel_desc_t *desc_i1,\n channel_desc_t *desc_i2,\n double snr_dB, double snr_i1_dB,\n double snr_i2_dB,\n uint16_t nb_rb)\n{\n double avg_sinr, snr = pow(10.0, .1 * snr_dB), snr_i1 = pow(10.0, .1 * snr_i1_dB), snr_i2 = pow(10.0, .1 * snr_i2_dB);\n uint16_t f;\n uint8_t aarx, aatx;\n double S;\n struct complex S_i1;\n struct complex S_i2;\n avg_sinr = 0.0;\n\n // printf(\"nb_rb %d\\n\",nb_rb);\n for(f = (nb_rb - 6); f < (nb_rb + 6); f++)\n {\n S = 0.0;\n S_i1.x = 0.0;\n S_i1.y = 0.0;\n S_i2.x = 0.0;\n S_i2.y = 0.0;\n\n for(aarx = 0; aarx < desc->nb_rx; aarx++)\n {\n for(aatx = 0; aatx < desc->nb_tx; aatx++)\n {\n S += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc->chF[aarx + (aatx * desc->nb_rx)][f].x +\n desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc->chF[aarx + (aatx * desc->nb_rx)][f].y);\n // printf(\"%d %d chF[%d] => (%f,%f)\\n\",aarx,aatx,f,desc->chF[aarx+(aatx*desc->nb_rx)][f].x,desc->chF[aarx+(aatx*desc->nb_rx)][f].y);\n\n if(desc_i1)\n {\n S_i1.x += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].x +\n desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].y);\n S_i1.y += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].y -\n desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].x);\n }\n\n if(desc_i2)\n {\n S_i2.x += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].x +\n desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].y);\n S_i2.y += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].y -\n desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].x);\n }\n }\n }\n\n // printf(\"snr %f f %d : S %f, S_i1 %f, S_i2 %f\\n\",snr,f-nb_rb,S,snr_i1*sqrt(S_i1.x*S_i1.x + S_i1.y*S_i1.y),snr_i2*sqrt(S_i2.x*S_i2.x + S_i2.y*S_i2.y));\n avg_sinr += (snr * S / (desc->nb_tx + snr_i1 * sqrt(S_i1.x * S_i1.x + S_i1.y * S_i1.y) + snr_i2 * sqrt(S_i2.x * S_i2.x + S_i2.y * S_i2.y)));\n }\n\n // printf(\"avg_sinr %f (%f,%f,%f)\\n\",avg_sinr/12.0,snr,snr_i1,snr_i2);\n return(10 * log10(avg_sinr / 12.0));\n}\n\n\ndouble compute_sinr(channel_desc_t *desc,\n channel_desc_t *desc_i1,\n channel_desc_t *desc_i2,\n double snr_dB, double snr_i1_dB,\n double snr_i2_dB,\n uint16_t nb_rb)\n{\n double avg_sinr, snr = pow(10.0, .1 * snr_dB), snr_i1 = pow(10.0, .1 * snr_i1_dB), snr_i2 = pow(10.0, .1 * snr_i2_dB);\n uint16_t f;\n uint8_t aarx, aatx;\n double S;\n struct complex S_i1;\n struct complex S_i2;\n DevAssert(nb_rb > 0);\n avg_sinr = 0.0;\n\n // printf(\"nb_rb %d\\n\",nb_rb);\n for(f = 0; f < 2 * nb_rb; f++)\n {\n S = 0.0;\n S_i1.x = 0.0;\n S_i1.y = 0.0;\n S_i2.x = 0.0;\n S_i2.y = 0.0;\n\n for(aarx = 0; aarx < desc->nb_rx; aarx++)\n {\n for(aatx = 0; aatx < desc->nb_tx; aatx++)\n {\n S += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc->chF[aarx + (aatx * desc->nb_rx)][f].x +\n desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc->chF[aarx + (aatx * desc->nb_rx)][f].y);\n\n if(desc_i1)\n {\n S_i1.x += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].x +\n desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].y);\n S_i1.y += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].y -\n desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].x);\n }\n\n if(desc_i2)\n {\n S_i2.x += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].x +\n desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].y);\n S_i2.y += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].y -\n desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].x);\n }\n }\n }\n\n // printf(\"f %d : S %f, S_i1 %f, S_i2 %f\\n\",f-nb_rb,snr*S,snr_i1*sqrt(S_i1.x*S_i1.x + S_i1.y*S_i1.y),snr_i2*sqrt(S_i2.x*S_i2.x + S_i2.y*S_i2.y));\n avg_sinr += (snr * S / (desc->nb_tx + snr_i1 * sqrt(S_i1.x * S_i1.x + S_i1.y * S_i1.y) + snr_i2 * sqrt(S_i2.x * S_i2.x + S_i2.y * S_i2.y)));\n }\n\n // printf(\"avg_sinr %f (%f,%f,%f)\\n\",avg_sinr/12.0,snr,snr_i1,snr_i2);\n return(10 * log10(avg_sinr / (nb_rb * 2)));\n}\n\nint pbch_polynomial_degree = 6;\ndouble pbch_awgn_polynomial[7] = {-7.2926e-05, -2.8749e-03, -4.5064e-02, -3.5301e-01, -1.4655e+00, -3.6282e+00, -6.6907e+00};\n\nvoid load_pbch_desc(FILE *pbch_file_fd)\n{\n int i, ret;\n char dummy[25];\n ret = fscanf(pbch_file_fd, \"%d\", &pbch_polynomial_degree);\n\n if(ret < 0)\n {\n printf(\"fscanf failed: %s\\n\", strerror(errno));\n exit(EXIT_FAILURE);\n }\n\n if(pbch_polynomial_degree > 6)\n {\n printf(\"Illegal degree for pbch interpolation polynomial %d\\n\", pbch_polynomial_degree);\n exit(-1);\n }\n\n printf(\"PBCH polynomial : \");\n\n for(i = 0; i <= pbch_polynomial_degree; i++)\n {\n ret = fscanf(pbch_file_fd, \"%24s\", dummy);\n\n if(ret < 0)\n {\n printf(\"fscanf failed: %s\\n\", strerror(errno));\n exit(EXIT_FAILURE);\n }\n\n pbch_awgn_polynomial[i] = strtod(dummy, NULL);\n printf(\"%f \", pbch_awgn_polynomial[i]);\n }\n\n printf(\"\\n\");\n}\n\ndouble pbch_bler(double sinr)\n{\n int i;\n double log10_bler = pbch_awgn_polynomial[pbch_polynomial_degree];\n double sinrpow = sinr;\n double bler = 0.0;\n\n // printf(\"log10bler %f\\n\",log10_bler);\n if(sinr < -10.0)\n {\n bler = 1.0;\n }\n else if(sinr >= 0.0)\n {\n bler = 0.0;\n }\n else\n {\n for(i = 1; i <= pbch_polynomial_degree; i++)\n {\n // printf(\"sinrpow %f\\n\",sinrpow);\n log10_bler += (pbch_awgn_polynomial[pbch_polynomial_degree - i] * sinrpow);\n sinrpow *= sinr;\n // printf(\"log10bler %f\\n\",log10_bler);\n }\n\n bler = pow(10.0, log10_bler);\n }\n\n //printf (\"sinr %f bler %f\\n\",sinr,bler);\n return(bler);\n}\n\n", "meta": {"hexsha": "431960118ad431e208ee233f61398af5fac4fc5f", "size": 12298, "ext": "c", "lang": "C", "max_stars_repo_path": "openair1/SIMULATION/TOOLS/abstraction.c", "max_stars_repo_name": "AManTw/oai5g", "max_stars_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openair1/SIMULATION/TOOLS/abstraction.c", "max_issues_repo_name": "AManTw/oai5g", "max_issues_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openair1/SIMULATION/TOOLS/abstraction.c", "max_forks_repo_name": "AManTw/oai5g", "max_forks_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1705882353, "max_line_length": 163, "alphanum_fraction": 0.5158562368, "num_tokens": 4112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.42960640903460573}} {"text": "/* cheb/gsl_chebyshev.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_CHEBYSHEV_H__\n#define __GSL_CHEBYSHEV_H__\n\n#include \n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n\n/* data for a Chebyshev series over a given interval */\n\nstruct gsl_cheb_series_struct {\n\n double * c; /* coefficients */\n size_t order; /* order of expansion */\n double a; /* lower interval point */\n double b; /* upper interval point */\n\n /* The following exists (mostly) for the benefit\n * of the implementation. It is an effective single\n * precision order, for use in single precision\n * evaluation. Users can use it if they like, but\n * only they know how to calculate it, since it is\n * specific to the approximated function. By default,\n * order_sp = order.\n * It is used explicitly only by the gsl_cheb_eval_mode\n * functions, which are not meant for casual use.\n */\n size_t order_sp;\n\n /* Additional elements not used by specfunc */\n\n double * f; /* function evaluated at chebyschev points */\n};\ntypedef struct gsl_cheb_series_struct gsl_cheb_series;\n\n\n/* Calculate a Chebyshev series of specified order over\n * a specified interval, for a given function.\n * Return 0 on failure.\n */\ngsl_cheb_series * gsl_cheb_alloc(const size_t order);\n\n/* Free a Chebyshev series previously calculated with gsl_cheb_alloc().\n */\nvoid gsl_cheb_free(gsl_cheb_series * cs);\n\n/* Calculate a Chebyshev series using the storage provided.\n * Uses the interval (a,b) and the order with which it\n * was initially created.\n *\n */\nint gsl_cheb_init(gsl_cheb_series * cs, const gsl_function * func,\n const double a, const double b);\n\n\n/* Evaluate a Chebyshev series at a given point.\n * No errors can occur for a struct obtained from gsl_cheb_new().\n */\ndouble gsl_cheb_eval(const gsl_cheb_series * cs, const double x);\nint gsl_cheb_eval_err(const gsl_cheb_series * cs, const double x, \n double * result, double * abserr);\n\n\n/* Evaluate a Chebyshev series at a given point, to (at most) the given order.\n * No errors can occur for a struct obtained from gsl_cheb_new().\n */\ndouble gsl_cheb_eval_n(const gsl_cheb_series * cs, const size_t order, \n const double x);\nint gsl_cheb_eval_n_err(const gsl_cheb_series * cs, const size_t order, \n const double x, double * result, double * abserr);\n\n\n/* Evaluate a Chebyshev series at a given point, using the default\n * order for double precision mode(s) and the single precision\n * order for other modes.\n * No errors can occur for a struct obtained from gsl_cheb_new().\n */\ndouble gsl_cheb_eval_mode(const gsl_cheb_series * cs, double x, gsl_mode_t mode);\nint gsl_cheb_eval_mode_e(const gsl_cheb_series * cs, const double x, gsl_mode_t mode, double * result, double * abserr);\n\n\n\n/* Compute the derivative of a Chebyshev series.\n */\nint gsl_cheb_calc_deriv(gsl_cheb_series * deriv, const gsl_cheb_series * cs);\n\n/* Compute the integral of a Chebyshev series. The\n * integral is fixed by the condition that it equals zero at\n * the left end-point, ie it is precisely\n * Integrate[cs(t; a,b), {t, a, x}]\n */\nint gsl_cheb_calc_integ(gsl_cheb_series * integ, const gsl_cheb_series * cs);\n\n\n\n\n__END_DECLS\n\n#endif /* __GSL_CHEBYSHEV_H__ */\n", "meta": {"hexsha": "65dbc2e923f79aa256fece6c580e918e3bce8630", "size": 4223, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cheb/gsl_chebyshev.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cheb/gsl_chebyshev.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/cheb/gsl_chebyshev.h", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 32.7364341085, "max_line_length": 120, "alphanum_fraction": 0.7156050201, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.42953418931956067}} {"text": "/*\n # This file is part of the Astrometry.net suite.\n # Licensed under a 3-clause BSD style license - see LICENSE\n */\n\n/**\n Runs the verification procedure in stand-alone mode.\n */\n#include \"os-features.h\"\n#include \"matchfile.h\"\n#include \"matchobj.h\"\n#include \"index.h\"\n#include \"xylist.h\"\n#include \"rdlist.h\"\n#include \"log.h\"\n#include \"errors.h\"\n#include \"mathutil.h\"\n\n#include \"verify.h\"\n#include \"verify2.h\"\n\n#define SIGN(x) (((x) >= 0) ? (1) : (-1))\n\nstatic const char* OPTIONS = \"hvi:m:f:r:p\";\n\nstatic void print_help(const char* progname) {\n printf(\"Usage: %s\\n\"\n \" -m \\n\"\n \" -f \\n\"\n \" ( -i \\n\"\n \" OR -r \\n\"\n \" )\\n\"\n \" [-v]: verbose\\n\"\n \"\\n\", progname);\n}\n\nint Npaths = 0;\n\nstatic void explore_path(il** reflists, dl** problists, int i, int NT, int NR,\n int* theta, double* logprobs, \n anbool* refused, int mu,\n double distractor, double logbg) {\n int j;\n double logprob;\n FILE* f = stderr;\n double logd = log(distractor + (1.0-distractor)*mu / (double)NR) + logbg;\n\n if (i == NT) {\n\n /*\n fprintf(f, \"allpaths.append(array([\");\n for (j=0; j\n#include \n#include \"gslutils.h\"\n\n\nvoid find_cd_correction(const double* testxy, const double* sigma2s, int NT,\n const int* theta, const double* refxy, int NR,\n const double* crpix) {\n gsl_matrix *A;\n gsl_vector *B1, *B2, *X1, *X2;\n int M, N;\n int mu;\n int i;\n\n /*\n solve min(|B - A*X|^2) for X\n\n B: (refxy - crpix)_{x,y} / sigma\n X: CD matrix elements (a,b) and (c,d)\n A: (testxy - crpix)_{x,y} / sigma\n */\n\n mu = 0;\n for (i=0; i= 0)\n mu++;\n // number of samples\n M = mu;\n // number of coefficients\n N = 2;\n\n A = gsl_matrix_alloc(M, N);\n B1 = gsl_vector_alloc(M);\n B2 = gsl_vector_alloc(M);\n\n mu = 0;\n for (i=0; iwcstan.imagew = fieldW;\n mo->wcstan.imageh = fieldH;\n\n fieldxy = xylist_read_field(xyls, NULL);\n if (!fieldxy) {\n ERROR(\"Failed to read a field from xylist %s\", xyfn);\n exit(-1);\n }\n\n if (indexfn) {\n index = index_load(indexfn, 0);\n if (!index) {\n ERROR(\"Failed to open index %s\", indexfn);\n exit(-1);\n }\n\n pix2 += square(index->meta.index_jitter / mo->scale);\n\n } else {\n double indexjitter;\n\n rdls = rdlist_open(rdfn);\n if (!rdls) {\n ERROR(\"Failed to open rdlist %s\", rdfn);\n exit(-1);\n }\n\n // HACK\n indexjitter = 1.0; // arcsec.\n pix2 += square(indexjitter / mo->scale);\n }\n\n logmsg(\"Pixel jitter: %g pix\\n\", sqrt(pix2));\n\n vf = verify_field_preprocess(fieldxy);\n\n if (index) {\n mo->logodds = 0.0;\n mo->dimquads = index_get_quad_dim(index);\n verify_hit(index->starkd, index->meta.cutnside,\n mo, NULL, vf,\n pix2, distractors, fieldW, fieldH,\n logbail, logkeep, logaccept, growvariance,\n fake);\n\n logodds = mo->logodds;\n\n index_close(index);\n\n } else {\n int cutnside;\n int cutnsweeps;\n int indexid;\n int uni_nw, uni_nh;\n int* perm;\n double* testxy;\n double* refxy;\n int i, j, NT, NR;\n double* sigma2s = NULL;\n rd_t* rd;\n double effA;\n double qc[2], Q2;\n\n // -get reference stars\n rd = rdlist_read_field(rdls, NULL);\n if (!rd) {\n ERROR(\"Failed to read rdls field\");\n exit(-1);\n }\n NR = rd_n(rd);\n refxy = malloc(2 * NR * sizeof(double));\n for (i=0; iwcstan), ra, dec, refxy + 2*i, refxy + 2*i + 1)) {\n ERROR(\"rdls point projects to wrong side of sphere!\");\n exit(-1);\n }\n }\n // -remove the ref star closest to each quad star.\n for (i=0; idimquads; i++) {\n double qxy[2];\n int besti = -1;\n double bestd2 = LARGE_VAL;\n if (!tan_xyzarr2pixelxy(&(mo->wcstan), mo->quadxyz + 3*i, qxy, qxy+1)) {\n ERROR(\"quad star projects to wrong side of sphere!\");\n exit(-1);\n }\n logmsg(\"Ref quad star %i is at (%.1f, %.1f)\\n\", i, qxy[0], qxy[1]);\n for (j=0; jindexid;\n if (index_get_missing_cut_params(indexid, &cutnside, &cutnsweeps, NULL, NULL, NULL)) {\n ERROR(\"Failed to get index cut parameters for index id %i\", indexid);\n exit(-1);\n }\n\n verify_get_quad_center(vf, mo, qc, &Q2);\n\n verify_apply_ror(refxy, NULL, &NR, cutnside, mo,\n vf, pix2, distractors, fieldW, fieldH,\n growvariance, fake,\n &testxy, &sigma2s, &NT, &perm, &effA, &uni_nw, &uni_nh);\n\n /*{\n double d = distractors;\n // Predicted optimal number of reference stars:\n int mmax = (int)round(exp(log(effA*(1-d)/(2*M_PI*pix2)) + d*log(d)/(1-d) + (M_PI*Q2 + 1)/effA * log(M_PI*Q2 / (M_PI*Q2 + effA))));\n logmsg(\"mmax = %i\\n\", mmax);\n logmsg(\"first term: %g\\n\", effA*(1-d)/(2*M_PI*pix2));\n logmsg(\"second term: %g\\n\", exp(d*log(d) / (1-d)));\n logmsg(\"third term: %g\\n\", exp((M_PI*Q2 + 1)/effA * log(M_PI*Q2 / (M_PI*Q2 + effA))));\n\n // Predicted number of reference stars to allow the\n // accept threshold to be reached.\n double t1 = d*log(d) + (1-d)*(log(effA*(1-d)/(2*M_PI*pix2)) + (M_PI*Q2 + 1)/effA * log(M_PI*Q2 / (M_PI*Q2 + effA)));\n for (i=1; i<1000000; i++) {\n double logM = i*t1 - i*(1-d)*log(i);\n if (logM > logkeep) {\n logmsg(\"m = %i: M = %g\\n\", i, exp(logM));\n break;\n }\n }\n //NR = MIN(NR, 2 * i + 10);\n //logmsg(\"Setting NR to %i\\n\", NR);\n }*/\n\t\t\n FILE* f = stderr;\n\n fprintf(f, \"distractor = %g\\nNR=%i\\nNT=%i\\n\", distractors, NR, NT);\n fprintf(f, \"W=%i\\nH=%i\\n\", (int)fieldW, (int)fieldH);\n fprintf(f, \"effA=%g\\n\", effA);\n fprintf(f, \"sig2=%g\\n\", pix2);\n\n fprintf(f, \"quadxy = array([\");\n for (i=0; idimquads; i++)\n fprintf(f, \"[%g,%g],\", mo->quadpix[2*i+0], mo->quadpix[2*i+1]);\n fprintf(f, \"])\\n\");\n\n fprintf(f, \"testxy = array([\");\n for (i=0; i may need all matches, not just nearest neighbour, to\n // do this correctly.\n double racc = 0, tacc = 0;\n int mu = 0;\n\n for (i=0; i\n#include \n#include \n\n\n//TODO Only one order is currently supported...\nenum BCSK_Q_ORDER { BcskWXYZ = 130 };\nenum BCSK_V_ORDER { BcskXYZ = 140 };\nenum BCSK_M_ORDER { BcskColMajor = 102 }; //TODO Add Row Major\n\n\n//copies first \"len\" entries of src to corresponding entries in dst\nint dDub ( double *dst , double *src , unsigned int len ) ;\n\n// Sets first \"len\" entries of array to 0;\nint dZeros ( double *array , unsigned int len ) ;\n\n// puts in dst the element-by-element sum of src1 and src2\nint dSum2 ( double *dst , double alpha , double *src1 , double beta , double *src2 , unsigned int len ) ;\n\n// sum up 3 arrays\nint dSum3 ( double *dst ,\n double a1 , double *src1 ,\n double a2 , double *src2 ,\n double a3 , double *src3 ,\n unsigned int len ) ;\n\n// sum up 4 arrays\nint dSum4 ( double *dst ,\n double a1 , double *src1 ,\n double a2 , double *src2 ,\n double a3 , double *src3 ,\n double a4 , double *src4 ,\n unsigned int len ) ;\n\n// sum up 5 arrays\nint dSum5 ( double *dst ,\n double a1 , double *src1 ,\n double a2 , double *src2 ,\n double a3 , double *src3 ,\n double a4 , double *src4 ,\n double a5 , double *src5 ,\n unsigned int len ) ;\n\n// Compute cross product between 2 3D vecs\n// c = a cross b ;\nint dCross ( double *c , double *a , double *b ) ;\n\n// Set the square matrix mat to the identity matrix\nint dEye ( unsigned int order , double scale , double *mat ) ;\n\n// Transpose square matrix\nint dSqTr ( int n , double *src , double *dst ) ;\n\n// Stores in quaternion c the hamilton product between quaternions a and b\nint dHamilton (const enum BCSK_Q_ORDER Order , double *c , double *a , double *b ) ;\n\n// Store in b the inverse of quaternion a\nint dQInv( const enum BCSK_Q_ORDER Order , double *b , double *a) ;\n\n//TODO vec arma_quat_between_vecs(const vec& a,const vec& b);\n\n/***********************************************\n* Compute angular velocity given the orientation quaternion\n* and its derivative.\n***********************************************/\n//int dQuatInv( const enum LIBQUAT_ORDER BOrder , double *v , const enum LIBQUAT_ORDER AOrder , double *a) ;\nint dQD2Vel ( const enum BCSK_V_ORDER v_order ,\n const enum BCSK_Q_ORDER q_order ,\n double *v ,\n double *q ,\n double *dqdt );\n\n/*TODO**********************************************\n* Compute angular accelleration given the orientation quaternion\n* and its derivatives.\n***********************************************/\n/*vec arma_quat_d_to_acc(const vec& q0,const vec& q1,const vec& q2){\n\tvec w1(4);\n\tw1 = 2 * arma_quat_hamilton( q2-arma_quat_hamilton(arma_quat_hamilton(q1,arma_quat_inv(q0)),q1) , arma_quat_inv(q0) );\n\treturn(w1.subvec(1,3));\n}\n*/\n\n/***********************************************\n* Rotate vector v by rotation q.\n* This formula should be faster than:\n* v_new = q * v * q^-1\n***********************************************/\n//TODO vec arma_quat_rot ( const vec& q,const vec& v ) ;\n\n/***********************************************\n* Return matrix M from vector v s.t. for any x\n* M*x = cross(v,x)\n***********************************************/\nint dCrossMat ( const enum BCSK_M_ORDER MOrder , double *M , const double *v ) ;\n\n/***********************************************\n* Applyes Rodriguez formula to convert quaternion q\n* to rotation matrix R\n***********************************************/\nint dQ2R ( const enum BCSK_M_ORDER Order , const enum BCSK_Q_ORDER , double *R , double *q) ;\n\n\n/***********************************************\n* Conversion from rotation matrix R to quaternion q\n***********************************************/\nint dR2Q ( const enum BCSK_M_ORDER ROrder , const enum BCSK_Q_ORDER QOrder , double *R , double *q) ;\n\n\n/* Saturate each elements of an array between -abs(sat_level) and +abs(sat_level)\n *\n * _______ _ +abs(sat_level)\n * | /\n * _______|/_______y _ 0\n * /\n * ______/| _ -abs(sat_level)\n * x\n *\n * x: input value\n * y: output value\n *\n * N.B. \n */\n\nint dSat( double *src , double *dst , double sat_level , int len ) ;\n\n\n\n// normalize vector X\nint dNormalise ( const int N , double *X ); \n\n// compute rotation quaternion between v1 and v2\nint dQbetVs ( double *Q , double *v1 , double *v2);\n\n#endif\n\n", "meta": {"hexsha": "a4c25e78baa3a06583abb543139fc345ba6cfeb1", "size": 4593, "ext": "h", "lang": "C", "max_stars_repo_path": "src/bcsk.h", "max_stars_repo_name": "fmr42/bcsk", "max_stars_repo_head_hexsha": "4f4b15addba20f2cce04ab42ce97c68472f41340", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bcsk.h", "max_issues_repo_name": "fmr42/bcsk", "max_issues_repo_head_hexsha": "4f4b15addba20f2cce04ab42ce97c68472f41340", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bcsk.h", "max_forks_repo_name": "fmr42/bcsk", "max_forks_repo_head_hexsha": "4f4b15addba20f2cce04ab42ce97c68472f41340", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5744680851, "max_line_length": 119, "alphanum_fraction": 0.5475723928, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.42939825716643687}} {"text": "// Copyright (c) 2021. Pfizer Inc. All rights reserved.\n#define PY_SSIZE_T_CLEAN\n#include \"Python.h\"\n#include \"numpy/arrayobject.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\nPyObject * moving_median(PyObject *NPY_UNUSED(self), PyObject *args){\n PyObject *x_;\n long wlen;\n\n if (!PyArg_ParseTuple(args, \"Ol:moving_median\", &x_, &wlen)) return NULL;\n\n PyArrayObject *data = (PyArrayObject *)PyArray_FromAny(\n x_, PyArray_DescrFromType(NPY_DOUBLE), 1, 0,\n NPY_ARRAY_ENSUREARRAY | NPY_ARRAY_CARRAY_RO, NULL\n );\n if (!data) return NULL;\n\n // get the number of dimensions, and the shape\n int ndim = PyArray_NDIM(data);\n npy_intp *ddims = PyArray_DIMS(data);\n\n // data pointers\n double *dptr = (double *)PyArray_DATA(data);\n \n gsl_movstat_workspace *w = gsl_movstat_alloc2(0, (size_t)wlen - 1);\n\n gsl_vector x;\n x.size = ddims[ndim-1];\n x.stride = 1;\n // x.data = dptr; // set this later\n x.block = NULL;\n x.owner = 0;\n\n // RETURN\n PyArrayObject *rmed = (PyArrayObject *)PyArray_EMPTY(ndim, ddims, NPY_DOUBLE, 0);\n if (!rmed){\n Py_XDECREF(data);\n Py_XDECREF(rmed);\n gsl_movstat_free(w);\n return NULL;\n }\n double *rptr = (double *)PyArray_DATA(rmed);\n\n gsl_vector xmean;\n xmean.size = ddims[ndim-1];\n xmean.stride = 1;\n // xmean.data = rptr; // set this later\n xmean.block = NULL;\n xmean.owner = 0;\n\n // for iterating over the data\n long stride = ddims[ndim - 1];\n int nrepeats = PyArray_SIZE(data) / stride;\n\n for (int i = 0; i < nrepeats; ++i){\n x.data = dptr;\n xmean.data = rptr;\n\n gsl_movstat_median(GSL_MOVSTAT_END_PADZERO, &x, &xmean, w);\n\n dptr += stride;\n rptr += stride;\n }\n gsl_movstat_free(w);\n Py_XDECREF(data);\n\n return (PyObject *)rmed;\n}\n\nstatic struct PyMethodDef methods[] = {\n {\"moving_median\", moving_median, 1, NULL}, // last is the docstring\n {NULL, NULL, 0, NULL} /* sentinel */\n};\n\nstatic struct PyModuleDef moduledef = {\n PyModuleDef_HEAD_INIT,\n \"moving_median\",\n NULL,\n -1,\n methods,\n NULL,\n NULL,\n NULL,\n NULL\n};\n\n/* Initialization function for the module */\nPyMODINIT_FUNC PyInit_moving_median(void)\n{\n PyObject *m;\n m = PyModule_Create(&moduledef);\n if (m == NULL) {\n return NULL;\n }\n\n /* Import the array object */\n import_array();\n\n /* XXXX Add constants here */\n\n return m;\n}\n", "meta": {"hexsha": "4be4206c98e89dadfbfeea433601c3d9eda5d198", "size": 2607, "ext": "c", "lang": "C", "max_stars_repo_path": "src/skdh/utility/_extensions/moving_median.c", "max_stars_repo_name": "PfizerRD/scikit-digital-health", "max_stars_repo_head_hexsha": "f834a82d750d9e3cdd35f4f5692a0a388210b821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T20:56:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:56:49.000Z", "max_issues_repo_path": "src/skdh/utility/_extensions/moving_median.c", "max_issues_repo_name": "PfizerRD/scikit-digital-health", "max_issues_repo_head_hexsha": "f834a82d750d9e3cdd35f4f5692a0a388210b821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/skdh/utility/_extensions/moving_median.c", "max_forks_repo_name": "PfizerRD/scikit-digital-health", "max_forks_repo_head_hexsha": "f834a82d750d9e3cdd35f4f5692a0a388210b821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2767857143, "max_line_length": 85, "alphanum_fraction": 0.60951285, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.42888710612716163}} {"text": "/* integration/romberg.c\n * \n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* the code in this module performs Romberg integration */\n\n#include \n#include \n#include \n#include \n#include \n\n#define ROMBERG_PRINT_ROW(i, r) \\\n do { \\\n size_t jj; \\\n fprintf(stderr, \"R[%zu] = \", i); \\\n for (jj = 0; jj <= i; ++jj) \\\n fprintf(stderr, \"%.8e \", r[jj]); \\\n fprintf(stderr, \"\\n\"); \\\n } while (0)\n\ngsl_integration_romberg_workspace *\ngsl_integration_romberg_alloc(const size_t n)\n{\n gsl_integration_romberg_workspace *w;\n\n /* check inputs */\n if (n < 1)\n {\n GSL_ERROR_VAL (\"workspace size n must be at least 1\", GSL_EDOM, 0);\n }\n\n w = calloc(1, sizeof(gsl_integration_romberg_workspace));\n if (w == NULL)\n {\n GSL_ERROR_VAL (\"unable to allocate workspace\", GSL_ENOMEM, 0);\n }\n\n /* ceiling on n, since the number of points is 2^n + 1 */\n w->n = GSL_MIN(n, 30);\n\n w->work1 = malloc(w->n * sizeof(double));\n if (w->work1 == NULL)\n {\n gsl_integration_romberg_free(w);\n GSL_ERROR_VAL (\"unable to allocate previous row\", GSL_ENOMEM, 0);\n }\n\n w->work2 = malloc(w->n * sizeof(double));\n if (w->work2 == NULL)\n {\n gsl_integration_romberg_free(w);\n GSL_ERROR_VAL (\"unable to allocate current row\", GSL_ENOMEM, 0);\n }\n\n return w;\n}\n\nvoid\ngsl_integration_romberg_free(gsl_integration_romberg_workspace * w)\n{\n if (w->work1)\n free(w->work1);\n\n if (w->work2)\n free(w->work2);\n\n free(w);\n}\n\nint\ngsl_integration_romberg(const gsl_function * f, const double a, const double b,\n const double epsabs, const double epsrel, double * result,\n size_t * neval, gsl_integration_romberg_workspace * w)\n{\n if (epsabs < 0.0)\n {\n GSL_ERROR(\"epsabs must be non-negative\", GSL_EDOM);\n }\n else if (epsrel < 0.0)\n {\n GSL_ERROR(\"epsrel must be non-negative\", GSL_EDOM);\n }\n else\n {\n const size_t n = w->n;\n double *Rp = &(w->work1[0]); /* previous row */\n double *Rc = &(w->work2[0]); /* current row */\n double *Rtmp;\n double h = 0.5 * (b - a); /* step size */\n size_t i;\n\n /* R(0,0) */\n Rp[0] = h * (GSL_FN_EVAL(f, a) + GSL_FN_EVAL(f, b));\n *neval = 2;\n\n /*ROMBERG_PRINT_ROW((size_t) 0, Rp);*/\n\n for (i = 1; i < n; ++i)\n {\n size_t j;\n double sum = 0.0;\n double err;\n double four_j; /* 4^j */\n size_t two_i = 1 << i; /* 2^i */\n\n for (j = 1; j < two_i; j += 2)\n {\n sum += GSL_FN_EVAL(f, a + j * h);\n ++(*neval);\n }\n\n /* R(i,0) */\n Rc[0] = sum * h + 0.5 * Rp[0];\n\n four_j = 4.0;\n for (j = 1; j <= i; ++j)\n {\n Rc[j] = (four_j * Rc[j - 1] - Rp[j - 1]) / (four_j - 1.0);\n four_j *= 4.0;\n }\n\n /*ROMBERG_PRINT_ROW(i, Rc);*/\n\n /*\n * compute difference between current and previous result and\n * check for convergence\n */\n err = fabs(Rc[i] - Rp[i - 1]);\n if ((err < epsabs) || (err < epsrel * fabs(Rc[i])))\n {\n *result = Rc[i];\n return GSL_SUCCESS;\n }\n\n /* swap Rp and Rc */\n Rtmp = Rp;\n Rp = Rc;\n Rc = Rtmp;\n\n h *= 0.5;\n }\n\n /* did not converge - return best guess */\n *result = Rp[n - 1];\n\n return GSL_EMAXITER;\n }\n}\n", "meta": {"hexsha": "581d087ef654d67751520abe6db8f403b41e5b32", "size": 4268, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/integration/romberg.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/integration/romberg.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/integration/romberg.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 25.8666666667, "max_line_length": 82, "alphanum_fraction": 0.5487347704, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.42867417951673525}} {"text": "/* integration/qag.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"initialise.c\"\n#include \"set_initial.c\"\n#include \"qpsrt.c\"\n#include \"util.c\"\n\nstatic int\nqag (const gsl_function *f,\n const double a, const double b,\n const double epsabs, const double epsrel,\n const size_t limit,\n gsl_integration_workspace * workspace,\n double * result, double * abserr,\n gsl_integration_rule * q) ;\n\nint\ngsl_integration_qag (const gsl_function *f,\n\t\t double a, double b,\n\t\t double epsabs, double epsrel, size_t limit,\n\t\t int key,\n\t\t gsl_integration_workspace * workspace,\n\t\t double * result, double * abserr)\n{\n int status ;\n gsl_integration_rule * integration_rule = gsl_integration_qk15 ;\n\n if (key < GSL_INTEG_GAUSS15)\n {\n key = GSL_INTEG_GAUSS15 ;\n } \n else if (key > GSL_INTEG_GAUSS61) \n {\n key = GSL_INTEG_GAUSS61 ;\n }\n\n switch (key) \n {\n case GSL_INTEG_GAUSS15:\n integration_rule = gsl_integration_qk15 ;\n break ;\n case GSL_INTEG_GAUSS21:\n integration_rule = gsl_integration_qk21 ;\n break ;\n case GSL_INTEG_GAUSS31:\n integration_rule = gsl_integration_qk31 ; \n break ;\n case GSL_INTEG_GAUSS41:\n integration_rule = gsl_integration_qk41 ;\n break ; \n case GSL_INTEG_GAUSS51:\n integration_rule = gsl_integration_qk51 ;\n break ; \n case GSL_INTEG_GAUSS61:\n integration_rule = gsl_integration_qk61 ;\n break ; \n default:\n GSL_ERROR(\"value of key does specify a known integration rule\", \n\t\tGSL_EINVAL) ;\n }\n\n status = qag (f, a, b, epsabs, epsrel, limit,\n workspace, \n result, abserr, \n integration_rule) ;\n \n return status ;\n}\n\nstatic int\nqag (const gsl_function * f,\n const double a, const double b,\n const double epsabs, const double epsrel,\n const size_t limit,\n gsl_integration_workspace * workspace,\n double *result, double *abserr,\n gsl_integration_rule * q)\n{\n double area, errsum;\n double result0, abserr0, resabs0, resasc0;\n double tolerance;\n size_t iteration = 0;\n int roundoff_type1 = 0, roundoff_type2 = 0, error_type = 0;\n\n double round_off;\t\n\n /* Initialize results */\n\n initialise (workspace, a, b);\n\n *result = 0;\n *abserr = 0;\n\n if (limit > workspace->limit)\n {\n GSL_ERROR (\"iteration limit exceeds available workspace\", GSL_EINVAL) ;\n }\n\n if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28))\n {\n GSL_ERROR (\"tolerance cannot be acheived with given epsabs and epsrel\",\n\t\t GSL_EBADTOL);\n }\n\n /* perform the first integration */\n\n q (f, a, b, &result0, &abserr0, &resabs0, &resasc0);\n\n set_initial_result (workspace, result0, abserr0);\n\n /* Test on accuracy */\n\n tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (result0));\n\n /* need IEEE rounding here to match original quadpack behavior */\n\n round_off = GSL_COERCE_DBL (50 * GSL_DBL_EPSILON * resabs0);\n\n if (abserr0 <= round_off && abserr0 > tolerance)\n {\n *result = result0;\n *abserr = abserr0;\n\n GSL_ERROR (\"cannot reach tolerance because of roundoff error \"\n\t\t \"on first attempt\", GSL_EROUND);\n }\n else if ((abserr0 <= tolerance && abserr0 != resasc0) || abserr0 == 0.0)\n {\n *result = result0;\n *abserr = abserr0;\n\n return GSL_SUCCESS;\n }\n else if (limit == 1)\n {\n *result = result0;\n *abserr = abserr0;\n\n GSL_ERROR (\"a maximum of one iteration was insufficient\", GSL_EMAXITER);\n }\n\n area = result0;\n errsum = abserr0;\n\n iteration = 1;\n\n do\n {\n double a1, b1, a2, b2;\n double a_i, b_i, r_i, e_i;\n double area1 = 0, area2 = 0, area12 = 0;\n double error1 = 0, error2 = 0, error12 = 0;\n double resasc1, resasc2;\n double resabs1, resabs2;\n\n /* Bisect the subinterval with the largest error estimate */\n\n retrieve (workspace, &a_i, &b_i, &r_i, &e_i);\n\n a1 = a_i; \n b1 = 0.5 * (a_i + b_i);\n a2 = b1;\n b2 = b_i;\n\n q (f, a1, b1, &area1, &error1, &resabs1, &resasc1);\n q (f, a2, b2, &area2, &error2, &resabs2, &resasc2);\n\n area12 = area1 + area2;\n error12 = error1 + error2;\n\n errsum += (error12 - e_i);\n area += area12 - r_i;\n\n if (resasc1 != error1 && resasc2 != error2)\n\t{\n\t double delta = r_i - area12;\n\n\t if (fabs (delta) <= 1.0e-5 * fabs (area12) && error12 >= 0.99 * e_i)\n\t {\n\t roundoff_type1++;\n\t }\n\t if (iteration >= 10 && error12 > e_i)\n\t {\n\t roundoff_type2++;\n\t }\n\t}\n\n tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (area));\n\n if (errsum > tolerance)\n\t{\n\t if (roundoff_type1 >= 6 || roundoff_type2 >= 20)\n\t {\n\t error_type = 2;\t/* round off error */\n\t }\n\n\t /* set error flag in the case of bad integrand behaviour at\n\t a point of the integration range */\n\n\t if (subinterval_too_small (a1, a2, b2))\n\t {\n\t error_type = 3;\n\t }\n\t}\n\n update (workspace, a1, b1, area1, error1, a2, b2, area2, error2);\n\n retrieve (workspace, &a_i, &b_i, &r_i, &e_i);\n\n iteration++;\n\n }\n while (iteration < limit && !error_type && errsum > tolerance);\n\n *result = sum_results (workspace);\n *abserr = errsum;\n\n if (errsum <= tolerance)\n {\n return GSL_SUCCESS;\n }\n else if (error_type == 2)\n {\n GSL_ERROR (\"roundoff error prevents tolerance from being achieved\",\n\t\t GSL_EROUND);\n }\n else if (error_type == 3)\n {\n GSL_ERROR (\"bad integrand behavior found in the integration interval\",\n\t\t GSL_ESING);\n }\n else if (iteration == limit)\n {\n GSL_ERROR (\"maximum number of subdivisions reached\", GSL_EMAXITER);\n }\n else\n {\n GSL_ERROR (\"could not integrate function\", GSL_EFAILED);\n }\n}\n\n\n", "meta": {"hexsha": "64798de94e4c2a9cc3e81c315f5efbef5b1933f1", "size": 6593, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/integration/qag.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/integration/qag.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/integration/qag.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 24.7857142857, "max_line_length": 78, "alphanum_fraction": 0.6267253147, "num_tokens": 1917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.42829599648252653}} {"text": "/*System includes*/\n#include \n#include \n#include \n#include \n#include \n#include \n\n/*GSL includes*/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n/*User includes*/\n#include \"vbgmmmodule.h\"\n\n\nstatic PyObject *vbgmm_fit(PyObject *self, PyObject *args)\n{\n const char *szFileStub = NULL;\n int nKStart = 0, nLMin = 0, nMaxIter;\n unsigned long lSeed;\n double dEpsilon;\n int bCout = 0;\n int sts;\n\n if (!PyArg_ParseTuple(args, \"siikidi\", &szFileStub,&nKStart,&nLMin,&lSeed,&nMaxIter,&dEpsilon,&bCout))\n \treturn NULL;\n sts = driver(szFileStub,nKStart,nLMin,lSeed,nMaxIter,dEpsilon,bCout);\n return Py_BuildValue(\"i\", sts);\n}\n\nstatic PyMethodDef VbgmmMethods[] = {\n {\"fit\", vbgmm_fit, METH_VARARGS,\n \"Fit a variational Bayesian Gaussian mixture.\"},\n {NULL, NULL, 0, NULL} /* Sentinel */\n};\n\n\n/* Python 2.x code */\n\nPyMODINIT_FUNC\ninitvbgmm(void)\n{\n (void) Py_InitModule(\"vbgmm\", VbgmmMethods);\n}\n\n\nint driver(const char* szFileStub, int nKStart, int nLMin, unsigned long lSeed, int nMaxIter, double dEpsilon, int bCOut)\n{\n t_Params tParams;\n t_Data tData;\n gsl_rng *ptGSLRNG = NULL;\n const gsl_rng_type *ptGSLRNGType = NULL;\n int i = 0, k = 0, nD = 0, nN = 0;\n char szOFile[MAX_LINE_LENGTH];\n FILE *ofp = NULL;\n t_VBParams tVBParams;\n t_Cluster *ptBestCluster = NULL;\n gsl_matrix *ptTemp = NULL;\n gsl_matrix *ptTVar = NULL;\n /*initialise GSL RNG*/\n gsl_rng_env_setup();\n\n gsl_set_error_handler_off();\n \n ptGSLRNGType = gsl_rng_default;\n ptGSLRNG = gsl_rng_alloc(ptGSLRNGType);\n \n /*get command line params*/\n tParams.nKStart = nKStart;\n tParams.nLMin = nLMin;\n tParams.nMaxIter = nMaxIter;\n tParams.dEpsilon = dEpsilon;\n tParams.lSeed = lSeed;\n\n setParams(&tParams,szFileStub);\n\n /*read in input data*/\n readInputData(tParams.szInputFile, &tData);\n\n readPInputData(tParams.szPInputFile, &tData);\n\n nD = tData.nD;\n nN = tData.nN;\n\n ptTemp = gsl_matrix_alloc(tData.nT,nD);\n ptTVar = gsl_matrix_alloc(tData.nT,tData.nT);\n\n setVBParams(&tVBParams, &tData);\n \n ptBestCluster = (t_Cluster *) malloc(sizeof(t_Cluster));\n\n ptBestCluster->nN = nN;\n ptBestCluster->nK = tParams.nKStart;\n ptBestCluster->nD = nD;\n ptBestCluster->ptData = &tData;\n ptBestCluster->ptVBParams = &tVBParams;\n ptBestCluster->lSeed = tParams.lSeed;\n ptBestCluster->nMaxIter = tParams.nMaxIter;\n ptBestCluster->dEpsilon = tParams.dEpsilon;\n\n if(bCOut > 0){\n\tptBestCluster->szCOutFile = szFileStub;\n }\n else{\n\tptBestCluster->szCOutFile = NULL;\n }\n runRThreads((void *) &ptBestCluster);\n\n compressCluster(ptBestCluster);\n\n calcCovarMatrices(ptBestCluster,&tData);\n\n sprintf(szOFile,\"%sclustering_gt%d.csv\",tParams.szOutFileStub,tParams.nLMin);\n writeClusters(szOFile,ptBestCluster,&tData);\n\n sprintf(szOFile,\"%spca_means_gt%d.csv\",tParams.szOutFileStub,tParams.nLMin);\n writeMeans(szOFile,ptBestCluster);\n\n sprintf(szOFile,\"%smeans_gt%d.csv\",tParams.szOutFileStub,tParams.nLMin);\n writeTMeans(szOFile,ptBestCluster,&tData);\n\n for(k = 0; k < ptBestCluster->nK; k++){\n sprintf(szOFile,\"%spca_variances_gt%d_dim%d.csv\",tParams.szOutFileStub,tParams.nLMin,k);\n \n writeSquareMatrix(szOFile, ptBestCluster->aptSigma[k], nD);\n \n /*not entirely sure this is correct?*/\n gsl_blas_dgemm (CblasNoTrans,CblasNoTrans,1.0,tData.ptTMatrix,ptBestCluster->aptSigma[k],0.0,ptTemp);\n \n gsl_blas_dgemm (CblasNoTrans,CblasTrans,1.0,ptTemp,tData.ptTMatrix,0.0,ptTVar);\n\n sprintf(szOFile,\"%svariances_gt%d_dim%d.csv\",tParams.szOutFileStub,tParams.nLMin,k);\n\n writeSquareMatrix(szOFile, ptTVar, nD);\n }\n\n sprintf(szOFile,\"%sresponsibilities.csv\",tParams.szOutFileStub);\n\n ofp = fopen(szOFile,\"w\");\n if(ofp){ \n\n for(i = 0; i < nN; i++){\n for(k = 0; k < ptBestCluster->nK - 1; k++){\n\tfprintf(ofp,\"%f,\",ptBestCluster->aadZ[i][k]);\n }\n fprintf(ofp,\"%f\\n\",ptBestCluster->aadZ[i][ptBestCluster->nK - 1]);\n }\n\n fclose(ofp);\n }\n else{\n fprintf(stderr,\"Failed openining %s in main\\n\", szOFile);\n fflush(stderr);\n }\n\n sprintf(szOFile,\"%svbl.csv\",tParams.szOutFileStub);\n\n ofp = fopen(szOFile,\"w\");\n if(ofp){ \n fprintf(ofp,\"%d,%f,%d\\n\",ptBestCluster->nK,ptBestCluster->dVBL,ptBestCluster->nThread);\n\n fclose(ofp);\n }\n else{\n fprintf(stderr,\"Failed openining %s in main\\n\", szOFile);\n fflush(stderr);\n }\n\n /*free up memory in data object*/\n destroyData(&tData);\n\n /*free up best BIC clusters*/\n\n destroyCluster(ptBestCluster);\n free(ptBestCluster);\n\n destroyParams(&tParams);\n gsl_rng_free(ptGSLRNG);\n gsl_matrix_free(tVBParams.ptInvW0);\n gsl_matrix_free(ptTemp);\n gsl_matrix_free(ptTVar);\n\n return EXIT_SUCCESS;\n}\n\nvoid setParams(t_Params *ptParams, const char *szFileStub)\n{\n\n ptParams->szInputFile = (char *) malloc(MAX_LINE_LENGTH*sizeof(char));\n if(!ptParams->szInputFile)\n goto memoryError;\n\n ptParams->szPInputFile = (char *) malloc(MAX_LINE_LENGTH*sizeof(char));\n if(!ptParams->szInputFile)\n goto memoryError;\n\n sprintf(ptParams->szInputFile,\"%s%s%d.csv\",szFileStub,INPUT_FILE,ptParams->nLMin);\n\n sprintf(ptParams->szPInputFile,\"%s%s%d.csv\",szFileStub,PINPUT_FILE,ptParams->nLMin);\n\n ptParams->szOutFileStub = szFileStub;\n\n return;\n\n memoryError:\n fprintf(stderr, \"Failed allocating memory in setParams\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nvoid destroyParams(t_Params *ptParams)\n{\n\n free(ptParams->szInputFile);\n\n free(ptParams->szPInputFile);\n}\n\nvoid setVBParams(t_VBParams *ptVBParams, t_Data *ptData)\n{\n int i = 0, nD = ptData->nD;\n double adVar[nD], adMu[nD];\n\n ptVBParams->dBeta0 = DEF_BETA0;\n ptVBParams->dNu0 = (double) nD;\n ptVBParams->ptInvW0 = gsl_matrix_alloc(nD,nD);\n \n calcSampleVar(ptData,adVar, adMu);\n gsl_matrix_set_zero (ptVBParams->ptInvW0);\n \n for(i = 0; i < nD; i++){\n double dRD = adVar[i]*((double) nD);\n \n gsl_matrix_set(ptVBParams->ptInvW0,i,i,dRD);\n }\n\n ptVBParams->dLogWishartB = dLogWishartB(ptVBParams->ptInvW0, nD, ptVBParams->dNu0, TRUE);\n}\n\n\nvoid readInputData(const char *szFile, t_Data *ptData)\n{\n double **aadX = NULL;\n int i = 0, j = 0, nD = 0, nN = 0;\n char szLine[MAX_LINE_LENGTH];\n FILE* ifp = NULL;\n\n ifp = fopen(szFile, \"r\");\n\n if(ifp){\n char* szTok = NULL;\n char* pcError = NULL;\n\n if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL)\n goto formatError;\n\n szTok = strtok(szLine, DELIM);\n /*count dimensions*/\n while(strtok(NULL, DELIM) != NULL){\n \n nD++;\n }\n /*count data points*/\n while(fgets(szLine, MAX_LINE_LENGTH, ifp) != NULL){\n \tnN++;\n }\n fclose(ifp);\n\n /*reopen input file*/\n ifp = fopen(szFile, \"r\");\t\n\n if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL)\n goto formatError;\n\n\n /*allocate memory for dimension names*/\n ptData->aszDimNames = (char **) malloc(nD*sizeof(char*));\n if(!ptData->aszDimNames)\n goto memoryError;\n\n szTok = strtok(szLine, DELIM);\n /*read in dim names*/\n for(i = 0; i < nD; i++){\n szTok = strtok(NULL, DELIM);\n ptData->aszDimNames[i] = strdup(szTok);\n }\n\t\n /*allocate memory for data matrix*/\n aadX = (double **) malloc(nN*sizeof(double*));\n if(!aadX)\n goto memoryError;\n for(i = 0; i < nN; i++){\n aadX[i] = (double *) malloc(nD*sizeof(double));\n if(!aadX[i])\n\tgoto memoryError;\n }\n\n /*read in input data*/\n ptData->aszSampleNames = (char **) malloc(nN*sizeof(char*));\n if(!ptData->aszSampleNames)\n goto memoryError;\n\n for(i = 0; i < nN; i++){\n \n if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL)\n\tgoto formatError;\n\n szTok = strtok(szLine, DELIM);\n ptData->aszSampleNames[i] = strdup(szTok);\n for(j = 0; j < nD; j++){\n\tszTok = strtok(NULL, DELIM);\n\n\taadX[i][j] = strtod(szTok,&pcError);\n\n\tif(*pcError != '\\0'){\n\t goto formatError;\n\t}\n }\n }\n }\n else{\n fprintf(stderr, \"Failed to open abundance data file %s aborting\\n\", szFile);\n fflush(stderr);\n exit(EXIT_FAILURE);\n }\n\n ptData->nD = nD;\n ptData->nN = nN;\n ptData->aadX = aadX;\n return;\n\n memoryError:\n fprintf(stderr, \"Failed allocating memory in readInputData\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n\n formatError:\n fprintf(stderr, \"Incorrectly formatted abundance data file\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nvoid readPInputData(const char *szFile, t_Data *ptData)\n{\n int i = 0, j = 0, nD = ptData->nD, nT = 0;\n char szLine[MAX_LINE_LENGTH];\n FILE* ifp = NULL;\n \n ifp = fopen(szFile, \"r\");\n\n if(ifp){\n char* szTok = NULL;\n char* pcError = NULL;\n nT = 1;\n\n if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL)\n goto memoryError;\n\n szTok = strtok(szLine, DELIM);\n /*count dimensions*/\n while(strtok(NULL, DELIM) != NULL){ \n nT++;\n }\n \n ptData->ptTMatrix = gsl_matrix_alloc(nT,nD);\n \n fclose(ifp);\n\n /*reopen input file*/\n ifp = fopen(szFile, \"r\");\t\n \n for(i = 0; i < nD; i++){\n double dTemp = 0.0;\n\n if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL)\n\tgoto formatError;\n\n szTok = strtok(szLine, DELIM);\n \n dTemp = strtod(szTok,&pcError);\n if(*pcError != '\\0'){\n\tgoto formatError;\n }\n\n gsl_matrix_set(ptData->ptTMatrix,0,i,dTemp);\n \n for(j = 1; j < nT; j++){\n\tszTok = strtok(NULL, DELIM);\n\n\tdTemp = strtod(szTok,&pcError);\n\tif(*pcError != '\\0'){\n\t goto formatError;\n\t}\n\n\tgsl_matrix_set(ptData->ptTMatrix,j,i,dTemp);\n }\n }\n }\n else{\n fprintf(stderr, \"Failed to open abundance data file %s aborting\\n\", szFile);\n fflush(stderr);\n exit(EXIT_FAILURE);\n }\n\n ptData->nT = nT;\n return;\n\n formatError:\n fprintf(stderr, \"Incorrectly formatted abundance data file\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n\n memoryError:\n fprintf(stderr, \"Failed allocating memory in readPInputFile\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nvoid destroyData(t_Data *ptData)\n{\n int nN = ptData->nN, nD = ptData->nD;\n int i = 0;\n\n gsl_matrix_free(ptData->ptTMatrix);\n\n for(i = 0; i < nD; i++){\n free(ptData->aszDimNames[i]);\n }\n free(ptData->aszDimNames);\n\n for(i = 0; i < nN; i++){\n free(ptData->aadX[i]);\n }\n free(ptData->aadX);\n\n for(i = 0; i < nN; i++){\n free(ptData->aszSampleNames[i]);\n }\n free(ptData->aszSampleNames);\n\n return;\n\n}\n\nvoid destroyCluster(t_Cluster* ptCluster)\n{\n int i = 0, nN = ptCluster->nN, nKSize = ptCluster->nKSize;\n \n if(ptCluster->szCOutFile != NULL){\n\t free(ptCluster->szCOutFile);\n }\n\n free(ptCluster->anMaxZ);\n\n free(ptCluster->anW); \n\n for(i = 0; i < nN; i++){\n free(ptCluster->aadZ[i]); \n }\n free(ptCluster->aadZ);\n\n free(ptCluster->adLDet); \n free(ptCluster->adPi); \n free(ptCluster->adBeta);\n free(ptCluster->adNu);\n\n for(i = 0; i < nKSize; i++){\n free(ptCluster->aadMu[i]);\n free(ptCluster->aadM[i]);\n }\n\n free(ptCluster->aadMu);\n free(ptCluster->aadM);\n\n for(i = 0; i < nKSize ; i++){\n gsl_matrix_free(ptCluster->aptSigma[i]);\n gsl_matrix_free(ptCluster->aptCovar[i]);\n }\n free(ptCluster->aptSigma);\n free(ptCluster->aptCovar);\n return;\n}\n\nvoid allocateCluster(t_Cluster *ptCluster, int nN, int nK, int nD, t_Data *ptData, long lSeed, int nMaxIter, double dEpsilon, char *szCOutFile)\n{\n int i = 0, j = 0, k = 0;\n\n ptCluster->szCOutFile = szCOutFile;\n ptCluster->ptVBParams = NULL;\n ptCluster->lSeed = lSeed;\n ptCluster->nMaxIter = nMaxIter;\n ptCluster->dEpsilon = dEpsilon;\n ptCluster->ptData = ptData;\n\n ptCluster->nN = nN;\n ptCluster->nK = nK;\n ptCluster->nKSize = nK;\n ptCluster->nD = nD;\n\n ptCluster->dVBL = 0.0;\n\n ptCluster->anMaxZ = (int *) malloc(nN*sizeof(int)); /*destroyed*/\n if(!ptCluster->anMaxZ)\n goto memoryError;\n\n ptCluster->anW = (int *) malloc(nK*sizeof(int)); /*destroyed*/\n if(!ptCluster->anW)\n goto memoryError;\n\n for(i = 0; i < nN; i++){\n ptCluster->anMaxZ[i] = NOT_SET;\n }\n\n for(i = 0; i < nK; i++){\n ptCluster->anW[i] = 0;\n }\n\n ptCluster->aadZ = (double **) malloc(nN*sizeof(double *)); /*destroyed*/\n if(!ptCluster->aadZ)\n goto memoryError;\n\n for(i = 0; i < nN; i++){\n ptCluster->aadZ[i] = (double *) malloc(nK*sizeof(double)); /*destroyed*/\n if(!ptCluster->aadZ[i])\n goto memoryError;\n\n for(j = 0; j < nK; j++){\n ptCluster->aadZ[i][j] = 0.0;\n }\n }\n\n ptCluster->adLDet = (double *) malloc(nK*sizeof(double)); /*all*/\n ptCluster->adPi = (double *) malloc(nK*sizeof(double));\n ptCluster->adBeta = (double *) malloc(nK*sizeof(double));\n ptCluster->adNu = (double *) malloc(nK*sizeof(double)); /*destroyed*/\n\n if(!ptCluster->adLDet || !ptCluster->adPi)\n goto memoryError;\n\n if(!ptCluster->adBeta || !ptCluster->adNu)\n goto memoryError;\n\n for(k = 0; k < nK; k++){\n ptCluster->adLDet[k] = 0.0;\n ptCluster->adPi[k] = 0.0;\n ptCluster->adBeta[k] = 0.0;\n ptCluster->adNu[k] = 0.0;\n }\n\n ptCluster->aadMu = (double **) malloc(nK*sizeof(double *));\n if(!ptCluster->aadMu)\n goto memoryError;\n\n ptCluster->aadM = (double **) malloc(nK*sizeof(double *));\n if(!ptCluster->aadM)\n goto memoryError;\n\n for(i = 0; i < nK; i++){\n ptCluster->aadM[i] = (double*) malloc (nD*sizeof(double));\n if(!ptCluster->aadM[i])\n goto memoryError;\n\n ptCluster->aadMu[i] = (double*) malloc (nD*sizeof(double));\n if(!ptCluster->aadMu[i])\n goto memoryError;\n }\n\n ptCluster->aptSigma = (gsl_matrix **) malloc(nK*sizeof(gsl_matrix *));\n if(!ptCluster->aptSigma)\n goto memoryError;\n\n for(i = 0; i < nK ; i++){\n ptCluster->aptSigma[i] = (gsl_matrix*) gsl_matrix_alloc (nD, nD);\n }\n\n ptCluster->aptCovar = (gsl_matrix **) malloc(nK*sizeof(gsl_matrix *));\n if(!ptCluster->aptCovar)\n goto memoryError;\n\n for(i = 0; i < nK ; i++){\n ptCluster->aptCovar[i] = (gsl_matrix*) gsl_matrix_alloc (nD, nD);\n }\n\n return;\n \n memoryError:\n fprintf(stderr, \"Failed allocating memory in allocateCluster\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nvoid writeSquareMatrix(char*szFile, gsl_matrix *ptMatrix, int nD)\n{\n int i = 0, j = 0;\n FILE* ofp = fopen(szFile,\"w\");\n\n if(ofp){\n for(i = 0; i < nD; i++){\n for(j = 0; j < nD - 1; j++){\n\tfprintf(ofp,\"%f,\",gsl_matrix_get(ptMatrix,i,j));\n }\n fprintf(ofp,\"%f\\n\",gsl_matrix_get(ptMatrix,i,j));\n }\n }\n else{\n fprintf(stderr,\"Failed to open %s for writing in writeSquareMatrix\\n\", szFile);\n fflush(stderr);\n }\n}\n\ndouble decomposeMatrix(gsl_matrix *ptSigmaMatrix, int nD)\n{\n double dDet = 0.0;\n int status;\n int l = 0;\n\n status = gsl_linalg_cholesky_decomp(ptSigmaMatrix);\n\n if(status == GSL_EDOM){\n fprintf(stderr,\"Failed Cholesky decomposition in decomposeMatrix\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n }\n else{\n for(l = 0; l < nD; l++){\n double dT = gsl_matrix_get(ptSigmaMatrix,l,l);\n dDet += 2.0*log(dT);\n }\n gsl_linalg_cholesky_invert(ptSigmaMatrix);\n return dDet;\n }\n}\n\nvoid performMStep(t_Cluster *ptCluster, t_Data *ptData){\n int i = 0, j = 0, k = 0, l = 0, m = 0;\n int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;\n double **aadZ = ptCluster->aadZ,**aadX = ptData->aadX;\n double *adLDet = ptCluster->adLDet, *adPi = ptCluster->adPi;\n double **aadCovar = NULL, **aadInvWK = NULL;\n t_VBParams *ptVBParams = ptCluster->ptVBParams;\n\n gsl_matrix* ptSigmaMatrix = gsl_matrix_alloc(nD,nD);\n \n aadCovar = (double **) malloc(nD*sizeof(double*));\n if(!aadCovar) \n goto memoryError;\n \n for(i = 0; i < nD; i++){\n aadCovar[i] = (double *) malloc(nD*sizeof(double));\n if(!aadCovar[i])\n goto memoryError;\n }\n \n aadInvWK = (double **) malloc(nD*sizeof(double*));\n if(!aadInvWK)\n goto memoryError;\n \n for(i = 0; i < nD; i++){\n aadInvWK[i] = (double *) malloc(nD*sizeof(double));\n if(!aadInvWK[i])\n goto memoryError;\n }\n \n /*perform M step*/\n for(k = 0; k < nK; k++){ /*loop components*/\n double* adMu = ptCluster->aadMu[k];\n gsl_matrix *ptSigmaMatrix = ptCluster->aptSigma[k];\n double dF = 0.0;\n /*recompute mixture weights and means*/\n for(j = 0; j < nD; j++){\n adMu[j] = 0.0;\n for(l = 0; l < nD; l++){\n aadCovar[j][l] = 0.0;\n }\n }\n\n /* compute weight associated with component k*/\n adPi[k] = 0.0;\n for(i = 0; i < nN; i++){\n if(aadZ[i][k] > MIN_Z){\n adPi[k] += aadZ[i][k];\n for(j = 0; j < nD; j++){\n adMu[j] += aadZ[i][k]*aadX[i][j];\n }\n }\n }\n\n /*normalise means*/\n if(adPi[k] > MIN_PI){\n /*Equation 10.60*/\n ptCluster->adBeta[k] = ptVBParams->dBeta0 + adPi[k];\n\n for(j = 0; j < nD; j++){\n /*Equation 10.61*/\n ptCluster->aadM[k][j] = adMu[j]/ptCluster->adBeta[k];\n adMu[j] /= adPi[k];\n }\n\n ptCluster->adNu[k] = ptVBParams->dNu0 + adPi[k];\n\n\n /*calculate covariance matrices*/\n for(i = 0; i < nN; i++){\n if(aadZ[i][k] > MIN_Z){\n double adDiff[nD];\n\n for(j = 0; j < nD; j++){\n adDiff[j] = aadX[i][j] - adMu[j];\n }\n\n for(l = 0; l < nD; l++){\n for(m = 0; m <=l ; m++){\n aadCovar[l][m] += aadZ[i][k]*adDiff[l]*adDiff[m];\n } \n }\n }\n }\n\n for(l = 0; l < nD; l++){\n for(m = l + 1; m < nD; m++){\n aadCovar[l][m] = aadCovar[m][l];\n }\n }\n\n /*save sample covariances for later use*/\n for(l = 0; l < nD; l++){\n for(m = 0; m < nD; m++){\n double dC = aadCovar[l][m] / adPi[k];\n gsl_matrix_set(ptCluster->aptCovar[k],l,m,dC);\n }\n }\n\n /*Now perform equation 10.62*/\n dF = (ptVBParams->dBeta0*adPi[k])/ptCluster->adBeta[k];\n for(l = 0; l < nD; l++){\n for(m = 0; m <= l; m++){\n aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m) + aadCovar[l][m] + dF*adMu[l]*adMu[m];\n }\n }\n\n for(l = 0; l < nD; l++){\n for(m = 0; m <= l ; m++){\n aadCovar[l][m] /= adPi[k];\n gsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]);\n gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]);\n }\n }\n\n\n /*Implement Equation 10.65*/\n adLDet[k] = ((double) nD)*log(2.0);\n\n for(l = 0; l < nD; l++){\n double dX = 0.5*(ptCluster->adNu[k] - (double) l);\n adLDet[k] += gsl_sf_psi (dX);\n }\n\n adLDet[k] -= decomposeMatrix(ptSigmaMatrix,nD);\n }\n else{\n /*Equation 10.60*/\n adPi[k] = 0.0;\n\n ptCluster->adBeta[k] = ptVBParams->dBeta0;\n\n for(j = 0; j < nD; j++){\n /*Equation 10.61*/\n ptCluster->aadM[k][j] = 0.0;\n adMu[j] = 0.0;\n }\n\n ptCluster->adNu[k] = ptVBParams->dNu0;\n\n\n for(l = 0; l < nD; l++){\n for(m = 0; m <= l; m++){\n aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m);\n }\n }\n\n for(l = 0; l < nD; l++){\n for(m = 0; m <= l ; m++){\naadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m);\n }\n }\n\n for(l = 0; l < nD; l++){\n for(m = 0; m <= l ; m++){\ngsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]);\n gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]);\n }\n }\n\n /*Implement Equation 10.65*/\n adLDet[k] = ((double) nD)*log(2.0);\n\n for(l = 0; l < nD; l++){\n double dX = 0.5*(ptCluster->adNu[k] - (double) l);\n adLDet[k] += gsl_sf_psi (dX);\n }\n\n adLDet[k] -= decomposeMatrix(ptSigmaMatrix,nD);\n }\n }\n\n/*Normalise pi*/\n\n if(1){\n double dNP = 0.0;\n\n for(k = 0; k < nK; k++){\n dNP += adPi[k];\n }\n\n for(k = 0; k < nK; k++){\n adPi[k] /= dNP;\n }\n }\n\n /*free up memory*/\n for(i = 0; i < nD; i++){\n free(aadCovar[i]);\n free(aadInvWK[i]);\n }\n\n free(aadCovar);\n free(aadInvWK);\n \n return;\n \n memoryError:\n fprintf(stderr, \"Failed allocating memory in performMStep\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n \nvoid calcCovarMatrices(t_Cluster *ptCluster, t_Data *ptData)\n{\n int i = 0, j = 0, k = 0, l = 0, m = 0;\n int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;\n double **aadZ = ptCluster->aadZ,**aadX = ptData->aadX;\n double *adPi = ptCluster->adPi, **aadCovar = NULL;\n double dN = (double) nN;\n\n\n aadCovar = (double **) malloc(nD*sizeof(double*));\n if(!aadCovar)\n goto memoryError;\n\n for(i = 0; i < nD; i++){\n aadCovar[i] = (double *) malloc(nD*sizeof(double));\n if(!aadCovar[i])\n goto memoryError;\n }\n\n\n for(k = 0; k < nK; k++){ /*loop components*/ \n double* adMu = ptCluster->aadMu[k];\n gsl_matrix *ptSigmaMatrix = ptCluster->aptSigma[k];\n /*recompute mixture weights and means*/\n for(j = 0; j < nD; j++){\n adMu[j] = 0.0;\n for(l = 0; l < nD; l++){\n\taadCovar[j][l] = 0.0;\n }\n /*prevents singularities*/\n aadCovar[j][j] = MIN_COVAR;\n }\n\n /* compute weight associated with component k*/\n adPi[k] = 0.0;\n for(i = 0; i < nN; i++){\n adPi[k] += aadZ[i][k];\n for(j = 0; j < nD; j++){\n\tadMu[j] += aadZ[i][k]*aadX[i][j];\n }\n }\n /*normalise means*/\n for(j = 0; j < nD; j++){\n adMu[j] /= adPi[k];\n }\n \n /*calculate covariance matrices*/\n for(i = 0; i < nN; i++){\n double adDiff[nD];\n \n for(j = 0; j < nD; j++){\n\tadDiff[j] = aadX[i][j] - adMu[j];\n }\n\n for(l = 0; l < nD; l++){\n\tfor(m = 0; m <=l ; m++){\n\t aadCovar[l][m] += aadZ[i][k]*adDiff[l]*adDiff[m];\n\t}\n } \n }\n \n for(l = 0; l < nD; l++){\n for(m = l + 1; m < nD; m++){\n\taadCovar[l][m] = aadCovar[m][l];\n }\n }\n\n for(l = 0; l < nD; l++){\n for(m = 0; m < nD; m++){\n\taadCovar[l][m] /= adPi[k];\n\tgsl_matrix_set(ptSigmaMatrix, l, m, aadCovar[l][m]);\n }\n }\n\n adPi[k] /= dN; /*normalise weights*/ \n }\n /*free up memory*/\n for(i = 0; i < nD; i++){\n free(aadCovar[i]);\n }\n\n //gsl_matrix_free(ptSigmaMatrix);\n free(aadCovar);\n\n return;\n memoryError:\n fprintf(stderr, \"Failed allocating memory in performMStep\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE); \n}\n\nvoid calcCovarMatricesVB(t_Cluster *ptCluster, t_Data *ptData){\n int i = 0, j = 0, k = 0, l = 0, m = 0;\n int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;\n double **aadZ = ptCluster->aadZ,**aadX = ptData->aadX;\n double *adLDet = ptCluster->adLDet, *adPi = ptCluster->adPi;\n double **aadCovar = NULL, **aadInvWK = NULL;\n t_VBParams *ptVBParams = ptCluster->ptVBParams;\n\n aadCovar = (double **) malloc(nD*sizeof(double*));\n if(!aadCovar)\n goto memoryError;\n\n for(i = 0; i < nD; i++){\n aadCovar[i] = (double *) malloc(nD*sizeof(double));\n if(!aadCovar[i])\n goto memoryError;\n }\n\n aadInvWK = (double **) malloc(nD*sizeof(double*));\n if(!aadInvWK)\n goto memoryError;\n\n for(i = 0; i < nD; i++){\n aadInvWK[i] = (double *) malloc(nD*sizeof(double));\n if(!aadInvWK[i])\n goto memoryError;\n }\n\n\n /*perform M step*/\n for(k = 0; k < nK; k++){ /*loop components*/ \n double* adMu = ptCluster->aadMu[k];\n gsl_matrix *ptSigmaMatrix = ptCluster->aptSigma[k];\n double dF = 0.0;\n\n /*recompute mixture weights and means*/\n for(j = 0; j < nD; j++){\n adMu[j] = 0.0;\n for(l = 0; l < nD; l++){\n\taadCovar[j][l] = 0.0;\n }\n }\n\n /* compute weight associated with component k*/\n adPi[k] = 0.0;\n for(i = 0; i < nN; i++){\n adPi[k] += aadZ[i][k];\n for(j = 0; j < nD; j++){\n\tadMu[j] += aadZ[i][k]*aadX[i][j];\n }\n }\n /*normalise means*/\n if(adPi[k] > MIN_PI){\n\n /*Equation 10.60*/\n ptCluster->adBeta[k] = ptVBParams->dBeta0 + adPi[k];\n\n for(j = 0; j < nD; j++){\n\t/*Equation 10.61*/\n\tptCluster->aadM[k][j] = adMu[j]/ptCluster->adBeta[k];\n\tadMu[j] /= adPi[k];\n }\n\n ptCluster->adNu[k] = ptVBParams->dNu0 + adPi[k];\n\n \n /*calculate covariance matrices*/\n for(i = 0; i < nN; i++){\n\tdouble adDiff[nD];\n \n\tfor(j = 0; j < nD; j++){\n\t adDiff[j] = aadX[i][j] - adMu[j];\n\t}\n\n\tfor(l = 0; l < nD; l++){\n\t for(m = 0; m <=l ; m++){\n\t aadCovar[l][m] += aadZ[i][k]*adDiff[l]*adDiff[m];\n\t }\n\t} \n }\n \n for(l = 0; l < nD; l++){\n\tfor(m = l + 1; m < nD; m++){\n\t aadCovar[l][m] = aadCovar[m][l];\n\t}\n }\n\n /*save sample covariances for later use*/\n for(l = 0; l < nD; l++){\n\tfor(m = 0; m < nD; m++){\n\t double dC = aadCovar[l][m] / adPi[k];\n\t gsl_matrix_set(ptCluster->aptCovar[k],l,m,dC);\n\t}\n }\n\n /*Now perform equation 10.62*/\n dF = (ptVBParams->dBeta0*adPi[k])/ptCluster->adBeta[k];\n for(l = 0; l < nD; l++){\n\tfor(m = 0; m <= l; m++){\n\t aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m) + aadCovar[l][m] + dF*adMu[l]*adMu[m];\n\t}\n }\n\n for(l = 0; l < nD; l++){\n\tfor(m = 0; m <= l ; m++){\n\t //aadCovar[l][m] /= adPi[k];\n\t gsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]);\n\t gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]);\n\t}\n }\n \n }\n else{\n /*Equation 10.60*/\n adPi[k] = 0.0;\n\n ptCluster->adBeta[k] = ptVBParams->dBeta0;\n\n for(j = 0; j < nD; j++){\n\t/*Equation 10.61*/\n\tptCluster->aadM[k][j] = 0.0;\n\tadMu[j] = 0.0;\n }\n\n ptCluster->adNu[k] = ptVBParams->dNu0;\n\n for(l = 0; l < nD; l++){\n\tfor(m = 0; m <= l; m++){\n\t aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m);\n\t}\n }\n\n for(l = 0; l < nD; l++){\n\tfor(m = 0; m <= l ; m++){\n\t //aadCovar[l][m] /= adPi[k];\n\t gsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]);\n\t gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]);\n\t}\n }\n \n /*Implement Equation 10.65*/\n adLDet[k] = ((double) nD)*log(2.0);\n\n for(l = 0; l < nD; l++){\n\tdouble dX = 0.5*(ptCluster->adNu[k] - (double) l);\n\tadLDet[k] += gsl_sf_psi (dX);\n }\n\n adLDet[k] -= decomposeMatrix(ptSigmaMatrix,nD);\n }\n }\n\n /*Normalise pi*/\n\n if(1){\n double dNP = 0.0;\n\n for(k = 0; k < nK; k++){\n dNP += adPi[k];\n }\n\n for(k = 0; k < nK; k++){\n adPi[k] /= dNP;\n }\n }\n\n /*free up memory*/\n for(i = 0; i < nD; i++){\n free(aadCovar[i]);\n free(aadInvWK[i]);\n }\n\n //gsl_matrix_free(ptSigmaMatrix);\n free(aadCovar);\n free(aadInvWK);\n return;\n memoryError:\n fprintf(stderr, \"Failed allocating memory in performMStep\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE); \n}\n\nvoid updateMeans(t_Cluster *ptCluster, t_Data *ptData){\n int i = 0, j = 0, k = 0;\n int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;\n int *anMaxZ = ptCluster->anMaxZ;\n int *anW = ptCluster->anW;\n double **aadX = ptData->aadX, **aadMu = ptCluster->aadMu;\n\n for(k = 0; k < nK; k++){\n \n for(j = 0; j < nD; j++){\n aadMu[k][j] = 0.0;\n }\n }\n\n for(i = 0; i < nN; i++){\n int nZ = anMaxZ[i];\n\n for(j = 0; j < nD; j++){\n aadMu[nZ][j] += aadX[i][j];\n }\n }\n\n for(k = 0; k < nK; k++){ /*loop components*/\n \n /*normalise means*/\n if(anW[k] > 0){\n for(j = 0; j < nD; j++){\n\taadMu[k][j] /= (double) anW[k];\n }\n }\n else{\n for(j = 0; j < nD; j++){\n\taadMu[k][j] = 0.0;\n }\n }\n }\n\n return;\n}\n\nvoid initRandom(gsl_rng *ptGSLRNG, t_Cluster *ptCluster, t_Data *ptData)\n{\n /*very simple initialisation assign each data point to random cluster*/\n int i = 0, k = 0;\n\n for(i = 0; i < ptData->nN; i++){\n int nIK = -1;\n\n for(k = 0; k < ptCluster->nK; k++){\n ptCluster->aadZ[i][k] = 0.0;\n }\n\n nIK = gsl_rng_uniform_int (ptGSLRNG, ptCluster->nK);\n\n ptCluster->aadZ[i][nIK] = 1.0;\n }\n \n performMStep(ptCluster, ptData);\n \n return;\n}\n\ndouble calcDist(double* adX, double *adMu, int nD)\n{\n double dDist = 0.0;\n int i = 0;\n \n for(i = 0; i < nD; i++){\n double dV = adX[i] - adMu[i];\n dDist += dV*dV;\n }\n \n return sqrt(dDist);\n}\n\nvoid initKMeans(gsl_rng *ptGSLRNG, t_Cluster *ptCluster, t_Data *ptData)\n{\n /*very simple initialisation assign each data point to random cluster*/\n int i = 0, k = 0, nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;\n double **aadMu = ptCluster->aadMu, **aadX = ptData->aadX; \n int *anMaxZ = ptCluster->anMaxZ, *anW = ptCluster->anW, nChange = nN;\n int nIter = 0, nMaxIter = ptCluster->nMaxIter;\n for(i = 0; i < nN; i++){\n int nIK = gsl_rng_uniform_int (ptGSLRNG, nK);\n\n ptCluster->anMaxZ[i] = nIK;\n anW[nIK]++;\n }\n \n updateMeans(ptCluster, ptData);\n \n while(nChange > 0 && nIter < nMaxIter){\n nChange = 0;\n /*reassign vectors*/\n for(i = 0; i < nN; i++){\n double dMinDist = DBL_MAX;\n int nMinK = NOT_SET;\n\n for(k = 0; k < nK; k++){\n\tdouble dDist = calcDist(aadX[i],aadMu[k],nD);\n\n\tif(dDist < dMinDist){\n\t nMinK = k;\n\t dMinDist = dDist;\n\t}\n }\n\n if(nMinK != anMaxZ[i]){\n\tint nCurr = anMaxZ[i];\n\tnChange++;\n\tanW[nCurr]--;\n\tanW[nMinK]++;\n\tanMaxZ[i] = nMinK;\n\n\t/*check for empty clusters*/\n\tif(anW[nCurr] == 0){\n\t int nRandI = gsl_rng_uniform_int (ptGSLRNG, nN);\n\t int nKI = 0;\n\t /*select at random from non empty clusters*/\n\n\t while(anW[anMaxZ[nRandI]] == 1){\n\t nRandI = gsl_rng_uniform_int (ptGSLRNG, nN);\n\t }\n\n\t nKI = anMaxZ[nRandI];\n\t anW[nKI]--;\n\t anW[nCurr] = 1;\n\t anMaxZ[nRandI] = nCurr;\n\t}\n }\n }\n //printf(\"%d %d\\n\",nIter,nChange);\n nIter++;\n updateMeans(ptCluster, ptData);\n }\n\n for(i = 0; i < nN; i++){\n for(k = 0; k < nK; k++){\n ptCluster->aadZ[i][k] = 0.0;\n }\n ptCluster->aadZ[i][anMaxZ[i]] = 1.0;\n }\n\n performMStep(ptCluster, ptData);\n return;\n}\n\n/*note assuming you are using inverse W matrix*/\ndouble dLogWishartB(gsl_matrix *ptInvW, int nD, double dNu, int bInv)\n{\n int i = 0;\n double dRet = 0.0, dT = 0.0;\n double dLogDet = 0.0, dD = (double) nD;\n gsl_matrix* ptTemp = gsl_matrix_alloc(nD,nD);\n\n gsl_matrix_memcpy(ptTemp, ptInvW);\n\n dLogDet = decomposeMatrix(ptTemp, nD);\n\n if(bInv == TRUE){\n dRet = 0.5*dNu*dLogDet;\n }\n else{\n dRet = -0.5*dNu*dLogDet;\n }\n \n dT = 0.5*dNu*dD*log(2.0);\n\n dT += 0.25*dD*(dD - 1.0)*log(M_PI);\n\n for(i = 0; i < nD; i++){\n dT += gsl_sf_lngamma(0.5*(dNu - (double) i));\n }\n\n gsl_matrix_free(ptTemp);\n\n return dRet - dT;\n}\n\ndouble dWishartExpectLogDet(gsl_matrix *ptW, double dNu, int nD)\n{\n int i = 0;\n double dRet = 0.0, dLogDet = 0.0, dD = (double) nD;\n gsl_matrix* ptTemp = gsl_matrix_alloc(nD,nD);\n\n gsl_matrix_memcpy(ptTemp, ptW);\n\n dLogDet = decomposeMatrix(ptW, nD);\n\n dRet = dD*log(2.0) + dLogDet;\n\n for(i = 0; i < nD; i++){\n dRet += gsl_sf_psi(0.5*(dNu - (double) i));\n }\n\n gsl_matrix_free(ptTemp);\n\n return dRet;\n}\n\n\ndouble dWishartEntropy(gsl_matrix *ptW, double dNu, int nD)\n{\n double dRet = -dLogWishartB(ptW, nD, dNu, FALSE);\n double dExpLogDet = dWishartExpectLogDet(ptW, dNu, nD);\n double dD = (double) nD;\n\n dRet -= 0.5 * (dNu - dD - 1.0)*dExpLogDet;\n\n dRet += 0.5*dNu*dD;\n\n return dRet;\n}\n\ndouble calcVBL(t_Cluster* ptCluster)\n{\n int i = 0, k = 0, l = 0, nN = ptCluster->nN;\n int nK = ptCluster->nK, nD = ptCluster->nD;\n double dBishop1 = 0.0, dBishop2 = 0.0, dBishop3 = 0.0, dBishop4 = 0.0, dBishop5 = 0.0; /*Bishop equations 10.71...*/\n gsl_matrix *ptRes = gsl_matrix_alloc(nD,nD);\n gsl_vector *ptDiff = gsl_vector_alloc(nD);\n gsl_vector *ptR = gsl_vector_alloc(nD);\n double dD = (double) nD;\n double** aadMu = ptCluster->aadMu, **aadM = ptCluster->aadM, **aadZ = ptCluster->aadZ;\n double* adBeta = ptCluster->adBeta, *adNu = ptCluster->adNu, *adLDet = ptCluster->adLDet, *adPi = ptCluster->adPi;\n double adNK[nK];\n double d2Pi = 2.0*M_PI, dBeta0 = ptCluster->ptVBParams->dBeta0, dNu0 = ptCluster->ptVBParams->dNu0, dRet = 0.0;\n double dK = 0.0;\n\n for(k = 0; k < nK; k++){\n adNK[k] = 0.0;\n }\n\n /*Equation 10.72*/\n for(i = 0; i < nN; i++){\n for(k = 0; k < nK; k++){\n adNK[k] += aadZ[i][k];\n if(adPi[k] > 0.0){\n\tdBishop2 += aadZ[i][k]*log(adPi[k]);\n }\n }\n }\n\n for(k = 0; k < nK; k++){\n if(adNK[k] > 0.0){\n dK++;\n }\n }\n\n /*Equation 10.71*/\n for(k = 0; k < nK; k++){\n if(adNK[k] > 0.0){\n double dT1 = 0.0, dT2 = 0.0, dF = 0.0;\n\n gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,ptCluster->aptCovar[k],ptCluster->aptSigma[k],0.0,ptRes);\n\n for(l = 0; l < nD; l++){\n\tdT1 += gsl_matrix_get(ptRes,l,l);\n }\n \n for(l = 0; l < nD; l++){\n\tgsl_vector_set(ptDiff,l,aadMu[k][l] - aadM[k][l]);\n }\n\n gsl_blas_dsymv (CblasLower, 1.0, ptCluster->aptSigma[k], ptDiff, 0.0, ptR);\n \n gsl_blas_ddot (ptDiff, ptR, &dT2);\n\n dF = adLDet[k] - adNu[k]*(dT1 + dT2) - dD*(log(d2Pi) + (1.0/adBeta[k]));\n\n dBishop1 += 0.5*adNK[k]*dF;\n }\n }\n\n /*Equation 10.74*/\n for(k = 0; k < nK; k++){\n if(adNK[k] > 0.0){\n double dT1 = 0.0, dT2 = 0.0, dF = 0.0;\n\n gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,ptCluster->ptVBParams->ptInvW0,ptCluster->aptSigma[k],0.0,ptRes);\n\n for(l = 0; l < nD; l++){\n\tdT1 += gsl_matrix_get(ptRes,l,l);\n }\n\n for(l = 0; l < nD; l++){\n\tgsl_vector_set(ptDiff,l,aadM[k][l]);\n }\n\n gsl_blas_dsymv (CblasLower, 1.0, ptCluster->aptSigma[k], ptDiff, 0.0, ptR);\n \n gsl_blas_ddot (ptDiff, ptR, &dT2);\n\n dF = dD*log(dBeta0/d2Pi) + adLDet[k] - ((dD*dBeta0)/adBeta[k]) - dBeta0*adNu[k]*dT2 - adNu[k]*dT1;\n\n dBishop3 += 0.5*(dF + (dNu0 - dD - 1.0)*adLDet[k]);\n }\n }\n\n dBishop3 += dK*ptCluster->ptVBParams->dLogWishartB;\n\n /*Equation 10.75*/\n for(i = 0; i < nN; i++){\n for(k = 0; k < nK; k++){\n if(aadZ[i][k] > 0.0){\n\tdBishop4 += aadZ[i][k]*log(aadZ[i][k]);\n }\n }\n }\n\n /*Equation 10.77*/\n for(k = 0; k < nK; k++){\n if(adNK[k] > 0.0){\n dBishop5 += 0.5*adLDet[k] + 0.5*dD*log(adBeta[k]/d2Pi) - 0.5*dD - dWishartExpectLogDet(ptCluster->aptSigma[k], adNu[k], nD);\n } \n }\n\n gsl_matrix_free(ptRes);\n gsl_vector_free(ptDiff);\n gsl_vector_free(ptR);\n \n dRet = dBishop1 + dBishop2 + dBishop3 - dBishop4 - dBishop5;\n\n return dRet;\n}\n\nvoid calcZ(t_Cluster* ptCluster, t_Data *ptData){\n double **aadX = ptData->aadX, **aadZ = ptCluster->aadZ;\n int i = 0, k = 0, l = 0;\n int nK = ptCluster->nK, nD = ptCluster->nD, nN = ptData->nN;\n gsl_vector *ptDiff = gsl_vector_alloc(nD);\n gsl_vector *ptRes = gsl_vector_alloc(nD);\n double adDist[nK], dD = (double) nD;\n double** aadM = ptCluster->aadM, *adPi = ptCluster->adPi;\n\n for(i = 0; i < nN; i++){\n double dMinDist = DBL_MAX;\n double dTotalZ = 0.0;\n double dNTotalZ = 0.0;\n\n for(k = 0; k < nK; k++){\n if(adPi[k] > 0.){\n /*set vector to data point*/\n for(l = 0; l < nD; l++){\n gsl_vector_set(ptDiff,l,aadX[i][l] - aadM[k][l]);\n }\n\n gsl_blas_dsymv (CblasLower, 1.0, ptCluster->aptSigma[k], ptDiff, 0.0, ptRes);\n\n gsl_blas_ddot (ptDiff, ptRes, &adDist[k]);\n\n adDist[k] *= ptCluster->adNu[k];\n\n adDist[k] -= ptCluster->adLDet[k];\n\n adDist[k] += dD/ptCluster->adBeta[k];\n\n if(adDist[k] < dMinDist){\n dMinDist = adDist[k];\n }\n }\n }\n\n for(k = 0; k < nK; k++){\n if(adPi[k] > 0.){\n aadZ[i][k] = adPi[k]*exp(-0.5*(adDist[k]-dMinDist));\n dTotalZ += aadZ[i][k];\n }\n else{\n aadZ[i][k] = 0.0;\n }\n } \n\n for(k = 0; k < nK; k++){\n double dF = aadZ[i][k] / dTotalZ;\n if(dF < MIN_Z){\n aadZ[i][k] = 0.0;\n }\n dNTotalZ += aadZ[i][k];\n }\n if(dNTotalZ > 0.){\n for(k = 0; k < nK; k++){\n aadZ[i][k] /= dNTotalZ;\n }\n }\n }\n\n gsl_vector_free(ptRes);\n gsl_vector_free(ptDiff);\n return;\n}\n\n\nvoid gmmTrainVB(t_Cluster *ptCluster, t_Data *ptData)\n{\n int i = 0, k = 0,nIter = 0;\n int nN = ptData->nN, nK = ptCluster->nK;\n /*change in log-likelihood*/\n double dLastVBL = 0.0, dDelta = DBL_MAX;\n double **aadZ = ptCluster->aadZ;\n int nMaxIter = ptCluster->nMaxIter;\n double dEpsilon = ptCluster->dEpsilon;\n FILE *ofp = NULL;\n\n if(ptCluster->szCOutFile){\n\tofp = fopen(ptCluster->szCOutFile,\"w\");\n\tif(!ofp){\n\t\tfprintf(stderr, \"Failed to open file %s in gmmTrainVB\\n\",ptCluster->szCOutFile);\n\t\tfflush(stderr);\n\t}\n }\n\n /*calculate data likelihood*/\n calcZ(ptCluster,ptData);\n ptCluster->dVBL = calcVBL(ptCluster);\n\n while(nIter < nMaxIter && dDelta > dEpsilon){\n \n /*update parameter estimates*/\n performMStep(ptCluster, ptData);\n\n /*calculate responsibilities*/\n calcZ(ptCluster,ptData);\n\n dLastVBL = ptCluster->dVBL;\n ptCluster->dVBL = calcVBL(ptCluster);\n dDelta = fabs(ptCluster->dVBL - dLastVBL);\n\n if(ofp){\n \tfprintf(ofp,\"%d,%f,%f,\",nIter, ptCluster->dVBL, dDelta);\n \tfor(k = 0; k < nK-1; k++){\n \t\tfprintf(ofp,\"%f,\",ptCluster->adPi[k]);\n \t}\n \tfprintf(ofp,\"%f\\n\",ptCluster->adPi[nK - 1]);\n\tfflush(ofp);\n }\n nIter++;\n }\n\n if(ofp){\n\tfclose(ofp);\n }\n\n /*assign to best clusters*/\n for(i = 0; i < nN; i++){\n double dMaxZ = aadZ[i][0];\n int nMaxK = 0;\n for(k = 1; k < nK; k++){\n if(aadZ[i][k] > dMaxZ){\n\tnMaxK = k;\n\tdMaxZ = aadZ[i][k];\n }\n }\n ptCluster->anMaxZ[i] = nMaxK;\n }\n\n return;\n}\n\nvoid writeClusters(char *szOutFile, t_Cluster *ptCluster, t_Data *ptData)\n{\n int nN = ptCluster->nN, i = 0;\n FILE* ofp = fopen(szOutFile,\"w\");\n\n if(ofp){\n for(i = 0; i < nN; i++){\n fprintf(ofp,\"%s,%d\\n\",ptData->aszSampleNames[i],ptCluster->anMaxZ[i]);\n }\n }\n else{\n fprintf(stderr,\"Failed to open %s for writing in writeClusters\\n\", szOutFile);\n fflush(stderr);\n }\n}\n\nvoid writeMeans(char *szOutFile, t_Cluster *ptCluster)\n{\n int nK = ptCluster->nK, nD = ptCluster->nD,i = 0, j = 0;\n FILE* ofp = fopen(szOutFile,\"w\");\n\n if(ofp){\n for(i = 0; i < nK; i++){\n for(j = 0; j < nD - 1; j++){\n\tfprintf(ofp,\"%f,\",ptCluster->aadMu[i][j]);\n }\n fprintf(ofp,\"%f\\n\",ptCluster->aadMu[i][nD - 1]);\n }\n }\n else{\n fprintf(stderr,\"Failed to open %s for writing in writeMeanss\\n\", szOutFile);\n fflush(stderr);\n }\n}\n\nvoid writeTMeans(char *szOutFile, t_Cluster *ptCluster, t_Data *ptData)\n{\n int nK = ptCluster->nK, nD = ptCluster->nD, nT = ptData->nT, i = 0, j = 0;\n FILE* ofp = fopen(szOutFile,\"w\");\n gsl_vector* ptVector = gsl_vector_alloc(nD);\n gsl_vector* ptTVector = gsl_vector_alloc(nT);\n \n if(ofp){\n for(i = 0; i < nK; i++){\n for(j = 0; j < nD; j++){\n\tgsl_vector_set(ptVector,j,ptCluster->aadMu[i][j]);\n }\n\n gsl_blas_dgemv (CblasNoTrans, 1.0,ptData->ptTMatrix,ptVector,0.0, ptTVector);\n\n for(j = 0; j < nT - 1; j++){\n\tfprintf(ofp,\"%f,\",gsl_vector_get(ptTVector,j));\n }\n fprintf(ofp,\"%f\\n\",gsl_vector_get(ptTVector,nD - 1));\n }\n }\n else{\n fprintf(stderr,\"Failed to open %s for writing in writeMeanss\\n\", szOutFile);\n fflush(stderr);\n }\n\n gsl_vector_free(ptVector);\n gsl_vector_free(ptTVector);\n}\n\n\n\nvoid* fitEM(void *pvCluster)\n{\n t_Cluster *ptCluster = (t_Cluster *) pvCluster;\n gsl_rng *ptGSLRNG = NULL;\n const gsl_rng_type *ptGSLRNGType = NULL;\n\n /*initialise GSL RNG*/\n ptGSLRNGType = gsl_rng_default;\n ptGSLRNG = gsl_rng_alloc(ptGSLRNGType);\n\n gsl_rng_set (ptGSLRNG, ptCluster->lSeed);\n\n initKMeans(ptGSLRNG, ptCluster, ptCluster->ptData);\n\n gmmTrainVB(ptCluster, ptCluster->ptData);\n\n gsl_rng_free(ptGSLRNG);\n\n return NULL;\n}\n\nvoid* runRThreads(void *pvpDCluster)\n{\n t_Cluster **pptDCluster = (t_Cluster **) pvpDCluster;\n t_Cluster *ptDCluster = (t_Cluster *) *pptDCluster;\n double dBestVBL = -DBL_MAX;\n t_Cluster** aptCluster = NULL;\n pthread_t atRestarts[N_RTHREADS]; /*run each restart on a separate thread*/\n int iret[N_RTHREADS];\n int r = 0, nBestR = -1;\n char *szCOutFile = NULL;\n aptCluster = (t_Cluster **) malloc(N_RTHREADS*sizeof(t_Cluster*));\n if(!aptCluster)\n goto memoryError;\n\n for(r = 0; r < N_RTHREADS; r++){\n if(ptDCluster->szCOutFile != NULL){\n\tszCOutFile = (char *) malloc(sizeof(char)*MAX_LINE_LENGTH);\n\tsprintf(szCOutFile,\"%sr%d.csv\",ptDCluster->szCOutFile,r);\n }\n\n aptCluster[r] = (t_Cluster *) malloc(sizeof(t_Cluster));\n\n allocateCluster(aptCluster[r],ptDCluster->nN,ptDCluster->nK,ptDCluster->nD,ptDCluster->ptData,ptDCluster->lSeed + r*R_PRIME,ptDCluster->nMaxIter,ptDCluster->dEpsilon,szCOutFile);\n aptCluster[r]->ptVBParams = ptDCluster->ptVBParams;\n aptCluster[r]->nThread = r;\n iret[r] = pthread_create(&atRestarts[r], NULL, fitEM, (void*) aptCluster[r]);\n }\n\n for(r = 0; r < N_RTHREADS; r++){\n pthread_join(atRestarts[r], NULL);\n }\n\n /*free up memory associated with input cluster*/\n free(ptDCluster);\n\n for(r = 0; r < N_RTHREADS; r++){\n if(aptCluster[r]->dVBL > dBestVBL){\n nBestR = r;\n dBestVBL = aptCluster[r]->dVBL;\n }\n }\n \n *pptDCluster = aptCluster[nBestR];\n for(r = 0; r < N_RTHREADS; r++){\n if(r != nBestR){\n destroyCluster(aptCluster[r]);\n free(aptCluster[r]);\n }\n }\n free(aptCluster);\n \n return NULL;\n memoryError:\n fprintf(stderr, \"Failed allocating memory in runRThreads\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nvoid calcSampleVar(t_Data *ptData,double *adVar, double *adMu)\n{\n double **aadX = ptData->aadX;\n int i = 0, n = 0;\n int nD = ptData->nD, nN = ptData->nN;\n /*sample means*/\n double dN = (double) nN;\n\n for(i = 0; i < nD; i++){\n adMu[i] = 0.0;\n adVar[i] = 0.0;\n }\n\n for(i = 0; i < nD; i++){\n for(n = 0; n < nN; n++){\n adMu[i] += aadX[n][i];\n adVar[i] += aadX[n][i]*aadX[n][i];\n }\n\n adMu[i] /= dN;\n\n adVar[i] = (adVar[i] - dN*adMu[i]*adMu[i])/(dN - 1.0);\n }\n\n return;\n}\n\nvoid compressCluster(t_Cluster *ptCluster)\n{\n int i = 0, k = 0, nNewK = 0, nN = ptCluster->nN;\n double **aadNewZ = NULL, dN = (double) nN;\n\n for(i = 0; i < ptCluster->nK; i++){\n if(ptCluster->adPi[i] > 0.0){\n nNewK++;\n }\n }\n\n aadNewZ = (double **) malloc(nN*sizeof(double *)); \n if(!aadNewZ)\n goto memoryError;\n\n for(i = 0; i < nN; i++){\n aadNewZ[i] = (double *) malloc(nNewK*sizeof(double));\n if(!aadNewZ[i])\n goto memoryError;\n }\n\n for(i = 0; i < nN; i++){\n int nC = 0;\n for(k = 0; k < ptCluster->nK; k++){\n if(ptCluster->adPi[k] > 0.0){\n\taadNewZ[i][nC] = ptCluster->aadZ[i][k];\n\tnC++;\n }\n }\n }\n\n for(i = 0; i < nN; i++){\n free(ptCluster->aadZ[i]);\n }\n free(ptCluster->aadZ);\n\n /*reset Z and K*/\n ptCluster->aadZ = aadNewZ;\n ptCluster->nK = nNewK;\n\n /*recalculate Pi*/\n for(k = 0; k < ptCluster->nK; k++){\n ptCluster->adPi[k] = 0.0;\n for(i = 0; i < nN; i++){\n ptCluster->adPi[k] += ptCluster->aadZ[i][k];\n }\n ptCluster->adPi[k] /= dN;\n }\n\n /*assign to best clusters*/\n for(i = 0; i < nN; i++){\n double dMaxZ = ptCluster->aadZ[i][0];\n int nMaxK = 0;\n for(k = 1; k < ptCluster->nK; k++){\n if(ptCluster->aadZ[i][k] > dMaxZ){\n\tnMaxK = k;\n\tdMaxZ = ptCluster->aadZ[i][k];\n }\n }\n ptCluster->anMaxZ[i] = nMaxK;\n }\n\n for(k = 0; k < ptCluster->nK; k++){\n ptCluster->anW[k] = 0;\n }\n\n for(i = 0; i < nN; i++){\n ptCluster->anW[ptCluster->anMaxZ[i]]++;\n }\n\n return;\n\n memoryError:\n fprintf(stderr, \"Failed allocating memory in main\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n", "meta": {"hexsha": "3d51521ba3ee4c8e6e01483681320967c81c7826", "size": 43851, "ext": "c", "lang": "C", "max_stars_repo_path": "c-concoct/vbgmmmodule.c", "max_stars_repo_name": "binnisb/CONCOCT", "max_stars_repo_head_hexsha": "9246dc947b24256c4eab1f7b081c7a21aebdd95b", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c-concoct/vbgmmmodule.c", "max_issues_repo_name": "binnisb/CONCOCT", "max_issues_repo_head_hexsha": "9246dc947b24256c4eab1f7b081c7a21aebdd95b", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c-concoct/vbgmmmodule.c", "max_forks_repo_name": "binnisb/CONCOCT", "max_forks_repo_head_hexsha": "9246dc947b24256c4eab1f7b081c7a21aebdd95b", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8579978237, "max_line_length": 182, "alphanum_fraction": 0.5686073294, "num_tokens": 15561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.42804382926010054}} {"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef utility_77d83a8d_bf54_4fbe_ab3c_b06d0be9e40e_h\r\n#define utility_77d83a8d_bf54_4fbe_ab3c_b06d0be9e40e_h\r\n\r\n#include \r\n#include \r\n\r\n/*\r\n * This file include a series of intersection operations.\r\n * Here are all the details:\r\n * point ratio\r\n * linear - linear: available available\r\n * linear - quad: none available\r\n * linear - cubic: none available\r\n * quad - quad: none available\r\n * quad - cubic: available none\r\n * cubic - cubic: available none\r\n * To convert from ratio to point was quite simple, this was why I suggest ratio first.\r\n * other cases limited by the algorithm where the point was the first result, I hope you\r\n * notice this and use certain methods to get your result, so I didn't offer an altered\r\n * way, but you can simply achieve that by calling the reparameterize functions.\r\n * Caution that the precision of intersection may cause loss of roots,\r\n * set tolerance around 0.2 - 0.3 might be good.\r\n */\r\n\r\n__gslib_begin__\r\n\r\ngs_export extern void linear_interpolate(vec2 c[], const vec2& p1, const vec2& p2, int step);\r\ngs_export extern void quadratic_interpolate(vec2 c[], const vec2& p1, const vec2& p2, const vec2& p3, int step);\r\ngs_export extern void cubic_interpolate(vec2 c[], const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4, int step);\r\ngs_export extern void hermite_interpolate(vec2 c[], const vec2& p1, const vec2& p2, const vec2& t1, const vec2& t2, int step);\r\ngs_export extern float linear_reparameterize(const vec2& p1, const vec2& p2, const vec2& p);\r\ngs_export extern float quad_reparameterize(const vec3 para[2], const vec2& p);\r\ngs_export extern float cubic_reparameterize(const vec4 para[2], const vec2& p);\r\ngs_export extern float best_quad_reparameterize(const vec3 para[2], const vec2& p);\r\ngs_export extern float best_cubic_reparameterize(const vec4 para[2], const vec2& p);\r\ngs_export extern bool is_concave_angle(const vec2& p1, const vec2& p2, const vec2& p3);\r\ngs_export extern bool is_concave_angle(const vec2& p1, const vec2& p2, const vec2& p3, bool cw);\r\ngs_export extern bool is_approx_line(const vec2& p1, const vec2& p2, const vec2& p3, float tolerance);\r\ngs_export extern void get_linear_coefficient(vec3& coef, const vec2& p, const vec2& d);\r\ngs_export extern void get_linear_parameter_equation(vec2 para[2], const vec2& a, const vec2& b);\r\ngs_export extern void get_quad_parameter_equation(vec3 para[2], const vec2& a, const vec2& b, const vec2& c);\r\ngs_export extern void get_cubic_parameter_equation(vec4 para[2], const vec2& a, const vec2& b, const vec2& c, const vec2& d);\r\ngs_export extern void get_first_derivate_factor(vec2 df1[2], const vec3 para[2]);\r\ngs_export extern void get_first_derivate_factor(vec3 df1[2], const vec4 para[2]);\r\ngs_export extern void get_second_derivate_factor(vec2 df2[2], const vec4 para[2]);\r\ngs_export extern void get_first_derivate_factor(vec3 df1[2], const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4);\r\ngs_export extern void get_second_derivate_factor(vec2 df2[2], const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4);\r\ngs_export extern void get_first_derivate(vec2& d, const vec3 df1[2], float t);\r\ngs_export extern void get_second_derivate(vec2& d, const vec2 df2[2], float t);\r\ngs_export extern float get_cubic_curvature(const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4, float t);\r\ngs_export extern int solve_univariate_quadratic(float t[2], const vec3& coef);\r\ngs_export extern int solve_univariate_cubic(float t[3], const vec4& coef);\r\ngs_export extern int solve_univariate_quartic(float t[4], const float coef[5]);\r\ngs_export extern int get_cubic_inflection(float t[2], const vec2& a, const vec2& b, const vec2& c, const vec2& d);\r\ngs_export extern int get_cubic_inflection(float t[2], const vec3 ff[2], const vec2 sf[2]);\r\ngs_export extern int get_quad_extrema(float t[], const vec2& ff);\r\ngs_export extern int get_cubic_extrema(float t[2], const vec3& ff);\r\ngs_export extern void get_quad_bound_box(rectf& rc, const vec2& p1, const vec2& p2, const vec2& p3);\r\ngs_export extern void get_cubic_bound_box(rectf& rc, const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4);\r\ngs_export extern int intersection_quad_linear(float t[2], const vec3 quad[2], const vec3& linear);\r\ngs_export extern int intersection_cubic_linear(float t[3], const vec4 cubic[2], const vec3& linear);\r\ngs_export extern int intersection_quad_quad(float ts[4][2], const vec3 quad1[2], const vec3 quad2[2]);\r\ngs_export extern void intersectp_linear_linear(vec2& ip, const vec2& p1, const vec2& p2, const vec2& d1, const vec2& d2);\r\ngs_export extern int intersectp_cubic_quad(vec2 ip[6], const vec2 cp1[4], const vec2 cp2[3], float tolerance);\r\ngs_export extern int intersectp_cubic_cubic(vec2 ip[9], const vec2 cp1[4], const vec2 cp2[4], float tolerance);\r\ngs_export extern bool get_self_intersection(float ts[2], const vec2& a, const vec2& b, const vec2& c, const vec2& d);\r\ngs_export extern void split_quad_bezier(vec2 c[5], const vec2 p[3], float t);\r\ngs_export extern void split_quad_bezier(vec2 c[7], const vec2 p[3], float t1, float t2);\r\ngs_export extern void split_cubic_bezier(vec2 c[7], const vec2 p[4], float t);\r\ngs_export extern void split_cubic_bezier(vec2 c[10], const vec2 p[4], float t1, float t2);\r\ngs_export extern void offset_cubic_bezier(vec2 c[4], const vec2 p[4], float d);\r\ngs_export extern float quad_bezier_length(const vec2 cp[3]);\r\ngs_export extern float cubic_bezier_length(const vec2 cp[4], float tolerance);\r\ngs_export extern int cubic_to_quad_bezier(vector& quadctl, const vec2 cp[4], float tolerance);\r\ngs_export extern float quad_control_length(const vec2& a, const vec2& b, const vec2& c);\r\ngs_export extern float cubic_control_length(const vec2& a, const vec2& b, const vec2& c, const vec2& d);\r\ngs_export extern float point_line_distance(const vec2& p, const vec2& p1, const vec2& p2);\r\ngs_export extern int get_interpolate_step(const vec2& a, const vec2& b, const vec2& c, float step_len = -1.f);\r\ngs_export extern int get_interpolate_step(const vec2& a, const vec2& b, const vec2& c, const vec2& d, float step_len = -1.f);\r\ngs_export extern int get_rough_interpolate_step(const vec2& a, const vec2& b, const vec2& c);\r\ngs_export extern int get_rough_interpolate_step(const vec2& a, const vec2& b, const vec2& c, const vec2& d);\r\ngs_export extern float get_cubic_klmcoords(vec3 m[4], const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4,\r\n const vec2& ac1, const vec2& ac2, const vec2& ac3, const vec2& ac4 /* absolute coord for error control */\r\n );\r\ngs_export extern float get_include_angle(const vec2& d1, const vec2& d2);\r\ngs_export extern float get_include_angle(const vec2& a, const vec2& b, const vec2& c);\r\ngs_export extern float get_rotate_angle(const vec2& d1, const vec2& d2);\r\ngs_export extern float get_rotate_angle(const vec2& a, const vec2& b, const vec2& c);\r\ngs_export extern void get_reduce_point(vec2& p, const vec2& a, const vec2& b, const vec2& c, const vec2& d);\r\ngs_export extern bool point_in_triangle(const vec2& p, const vec2& p1, const vec2& p2, const vec2& p3);\r\ngs_export extern int point_in_polygon(const vec2& p, const vector& poly); /* 0: outside; 1 : inside; -1 : coincide */\r\ngs_export extern float get_triangle_area(const vec2& p1, const vec2& p2, const vec2& p3);\r\ngs_export extern vec3 get_barycentric_coords(const vec2& p, const vec2& p1, const vec2& p2, const vec2& p3);\r\ngs_export extern bool clip_line_rect(float t[2], const vec2& p1, const vec2& p2, const rect& clipbox);\r\ngs_export extern bool clip_line_rectf(float t[2], const vec2& p1, const vec2& p2, const rectf& clipbox);\r\ngs_export extern void trace_quad_strip(const vec2 cp[], int size);\r\ngs_export extern void trace_cubic_strip(const vec2 cp[], int size);\r\n\r\ninline bool is_isosigned(float a, float b) { return (int)((*(uint*)&a ^ *(uint*)&b)) >= 0; }\r\ninline bool is_isosigned(double a, double b) { return (long long)((*(unsigned long long*)&a ^ *(unsigned long long*)&b)) >= 0; }\r\ninline bool fuzzy_zero(float f) { return (f <= 1e-4f && f >= -1e-4f); }\r\ninline bool fuzzy_zero(float f, float tol) { return f <= tol && f >= -tol; }\r\ninline bool fuzzy_between(float a, float b, float c, float tol) { return b > a - tol && b < c + tol; }\r\ninline bool fuzzy_greater_inclusive(float m, float n, float tol) { return m > (n - tol); }\r\ninline bool fuzzy_less_inclusive(float m, float n, float tol) { return m < (n + tol); }\r\ninline bool fuzzy_greater_exclusive(float m, float n, float tol) { return m > (n + tol); }\r\ninline bool fuzzy_less_exclusive(float m, float n, float tol) { return m < (n - tol); }\r\ninline bool is_parallel(const vec2& a, const vec2& b) { return fuzzy_zero(a.ccw(b)); }\r\n\r\ninline vec2& eval_linear(vec2& v, const vec2 para[2], float t)\r\n{\r\n vec2 sv(t, 1.f);\r\n v.x = para[0].dot(sv);\r\n v.y = para[1].dot(sv);\r\n return v;\r\n}\r\n\r\ninline vec2& eval_quad(vec2& v, const vec3 para[2], float t)\r\n{\r\n vec3 sv(t * t, t , 1.f);\r\n v.x = para[0].dot(sv);\r\n v.y = para[1].dot(sv);\r\n return v;\r\n}\r\n\r\ninline vec2& eval_cubic(vec2& v, const vec4 para[2], float t)\r\n{\r\n vec4 sv(t * t * t, t * t, t, 1.f);\r\n v.x = para[0].dot(sv);\r\n v.y = para[1].dot(sv);\r\n return v;\r\n}\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "6f73fa7d5826064afb64a9e7dd55eea500d37bb6", "size": 10626, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/utility.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/utility.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/utility.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 64.7926829268, "max_line_length": 129, "alphanum_fraction": 0.7273668361, "num_tokens": 3066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4277530921163461}} {"text": "// The MIT License (MIT)\n//\n// Copyright (c) 2018 Mateusz Pusz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace units {\n\nstruct ratio;\nconstexpr ratio inverse(const ratio& r);\n\n/**\n * @brief Provides compile-time rational arithmetic support.\n *\n * This class is really similar to @c std::ratio but gets an additional `Exp`\n * template parameter that defines the exponent of the ratio. Another important\n * difference is the fact that the objects of that class are used as class NTTPs\n * rather then a type template parameter kind.\n */\nstruct ratio {\n std::intmax_t num;\n std::intmax_t den;\n std::intmax_t exp;\n\n constexpr explicit ratio(std::intmax_t n, std::intmax_t d = 1, std::intmax_t e = 0): num(n), den(d), exp(e)\n {\n gsl_Expects(den != 0);\n detail::normalize(num, den, exp);\n }\n\n [[nodiscard]] friend constexpr bool operator==(const ratio&, const ratio&) = default;\n\n [[nodiscard]] friend constexpr ratio operator*(const ratio& lhs, const ratio& rhs)\n {\n const std::intmax_t gcd1 = std::gcd(lhs.num, rhs.den);\n const std::intmax_t gcd2 = std::gcd(rhs.num, lhs.den);\n return ratio(detail::safe_multiply(lhs.num / gcd1, rhs.num / gcd2),\n detail::safe_multiply(lhs.den / gcd2, rhs.den / gcd1),\n lhs.exp + rhs.exp);\n }\n\n [[nodiscard]] friend constexpr ratio operator/(const ratio& lhs, const ratio& rhs)\n {\n return lhs * inverse(rhs);\n }\n};\n\n[[nodiscard]] constexpr ratio inverse(const ratio& r)\n{\n return ratio(r.den, r.num, -r.exp);\n}\n\n[[nodiscard]] constexpr bool is_integral(const ratio& r)\n{\n if(r.exp < 0) {\n return false;\n } else {\n return detail::gcdpow(r.num, r.exp, r.den) == r.den;\n }\n}\n\nnamespace detail {\n\n[[nodiscard]] constexpr auto make_exp_align(const ratio& r, std::intmax_t alignment)\n{\n gsl_Expects(alignment > 0);\n const std::intmax_t rem = r.exp % alignment;\n\n if (rem == 0) { // already aligned\n return std::array{r.num, r.den, r.exp};\n }\n\n if (r.exp > 0) { // remainder is positive\n return std::array{r.num * ipow10(rem), r.den, r.exp - rem};\n }\n\n // remainder is negative\n return std::array{r.num, r.den * ipow10(-rem), r.exp - rem};\n}\n\ntemplate\n requires gt_zero\n[[nodiscard]] constexpr ratio root(const ratio& r)\n{\n if constexpr (N == 1) {\n return r;\n } else {\n if (r.num == 0) {\n return ratio(0);\n }\n\n const auto aligned = make_exp_align(r, N);\n return ratio(iroot(aligned[0]), iroot(aligned[1]), aligned[2] / N);\n }\n}\n\n} // namespace detail\n\ntemplate\n requires detail::non_zero\n[[nodiscard]] constexpr ratio pow(const ratio& r)\n{\n if constexpr (Num == 0) {\n return ratio(1);\n } else if constexpr (Num == Den) {\n return r;\n } else {\n // simplify factors first and compute power for positive exponent\n constexpr std::intmax_t gcd = std::gcd(Num, Den);\n constexpr std::intmax_t num = detail::abs(Num / gcd);\n constexpr std::intmax_t den = detail::abs(Den / gcd);\n\n // integer root loses precision so do pow first\n const ratio result = detail::root(detail::pow_impl(r));\n\n if constexpr (Num * Den < 0) { // account for negative exponent\n return inverse(result);\n } else {\n return result;\n }\n }\n}\n\n[[nodiscard]] constexpr ratio sqrt(const ratio& r) { return pow<1, 2>(r); }\n\n[[nodiscard]] constexpr ratio cbrt(const ratio& r) { return pow<1, 3>(r); }\n\n// common_ratio\n[[nodiscard]] constexpr ratio common_ratio(const ratio& r1, const ratio& r2)\n{\n const auto res = detail::gcd_frac(r1.num, r1.den, r1.exp, r2.num, r2.den, r2.exp);\n return ratio(res[0], res[1], res[2]);\n}\n\n} // namespace units\n", "meta": {"hexsha": "17a97613056660c9dc4c64ac93dc68d2fd87c382", "size": 4998, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/units/ratio.h", "max_stars_repo_name": "HazardyKnusperkeks/units", "max_stars_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/include/units/ratio.h", "max_issues_repo_name": "HazardyKnusperkeks/units", "max_issues_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/include/units/ratio.h", "max_forks_repo_name": "HazardyKnusperkeks/units", "max_forks_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2909090909, "max_line_length": 109, "alphanum_fraction": 0.6778711485, "num_tokens": 1319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4277432250033807}} {"text": "/* Copyright (c) 2014, Giuseppe Argentieri \n\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n * \n *\n *\n * Filename: evol.c\n *\n * Description: Evolution of the density matrix with a given generator\n *\n * Version: 1.0\n * Created: 02/05/2014 14:40:25\n * Revision: none\n * License: BSD\n *\n * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it\n * Organization: Università degli Studi di Trieste\n *\n * \n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"funcs.h\"\n\n\n/* \n * FUNCTION \n * Name: generator\n * Description: Setting the dydt in Bloch form\n * \n */\nint generator ( double t, const double y[], double dydt[], void* PARS )\n{\n\t/* Extracting the matrix address from PARS */\n\tgsl_matrix* M = (gsl_matrix*) PARS ;\n\n\t/* Generator */\n\tunsigned int i , j ;\n\tfor ( i = 0; i < 4 ; i++ )\n\t\tdydt[i] = 0 ;\n\n\tfor ( i = 1 ; i < 4 ; i++ )\n\t\tfor ( j = 0 ; j < 4 ; j++ )\n\t\t\tdydt[i] = dydt[i] + gsl_matrix_get( M, i, j )*y[j] ;\n\n\treturn GSL_SUCCESS;\n}\t\t/* ----- end of function generator ----- */\n\n\n/* \n * FUNCTION \n * Name: jac\n * Description: Jacobian matrix of the generator (which is exactly the Bloch matrix)\n * \n */\nint jac ( double t, const double y[], double dfdy[] , double dfdt[], void* PARS )\n{\n\t/* Taking the generator Bloch's matrix address from PARS */\n\tgsl_matrix* bloch = (gsl_matrix*) PARS ;\n\n\t/* Creating a matrix view of the array dfdy */\n\tgsl_matrix_view m = gsl_matrix_view_array ( dfdy , 4, 4 ) ; \t\n\t\n\t/* Initializing the jacobian matrix with the Bloch generator */\n\tunsigned int i, j ; \n\tfor ( i = 0 ; i < 4 ; i++ ) \n\t\tfor ( j = 0 ; j < 4 ; j++ ) \n\t\t\tgsl_matrix_set ( &m.matrix, i, j, gsl_matrix_get(bloch,i,j) ) ;\n\n\tfor ( i = 0 ; i < 4 ; i++ )\n\t\tdfdt[i] = 0 ;\n\n\treturn GSL_SUCCESS;\n}\t\t/* ----- end of function jac ----- */\n\n\n/* \n * FUNCTION \n * Name: evol\n * Description: \n * \n */\nint evol ( double t, gsl_vector* state, double step,\n\t\tgsl_odeiv2_evolve* e, gsl_odeiv2_control* c, gsl_odeiv2_step* s,\n\t\tgsl_odeiv2_system* sys )\n{\n\t/* Creating the array 'rho' for the vector 'state' */\n\tdouble rho[4] ;\n\tunsigned int i ;\n\tfor ( i = 0 ; i < 4 ; i++ ) \n\t\trho[i] = VECTOR( state, i ) ;\n\n\t/* evolving the array 'rho' */\n\tint status = gsl_odeiv2_evolve_apply_fixed_step\t( e, c, s, sys, &t, step, rho ) ;\n\tif ( status != GSL_SUCCESS )\n\t{\n\t\tprintf(\"STATUS: %d\\n\", status) ;\n\t\texit(1) ;\n\t}\n\n\t/* updating vector 'state' */\n\tfor ( i = 0 ; i < 4 ; i++ )\n\t\tgsl_vector_set( state, i, rho[i] ) ;\n\n\treturn status ;\n}\t\t/* ----- end of function evol ----- */\n\n\n\n", "meta": {"hexsha": "321e5bf219593affe4ee876b2ccc69f291a8629d", "size": 3981, "ext": "c", "lang": "C", "max_stars_repo_path": "evol.c", "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "evol.c", "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "evol.c", "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0583941606, "max_line_length": 86, "alphanum_fraction": 0.6455664406, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.427473458738533}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"compearth.h\"\n#ifdef COMPEARTH_USE_MKL\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#pragma clang diagnostic ignored \"-Wstrict-prototypes\"\n#endif\n#include \n#include \n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include \n#include \n#endif\n#include \"cmopad.h\"\n\n/*\nCopyright (C) 2010\nLars Krieger & Sebastian Heimann\n\nContact\nlars.krieger@zmaw.de & sebastian.heimann@zmaw.de\n\nModifications - 2015\nConverted original Python mopad.py to C - Ben Baker (ISTI)\n\nContact\nbenbaker@isti.com\n\n#######################################################################\n\nLicense:\n\nGNU Lesser General Public License, Version 3\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public License\nas published by the Free Software Foundation; either version 3\nof the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n02110-1301, USA.\n*/\n\n#define rad2deg 180.0/M_PI\n#define epsilon 1.e-13\nstatic double numpy_mod(double a, double b);\nstatic int __cmopad_argsort3(double *a, int *perm);\nstatic int __cmopad_inv3(double Amat[3][3]);\nstatic double __cmopad_determinant3x3(double A[3][3]);\nstatic double __cmopad_trace3(double M[3][3]);\nstatic int __cmopad_Eigs3x3(double a[3][3], int job, double eigs[3]);\nstatic void __cmopad_swap8(double *a, double *b);\nstatic void array_cross3(const double *__restrict__ u,\n const double *__restrict__ v,\n double *__restrict__ n);\n\n//============================================================================//\n/*!\n * @brief Generates basis for coordinate transform switch \n *\n * @param[in] in_system input system: NED, USE, XYZ, NWU\n * @param[in] out_system output system: NED, USE, XYZ, NWU\n *\n * @param[out] r rotation matrix [3 x 3] \n *\n * @result 0 in indicates success\n *\n */\nint cmopad_basis_switcher(enum cmopad_basis_enum in_system, \n enum cmopad_basis_enum out_system, double r[3][3])\n{\n const char *fcnm = \"cmopad_basis_switcher\\0\";\n double From[9], To[9], r9[9]; \n double alpha = 1.0;\n double beta = 0.0;\n int n3 = 3;\n int i, j;\n //------------------------------------------------------------------------//\n //\n // null out to and from\n for (i=0; i<9; i++)\n {\n To[i] = 0.0;\n From[i] = 0.0;\n }\n // Classify in\n if (in_system == NED)\n {\n // Inverse of identity: From[0] = 1.0; From[4] = 1.0; From[8] = 1.0 is:\n From[0] = 1.0; From[4] = 1.0; From[8] = 1.0;\n }\n else if (in_system == USE)\n {\n From[3] =-1.0; From[7] = 1.0; From[2] =-1.0; \n }\n else if (in_system == XYZ)\n {\n From[3] = 1.0; From[1] = 1.0; From[8] =-1.0; \n }\n else if (in_system == NWU)\n {\n From[0] = 1.0; From[4] =-1.0; From[8] =-1.0;\n }\n else\n {\n printf(\"%s: Invalid in coordinate system %d\\n\", fcnm, in_system);\n return -1;\n }\n // Classify out\n if (out_system == NED)\n {\n To[0] = 1.0; To[4] = 1.0; To[8] = 1.0;\n }\n else if (out_system == USE)\n {\n // Inverse of: To[3] =-1.0; To[7] = 1.0; To[2] =-1.0; is\n To[1] =-1.0; To[5] = 1.0; To[6] =-1.0;\n }\n else if (out_system == XYZ)\n {\n // Inverse of To[3] = 1.0; To[1] = 1.0; To[8] =-1.0; is:\n To[1] = 1.0; To[3] = 1.0; To[8] =-1.0;\n }\n else if (out_system == NWU)\n {\n //Inverse of: To[0] = 1.0; To[4] =-1.0; To[8] =-1.0; is\n To[0] = 1.0; To[4] =-1.0; To[8] =-1.0;\n }\n else\n {\n printf(\"%s: Invalid out coordinate system %d\\n\", fcnm, out_system);\n return -1;\n } \n // Multiply inv(in)*out\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n n3, n3, n3, alpha, From, n3, To, n3, beta,\n r9, n3);\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n r[i][j] = r9[3*j + i];\n }\n }\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Transform a matrix from in_sys to out_sys. This is an interface\n * routine to cmopad_basis__transformMatrixM33\n * because many matrices are stored as a length 6 array.\n *\n * @param[in,out] m on input length 6 matrix in in_sys. the ordering is \n * \\f$ {1,2,3,4,5,6} = {11,22,33,12,13,23} \\f$.\n * on output length 6 matrix in out_sys. the ordering is\n * \\f$ {1,2,3,4,5,6} = {11,22,33,12,13,23} \\f$.\n *\n * @param[in] in_sys input system: NED, USE, XYZ, NWU\n * @param[in] out_sys output system: NED, USE, XYZ, NWU\n *\n * @result 0 indicates success\n *\n */\nint cmopad_basis_transformMatrixM6(double *m,\n enum cmopad_basis_enum in_sys,\n enum cmopad_basis_enum out_sys)\n{\n const char *fcnm = \"cmopad_basis_transformMatrixM6\\0\";\n double M33[3][3];\n int ierr;\n //------------------------------------------------------------------------//\n //\n // Convert array matrix to matrix matrix\n M33[0][0] = m[0]; //mxx; mrr\n M33[1][1] = m[1]; //myy; mtt\n M33[2][2] = m[2]; //mzz; mpp\n M33[0][1] = M33[1][0] = m[3]; //mxy; mrt\n M33[0][2] = M33[2][0] = m[4]; //mxz; mrp\n M33[1][2] = M33[2][1] = m[5]; //myz; mtp\n // Switch basis \n ierr = cmopad_basis_transformMatrixM33(M33, in_sys, out_sys);\n if (ierr != 0)\n {\n printf(\"%s: Error changing basis\\n\", fcnm);\n return -1;\n }\n // Convert matrix matrix back to array matrix\n m[0] = M33[0][0]; //mxx; mrr\n m[1] = M33[1][1]; //myy; mtt\n m[2] = M33[2][2]; //mzz; mpp\n m[3] = M33[0][1]; //mxy; mrt\n m[4] = M33[0][2]; //mxz; mrp\n m[5] = M33[1][2]; //myz; mtp\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Transform a symmetric 3x3 matrix from in_sys to out_sys. \n *\n * @param[in,out] m on input [3x3] symmetric matrix in in_sys.\n * on output [3x3] symmetric matrix in out_sys\n *\n * @param[in] in_sys input system: NED, USE, XYZ, NWU\n * @param[in] out_sys output system: NED, USE, XYZ, NWU\n *\n * @result 0 indicates success\n *\n */\nint cmopad_basis_transformMatrixM33(double m[3][3],\n enum cmopad_basis_enum in_sys,\n enum cmopad_basis_enum out_sys)\n{\n const char *fcnm = \"cmopad_basis_transformMatrixM33\\0\";\n double r[3][3], t9[9], invR[3][3], invR9[9], r9[9], m9[9];\n double alpha = 1.0;\n double beta = 0.0;\n int n3 = 3;\n int i, j, ierr;\n //------------------------------------------------------------------------//\n //\n // Compute change of basis matrix \n ierr = cmopad_basis_switcher(in_sys, out_sys, r);\n if (ierr != 0)\n {\n printf(\"%s: Error generating basis switching matrix\\n\",fcnm);\n return -1;\n }\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n r9[3*j + i] = r[i][j];\n m9[3*j + i] = m[i][j];\n //invR9[3*j + i] = r[i][j];\n invR[i][j] = r[i][j];\n }\n }\n // compute inv(R)\n ierr = __cmopad_inv3(invR); //double Amat[3][3])\n if (ierr != 0)\n {\n printf(\"%s: Unlikely error!\\n\", fcnm);\n return -1;\n }\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n invR9[3*j + i] = invR[i][j];\n }\n }\n // Compute R M inv(R)\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n n3, n3, n3, alpha, m9, n3, invR9, n3, beta,\n t9, n3);\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n n3, n3, n3, alpha, r9, n3, t9, n3, beta,\n m9, n3);\n // Copy back\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n m[i][j] = m9[3*j + i];\n }\n }\n return 0;\n}\n//============================================================================//\n/*! \n * @brief Transforms a vector v from basis in_sys to basis out_sys\n *\n * @param[in,out] v on input length 3 vector in in_sys. \n * on output length 3 vector in out_sys.\n *\n * @param[in] in_sys input system: NED, USE, XYZ, NWU\n * @param[in] out_sys output system: NED, USE, XYZ, NWU\n *\n * @result 0 indicates success\n *\n */\nint cmopad_basis_transformVector(double v[3],\n enum cmopad_basis_enum in_sys,\n enum cmopad_basis_enum out_sys)\n{\n const char *fcnm = \"cmopad_basis_transformVector\\0\";\n double r[3][3], r9[9], x[3]; \n double alpha = 1.0;\n double beta = 0.0;\n int n3 = 3;\n int incx = 1;\n int incy = 1;\n int i,j,ierr;\n //------------------------------------------------------------------------//\n //\n // Compute change of basis matrix\n ierr = cmopad_basis_switcher(in_sys, out_sys, r);\n if (ierr != 0)\n {\n printf(\"%s: Error making basis switcher matrix\\n\", fcnm);\n return -1;\n }\n for (i=0; i<3; i++)\n {\n x[i] = v[i];\n for (j=0; j<3; j++)\n {\n r9[3*j + i] = r[i][j];\n }\n }\n // Compute v <- R*v \n cblas_dgemv(CblasColMajor, CblasNoTrans, n3, n3, alpha, r9,\n n3, x, incx, beta, v, incy);\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Cross product of 2 length 3 vectors u and v. Returns normal vector n.\n * \n * @param[in] u first vector in cross product u x v [3]\n * @param[in] v second vector in cross product u x v [3]\n * \n * @param[out] n normal vector n = u x v [3]\n *\n */\nstatic void array_cross3(const double *__restrict__ u,\n const double *__restrict__ v,\n double *__restrict__ n)\n{\n n[0] = u[1]*v[2] - u[2]*v[1];\n n[1] = u[2]*v[0] - u[0]*v[2]; \n n[2] = u[0]*v[1] - u[1]*v[0];\n return;\n}\n//============================================================================//\n/*! \n * @brief Converts the unit eigenvector of length eig in coordinate system\n * coord to length, azimuth, plunge. \n * http://docs.obspy.org/_modules/obspy/imaging/beachball.html#PrincipalAxis\n * This is an extension of MoPaD\n *\n * @param[in] coord coordinate system (e.g., NED,USE,XYZ)\n * @param[in] eig length of eigenvector\n * @param[in] ev eigenvector in system coordinate system [3]\n * \n * @param[out] paxis principal axis store azimuth, plunge, length [3]\n * \n * @result 0 indicates success\n *\n */\nint cmopad_Eigenvector2PrincipalAxis(enum cmopad_basis_enum coord, double eig, \n double ev[3], double paxis[3])\n{ \n const char *fcnm = \"cmopad_Eigenvector2PrincipalAxis\\0\";\n double v[3], az, plunge;\n double twopi = 2.0*M_PI;\n double pi180i = 180.0/M_PI;\n int ierr;\n //------------------------------------------------------------------------//\n //\n // Convert eigenvector ev to USE convention \n cblas_dcopy(3, ev, 1, v, 1);\n ierr = cmopad_basis_transformVector(v, coord, USE);\n if (ierr != 0)\n {\n printf(\"%s: Error switching basis\\n\", fcnm);\n return -1; \n } \n // Compute azimuth and plunge angles \n plunge = asin(-v[0]); //arcsin(-z/r)\n az = atan2(v[2],-v[1]); //atan(x/y)\n if (plunge <= 0.0)\n {\n plunge =-plunge;\n az = az + M_PI;\n } \n if (az < 0.0){az = az + twopi;} //Shift to [0,360]\n if (az > twopi){az = az - twopi;} //Shift to [0,360]\n // Convert to degrees\n plunge = plunge*pi180i;\n az = az*pi180i;\n // Copy back result\n paxis[0] = az; //First value is azimuth (degrees)\n paxis[1] = plunge; //Second value is plunge (degrees)\n paxis[2] = eig; //Final value is eigenvalue (distance)\n return 0;\n}\n//============================================================================//\n/*! \n * @brief Given coordinate system (x,y,z) and rotated system (xs,ys,zs)\n * the line of nodes is the intersection between the x-y and the xs-ys\n * planes.\n *\n * @param[in] alpha is the angle between the z-axis and the zs-axis\n * and represents the dip angle (radians)\n * @param[in] beta is the angle between the x-axis and the line of nodes\n * and represents the strike (radians)\n * @param[in] gamma is the angle between the line of nodes and the xs-axis\n * and represents the rake angle (radians)\n *\n * @param[out] mat rotation matrix built from euler angles [3 x 3]\n *\n * @note Original Python usage for moment tensors:\n *\n * m_unrot = numpy.matrix([[0,0,-1],[0,0,0],[-1,0,0]])\n * rotmat = cmopadEulerToMatrix(dip,strike,-rake)\n * m = rotmat.T * m_unrot * rotmat'''\n *\n */\nvoid cmopad_eulerToMatrix(double alpha, double beta, double gamma,\n double mat[3][3])\n{\n double ca, cb, cg, sa, sb, sg;\n ca = cos(alpha);\n cb = cos(beta);\n cg = cos(gamma);\n sa = sin(alpha);\n sb = sin(beta);\n sg = sin(gamma);\n\n mat[0][0] = cb*cg-ca*sb*sg; mat[0][1] = sb*cg+ca*cb*sg; mat[0][2] = sa*sg;\n mat[1][0] =-cb*sg-ca*sb*cg; mat[1][1] =-sb*sg+ca*cb*cg; mat[1][2] = sa*cg;\n mat[2][0] = sa*sb; mat[2][1] =-sa*cb; mat[2][2] = ca;\n return;\n}\n//============================================================================//\n/*!\n * @brief Computes the moment magnitude from a 6 vector\n *\n * @param[in] M6 moment tensor stored:\n * \\f$ \\{m_{11},m_{22},m_{33},m_{12},m_{13},m_{23} \\} \\f$\n * with the moment tensor terms of units Newton-meters\n *\n * @param[out] ierr 0 indicates success\n *\n * @result moment magnitue\n *\n * @author Ben Baker (ISTI)\n *\n */\ndouble cmopad_momentMagnitudeM6(const double M6[6], int *ierr)\n{\n const char *fcnm = \"cmopad_momentMagnitudeM6\\0\";\n double mag;\n const double two_third = 2.0/3.0;\n *ierr = 0;\n mag = M6[0]*M6[0] + M6[1]*M6[1] + M6[2]*M6[2]\n + 2.0*(M6[3]*M6[3] + M6[4]*M6[4] + M6[5]*M6[5]);\n if (mag == 0.0)\n {\n *ierr = 1;\n printf(\"%s: Error magnitude is zero\\n\", fcnm);\n }\n else\n {\n mag = two_third*(log10(mag) - 9.1);\n }\n return mag;\n}\n//============================================================================//\n/*!\n * @brief Computes the moment magnitude from a the symmetric moment tensor\n *\n * @param[in] M symmetric moment tensor with terms given in Newton-meters\n *\n * @param[out] ierr 0 indicates success\n *\n * @result moment magnitue\n *\n * @author Ben Baker (ISTI)\n *\n */\ndouble cmopad_momentMagnitudeM3x3(const double M[3][3], int *ierr)\n{\n const char *fcnm = \"cmopad_momentMagnitudeM33\\0\";\n double M6[6], mag;\n M6[0] = M[0][0];\n M6[1] = M[1][1];\n M6[2] = M[2][2];\n M6[3] = M[0][1];\n M6[4] = M[0][2];\n M6[5] = M[1][2];\n mag = cmopad_momentMagnitudeM6(M6, ierr);\n if (*ierr != 0) \n {\n printf(\"%s: Error computing moment magnitude\\n\", fcnm);\n }\n return mag;\n}\n//============================================================================//\n/*!\n * @brief Sets the two angle-triples, describing the faultplanes of the\n * Double Couple, defined by the eigenvectors P and T of the\n * moment tensor object.\n *\n * Define a reference Double Couple with strike = dip =\n * slip-rake = 0, the moment tensor object's DC is transformed\n * (rotated) w.r.t. this orientation. The respective rotation\n * matrix yields the first fault plane angles as the Euler\n * angles. After flipping the first reference plane by\n * multiplying the appropriate flip-matrix, one gets the second fault\n * plane's geometry.\n *\n * All output angles are in degree\n *\n * @param[in] iverb controls verbosity for debugging. 0 should be quiet.\n *\n * @param[in,out] src on input holds plot_clr_order \n * on output holds the strike, dips, and rakes\n * describing fault planes fp1 and fp2\n *\n * @result 0 indicates success\n *\n */\nint cmopad_findFaultPlanes(int iverb, struct cmopad_struct *src)\n{\n const char *fcnm = \"cmopad_findFaultPlanes\\0\";\n int n3 = 3;\n double rot_matrix_fp1[3][3], rot_matrix_fp2[3][3],\n refDC_evecs[9], flip_dc[9], work1[9], work2[9],\n pnt_sorted_EV_matrix[3][3],\n det;\n double sqrt22 = 0.7071067811865476; //sqrt(2)/2 \n double alpha = 1.0, beta = 0.0;\n int i, j;\n //------------------------------------------------------------------------//\n //\n // reference Double Couple (in NED) basis w/ (strike,dip,slip) = (0,0,0)\n refDC_evecs[0] =-sqrt22; refDC_evecs[3] = 0.0; refDC_evecs[6] =-sqrt22; \n refDC_evecs[1] = 0.0; refDC_evecs[4] = 1.0; refDC_evecs[7] = 0.0;\n refDC_evecs[2] =-sqrt22; refDC_evecs[5] = 0.0; refDC_evecs[8] = sqrt22;\n\n //refDC_evals[0] =-1.0; \n //refDC_evals[1] = 0.0;\n //refDC_evals[2] = 1.0;\n // Matrix which is turning from one fault plane to the other\n flip_dc[0] = 0.0; flip_dc[3] = 0.0; flip_dc[6] =-1.0; \n flip_dc[1] = 0.0; flip_dc[4] =-1.0; flip_dc[7] = 0.0;\n flip_dc[2] =-1.0; flip_dc[5] = 0.0; flip_dc[8] = 0.0;\n // Euler-tools need matrices of EV sorted in PNT (pressure,null,tension):\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n pnt_sorted_EV_matrix[i][j] = src->rotation_matrix[i][j];\n }\n } \n // Re-sort only necessary if abs(p) <= abs(t)\n if (src->plot_clr_order < 0)\n {\n for (i=0; i<3; i++)\n {\n pnt_sorted_EV_matrix[i][0] = src->rotation_matrix[i][2];\n pnt_sorted_EV_matrix[i][2] = src->rotation_matrix[i][0];\n }\n }\n // Rotation matrix, describing the rotation of the eigenvector\n // system of the input moment tensor into the eigenvector\n // system of the reference Double Couple\n if (iverb > 1)\n {\n printf(\"%s: Pressure, null, tension eigenvectors:\\n\",fcnm);\n }\n for (j=0; j<3; j++)\n {\n for (i=0; i<3; i++)\n {\n work1[j*n3 + i] = pnt_sorted_EV_matrix[i][j];\n }\n if (iverb > 1)\n {\n printf(\n \"%8.5f %8.5f %8.5f\\n\",pnt_sorted_EV_matrix[j][0],\n pnt_sorted_EV_matrix[j][1],\n pnt_sorted_EV_matrix[j][2]);\n }\n }\n if (iverb > 1)\n {\n printf(\"%s: Reference double couple eigenvectors:\\n\",fcnm);\n for (i=0; i<3; i++)\n {\n printf(\n \"%8.5f %8.5f %8.5f\\n\",refDC_evecs[i],\n refDC_evecs[3+i],refDC_evecs[6+i]);\n }\n }\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n3, n3, n3, \n alpha, work1, n3, refDC_evecs, n3, beta,\n work2, n3);\n for (j=0; j<3; j++)\n {\n for (i=0; i<3; i++)\n {\n rot_matrix_fp1[j][i] = work2[j*n3 + i]; //Copy transpose\n }\n }\n // check if rotation has correct orientation\n det = __cmopad_determinant3x3(rot_matrix_fp1);\n if (det < 0.0)\n {\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n rot_matrix_fp1[i][j] =-1.0*rot_matrix_fp1[i][j];\n }\n }\n } \n for (j=0; j<3; j++)\n {\n for (i=0; i<3; i++)\n {\n work1[j*3 + i] = rot_matrix_fp1[i][j];\n }\n }\n // adding a rotation into the (ambiguous) system of the 2nd fault plane\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n3, n3, n3,\n alpha, flip_dc, n3, work1, n3, beta, \n work2, n3);\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n rot_matrix_fp2[i][j] = work2[j*3 + i];\n }\n }\n // Calculate strike, dip, rake of fault planes\n cmopad_findStrikeDipRake(rot_matrix_fp1, \n &src->fp1[1], &src->fp1[0], &src->fp1[2]);\n cmopad_findStrikeDipRake(rot_matrix_fp2,\n &src->fp2[1], &src->fp2[0], &src->fp2[2]);\n // For convenience if choose the first fault plane to be the one with\n // the smaller strike\n if (src->fp2[0] < src->fp1[0])\n {\n for (i=0; i<3; i++)\n {\n __cmopad_swap8(&src->fp1[i], &src->fp2[i]);\n }\n }\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Returns dip, strike, and slip(rake) angles in degrees describing the \n * fault plane.\n *\n * @param[in] rot_mat matrix of eignevectors for fault plane [3 x 3]\n *\n * @param[out] alpha dip angle (degrees)\n * @param[out] beta strike angle (degrees)\n * @param[out] gamma rake angle (degrees)\n *\n */\nvoid cmopad_findStrikeDipRake(double rot_mat[3][3],\n double *alpha, double *beta, double *gamma)\n{\n double a = 0.0, b = 0.0, g = 0.0;\n cmopad_MatrixToEuler(rot_mat, &a, &b, &g);\n *alpha = a*rad2deg;\n *beta = b*rad2deg;\n *gamma =-g*rad2deg;\n return;\n}\n//============================================================================//\n/*!\n * @brief Returns three Euler angles alpha, beta, and gamma (radians) from a\n * rotation matrix.\n *\n * @param[in] rotmat rotation matrix of which to decompose into euler angles\n * [3 x 3]\n *\n * @param[out] alpha euler angle representing dip (radians)\n * @param[out] beta euler angle representing strike (radians)\n * @param[out] gamma euler angle representing -rake (radians)\n *\n */\nvoid cmopad_MatrixToEuler(double rotmat[3][3],\n double *alpha, double *beta, double *gamma)\n{\n const int n3 = 3;\n int inc = 1;\n double ex[3], ez[3], exs[3], ezs[3], enodes[3], enodess[3], \n xnorm, cos_alpha, a,b,g,a1,a2;\n double twopi = 2.0*M_PI;\n int i,j;\n //------------------------------------------------------------------------//\n //\n // transpose matrix vector multiply\n ex[0] = 1.0; ex[1] = 0.0; ex[2] = 0.0;\n ez[0] = 0.0; ez[1] = 0.0; ez[2] = 1.0;\n for (i=0; i<3; i++)\n {\n exs[i] = 0.0; ezs[i] = 0.0;\n for (j=0; j<3; j++)\n {\n exs[i] = exs[i] + rotmat[j][i]*ex[j];\n ezs[i] = ezs[i] + rotmat[j][i]*ez[j];\n }\n }\n // Cross product\n array_cross3(ez, ezs, enodes);\n xnorm = sqrt(pow(enodes[0],2) + pow(enodes[1],2) + pow(enodes[2],2));\n if (xnorm < 1.e-10)\n {\n for (i=0; i<3; i++)\n {\n enodes[i] = exs[i];\n }\n }\n for (i=0; i<3; i++)\n {\n enodess[i] = 0.0;\n for (j=0; j<3; j++)\n {\n enodess[i] = enodess[i] + rotmat[i][j]*enodes[j];\n }\n }\n // Multiply\n cos_alpha = cblas_ddot(n3, ez, inc, ezs, inc); \n cos_alpha = fmin( 1.0, cos_alpha);\n cos_alpha = fmax(-1.0, cos_alpha);\n a = acos(cos_alpha); \n a1 = atan2( enodes[1], enodes[0]);\n a2 =-atan2(enodess[1], enodess[0]);\n b = numpy_mod(a1, twopi);\n g = numpy_mod(a2, twopi);\n // Compute unique Euler angles\n cmopad_uniqueEuler(&a, &b, &g);\n *alpha = a; \n *beta = b; \n *gamma = g;\n return;\n}\n//============================================================================//\n/*!\n * @brief Clone of the numpy mod(a,b) function\n *\n * @result numpy.mod(a, b)\n *\n */\nstatic double numpy_mod(double a, double b)\n{\n if (b == 0.0){return a;}\n if (a >= 0.0)\n {\n if (b > 0.0)\n {\n return a - floor(a/b)*b;\n }\n else\n {\n return a - fabs(floor(a/b))*fabs(b);\n } \n }\n else\n {\n if (b > 0.0)\n {\n return a + fabs(floor(a/b))*fabs(b);\n }\n else\n {\n return a + floor(a/b)*fabs(b);\n }\n }\n}\n//============================================================================//\n/*! \n * Read in Matrix M and set up eigenvalues (EW) and eigenvectors\n * (EV) for setting up the principal axis system.\n *\n * The internal convention is the 'HNS'-system: H is the\n * eigenvector for the smallest absolute eigenvalue, S is the\n * eigenvector for the largest absolute eigenvalue, N is the null\n * axis.\n *\n * Naming due to the geometry: a CLVD is\n * Symmetric to the S-axis,\n * Null-axis is common sense, and the third (auxiliary) axis\n * Helps to construct the RA3.\n *\n * Additionally builds matrix for basis transformation back to NED system.\n *\n * The eigensystem setup defines the colouring order for a later\n * plotting in the BeachBall class. This order is set by the\n * `_plot_clr_order' attribute.\n *\n * @param[in] iverb controls verbosity. 0 is quiet.\n *\n * @param[in,out] src on input holds the input moment tensor \n * on output has the eigenvalues and fault planes\n *\n */\nint cmopad_MT2PrincipalAxisSystem(int iverb, struct cmopad_struct *src)\n{\n const char *fcnm = \"cmopad_MT2PrincipalAxisSystem\\0\";\n int ival = 0;\n double M[3][3], M_devi[3][3], EV_devi[3][3], EV[3][3], EW[3], \n EW_devi[3], EV1[3], EV2[3], EV3[3], EVh[3], EVs[3], EVn[3], \n EWs, EWh, EWn,\n EW1, EW2, EW3, EW1_devi, EW2_devi, EW3_devi, \n trace_M, xsum;\n int EW_order[3], symmetry_around_tension, clr, i, j, ierr;\n //------------------------------------------------------------------------//\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n M[i][j] = src->M[i][j];\n M_devi[i][j] = src->M_devi[i][j];\n EV[i][j] = M[i][j];\n EV_devi[i][j] = M_devi[i][j];\n }\n }\n ierr = __cmopad_Eigs3x3(EV_devi, ival, EW_devi);\n if (ierr != 0)\n {\n printf(\"%s: Error computing eigenvalues (a)!\", fcnm);\n return -1; \n } \n ierr = __cmopad_argsort3(EW_devi, EW_order);\n // Removed if statement, always true in python code\n trace_M = __cmopad_trace3(M); // M[0][0] + M[1][1] + M[2][2];\n if (trace_M < epsilon){trace_M = 0.0;}\n ierr = __cmopad_Eigs3x3(EV, ival, EW);\n if (ierr != 0)\n {\n printf(\"%s: Error computing eigenvalues (b)!\", fcnm);\n return -1;\n }\n for (i=0; i<3; i++)\n {\n if (fabs(EW[i]) < epsilon){EW[i] = 0.0;}\n }\n //trace_M_devi = cmopadTrace(3,M_devi);\n\n // Save eigenvalues/eigenvectors for deviatoric and full moment tensor\n EW1_devi = EW_devi[EW_order[0]];\n EW2_devi = EW_devi[EW_order[1]];\n EW3_devi = EW_devi[EW_order[2]];\n if (fabs(EW2_devi) < epsilon){EW2_devi = 0.0;}\n\n EW1 = EW[EW_order[0]];\n EW2 = EW[EW_order[1]];\n EW3 = EW[EW_order[2]];\n for (i=0; i<3; i++)\n {\n //EV1_devi[i] = EV_devi[i][EW_order[0]];\n //EV2_devi[i] = EV_devi[i][EW_order[1]]; \n //EV3_devi[i] = EV_devi[i][EW_order[2]]; \n EV1[i] = EV[i][EW_order[0]];\n EV2[i] = EV[i][EW_order[1]];\n EV3[i] = EV[i][EW_order[2]]; \n }\n\n // Classify tension axis symmetry\n symmetry_around_tension = 1;\n clr = 1;\n xsum = EW1 + EW2 + EW3;\n // implosion\n if (EW1 < 0.0 && EW2 < 0.0 && EW3 < 0.0)\n {\n if (iverb > 2){printf(\"%s: Implosion\\n\", fcnm);}\n symmetry_around_tension = 0;\n clr = 1;\n }\n // explosion\n else if (EW1 > 0.0 && EW2 > 0.0 && EW3 > 0.0)\n {\n if (iverb > 2){printf(\"%s: Explosion\\n\", fcnm);}\n symmetry_around_tension = 1;\n if (fabs(EW1_devi) > fabs(EW3_devi))\n {\n symmetry_around_tension = 0;\n }\n clr = -1;\n }\n // net-implosion\n else if (EW2 < 0.0 && xsum < 0.0)\n {\n if (iverb > 2){printf(\"%s: Net-implosion (1)\\n\", fcnm);}\n if (fabs(EW1_devi) < fabs(EW3_devi))\n {\n symmetry_around_tension = 1;\n clr = 1; \n }\n else\n {\n symmetry_around_tension = 1;\n clr = 1;\n }\n }\n // net-implosion\n else if (EW2_devi >= 0.0 && xsum < 0.0)\n {\n if (iverb > 2){printf(\"%s: Net-impolosion (2)\\n\", fcnm);}\n symmetry_around_tension = 0;\n clr = -1;\n if (fabs(EW1_devi) < fabs(EW3_devi))\n {\n symmetry_around_tension = 1;\n clr = 1;\n }\n }\n // net-explosion\n else if (EW2_devi < 0.0 && xsum > 0.0)\n {\n if (iverb > 2){printf(\"%s: Net-explosion (1)\\n\", fcnm);}\n symmetry_around_tension = 1;\n clr = 1;\n if (fabs(EW1_devi) > fabs(EW3_devi))\n {\n symmetry_around_tension = 0;\n clr = -1;\n }\n }\n // net-explosion\n else if ( EW2_devi >= 0.0 && xsum > 0.0)\n {\n if (iverb > 2){printf(\"%s: Net-explosion (2)\\n\", fcnm);}\n symmetry_around_tension = 0;\n clr = -1;\n }\n else\n {\n // If the trace is 0 to machine epsilon then purely deviatoric\n if (trace_M/fmax(fabs(EW1_devi),fabs(EW3_devi)) > 1.e-10){ //!= 0.0){\n printf(\"%s: Warning should not be here %f %f %f\\n\",\n fcnm, EW2_devi, trace_M, xsum);\n }\n }\n if (iverb > 1)\n {\n printf(\"%s: sym/clr %d %d\\n\",\n fcnm, symmetry_around_tension, clr);\n }\n // Deviatoric classification\n if (fabs(EW1_devi) < fabs(EW3_devi))\n {\n symmetry_around_tension = 1;\n clr = 1;\n }\n if (fabs(EW1_devi) >= fabs(EW3_devi))\n {\n symmetry_around_tension = 0;\n clr = -1;\n }\n //explosive src with all neg evals? - TODO: email lars. an edge\n //case is (-1,-1,-1, 0,0,0) which has trace_M == 0.0 and is a pure\n //implosion. in this case there is a breakdown of the code because\n //trace_M == 0.0\n if (EW3 < 0.0 && trace_M > 0.0)\n {\n printf(\"%s: Critical error!\\n\", fcnm);\n return -1;\n }\n\n // Classify pure deviatoric - pure deviatoric\n if (trace_M == 0.0)\n {\n if (iverb > 1){printf(\"%s: Pure-deviatoric\\n\", fcnm);}\n // pure shear\n if (EW2 == 0.0)\n {\n if (iverb > 1){printf(\"%s: Pure-shear\\n\", fcnm);}\n symmetry_around_tension = 1;\n clr = 1;\n }\n else if (2.0*fabs(EW2) == fabs(EW1) || 2.0*fabs(EW2) == fabs(EW3))\n {\n if (iverb > 1){printf(\"%s: Pure CLVD\\n\", fcnm);}\n // CLVD symmetry around tension\n if (fabs(EW1) < EW3)\n {\n if (iverb > 2)\n {\n printf(\"%s: CLVD symmetry around tension\\n\", fcnm);\n }\n symmetry_around_tension = 1;\n clr = 1;\n }\n // CLVD symmetry around pressure\n else\n {\n if (iverb > 2)\n {\n printf(\"%s: CLVD symmetry around pressure\\n\", fcnm);\n }\n symmetry_around_tension = 0;\n clr = -1;\n }\n }\n // mix of DC and CLVD\n else\n {\n if (iverb > 1)\n {\n printf(\"%s: Mix of DC and CLVD\\n\", fcnm);\n }\n // symmetry around tension\n if (fabs(EW1) < EW3)\n {\n if (iverb > 2)\n {\n printf(\"%s: Symmetry around tension\\n\", fcnm);\n }\n symmetry_around_tension = 1;\n clr = 1;\n }\n // symmetry around pressure\n else\n {\n if (iverb > 2)\n {\n printf(\"%s: Symmetry around pressure\\n\", fcnm);\n }\n symmetry_around_tension = 0;\n clr = -1;\n }\n }\n }\n if (iverb > 0)\n {\n printf(\"%s: Final symmetry %d %d\\n\",\n fcnm, symmetry_around_tension, clr);\n }\n // Define order of eigenvectors and values according to symmetry axis\n if (symmetry_around_tension == 1)\n {\n EWs = EW3;\n EWh = EW1; \n EWn = EW2;\n for (i=0; i<3; i++)\n {\n EVs[i] = EV3[i];\n EVh[i] = EV1[i];\n EVn[i] = EV2[i];\n }\n }\n else\n {\n EWs = EW1;\n EWh = EW3;\n EWn = EW2;\n for (i=0; i<3; i++)\n {\n EVs[i] = EV1[i];\n EVh[i] = EV3[i];\n EVn[i] = EV2[i]; \n }\n }\n // Order of eigenvector's basis: (H,N,S)\n for (i=0; i<3; i++)\n {\n // Matrix for basis transform\n src->rotation_matrix[i][0] = EVh[i]; \n src->rotation_matrix[i][1] = EVn[i];\n src->rotation_matrix[i][2] = EVs[i]; \n // Save eigenvectors \n src->eigenvectors[i][0] = EVh[i];\n src->eigenvectors[i][1] = EVn[i];\n src->eigenvectors[i][2] = EVs[i];\n // Principal axis\n src->p_axis[i] = EV1[i]; //Smallest (most negative) eval/evec pair\n src->null_axis[i] = EVn[i]; //Intermediate eval/evec pair\n src->t_axis[i] = EV3[i]; //Largest (most positive) eval/evec pair \n /* TODO the above is definitionally correct but the following works. \n What's going on here? Did someone switch conventions on me? */\n //src->t_axis[i] = EV1[i];\n //src->null_axis[i] = EVn[i];\n //src->p_axis[i] = EV3[i];\n }\n src->eig_pnt[0] = EW1_devi; // Smallest - most negative eigenvalue\n src->eig_pnt[1] = EW2_devi;\n src->eig_pnt[2] = EW3_devi; // Largest eigenvalue\n // TODO - these are reversed to match above t_axis, null_axis, and p_axis\n //printf(\"%f %f\\n\", EW1_devi, EW3_devi);\n //src->eig_pnt[0] = EW3_devi; // Make pressure most positive eigenvalue?\n //src->eig_pnt[1] = EW2_devi;\n //src->eig_pnt[2] = EW1_devi; // Make tension most negative eigenvalue\n // Eigenvalues corresponding to eigenvectors (H,N,S) basis\n src->eigenvalues[0] = EWh;\n src->eigenvalues[1] = EWn;\n src->eigenvalues[2] = EWs;\n\n // Important for plot in BeachBall class (also used in FindFaultPlanes)\n src->plot_clr_order = clr;\n\n ierr = cmopad_findFaultPlanes(iverb, src);\n if (ierr != 0)\n {\n printf(\"%s: Error computing fault planes!\\n\", fcnm);\n }\n return ierr;\n}\n//============================================================================//\n/*! \n * @brief Prints a 3x3 matrix in a Mopad-esque style.\n *\n * @param[in] lfact if true then use a normalization factor\n * @param[in] m the 3x3 matrix to write to standard out\n * \n */\nvoid cmopad_printMatrix3x3(bool lfact, double m[3][3])\n{\n const char *fcnm = \"cmopad_printMatrix3x3\\0\";\n double norm_fact, m11,m22,m33,m12,m13,m23;\n int i,j;\n //------------------------------------------------------------------------//\n norm_fact = 1.0;\n if (lfact)\n {\n norm_fact = 0.0;\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n //norm_fact = fmax(norm_fact,fabs(mathRound(m[i][j],5)));\n norm_fact = fabs(m[i][j]);\n }\n }\n if (norm_fact == 0.0)\n {\n printf(\"%s: Warning norm_fact = 0.0!\\n\", fcnm);\n return;\n }\n }\n m11 = m[0][0]/norm_fact;\n m22 = m[1][1]/norm_fact;\n m33 = m[2][2]/norm_fact;\n m12 = m[0][1]/norm_fact; \n m13 = m[0][2]/norm_fact;\n m23 = m[1][2]/norm_fact; \n if (lfact)\n {\n printf(\" [ %5.2f %5.2f %5.2f ] \\n\",m11,m12,m13);\n printf(\" [ %5.2f %5.2f %5.2f ] x %f\\n\",\n m12,m22,m23,norm_fact);\n printf(\" [ %5.2f %5.2f %5.2f ] \\n\",m13,m23,m33);\n }\n else\n {\n printf(\" [ %5.2f %5.2f %5.2f ]\\n\",m11,m12,m13);\n printf(\" [ %5.2f %5.2f %5.2f ]\\n\",m12,m22,m23);\n printf(\" [ %5.2f %5.2f %5.2f ]\\n\",m13,m23,m33);\n }\n return;\n}\n//============================================================================//\n/*!\n * @brief Brings the provided mechanism into symmetric 3x3 matrix form.\n *\n * The source mechanism may be provided in different forms:\n *\n * -- as 3x3 matrix - symmetry is checked - one basis \n * system has to be chosen, or NED as default is taken\n * -- as 3-element tuple or array - interpreted as \n * strike, dip, slip-rake angles in degree\n * -- as 4-element tuple or array - interpreted as strike, dip, \n * slip-rake angles in degree + seismic scalar moment in Nm\n * -- as 6-element tuple or array - interpreted as the 6 independent \n * entries of the moment tensor\n * -- as 7-element tuple or array - interpreted as the 6 independent \n * entries of the moment tensor + seismic scalar moment in Nm\n * -- as 9-element tuple or array - interpreted as the 9 entries \n * of the moment tensor - checked for symmetry\n * -- as a nesting of one of the upper types (e.g. a list of \n * n-tuples) - first element of outer nesting is taken\n *\n */\nint cmopad_SetupMT(int nmech, double *mech, \n enum cmopad_basis_enum input_basisIn,\n double Mech_out[3][3])\n{\n const char *fcnm = \"cmopad_SetupMT\\0\";\n enum cmopad_basis_enum input_basis;\n double rotmat[9], mtemp1[9], mtemp2[9], m_unrot[9], scalar_moment, \n strike, dip, rake;\n int i, j, ierr;\n double pi180 = M_PI/180.0;\n double alpha = 1.0;\n double beta = 0.0;\n int n3 = 3;\n //------------------------------------------------------------------------//\n //\n // All 9 elements are specified\n input_basis = input_basisIn;\n if (nmech == 9)\n {\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n Mech_out[i][j] = mech[3*j + i];\n }\n }\n }\n // Mechanism given as 6 or 7 element array\n else if (nmech == 6 || nmech == 7)\n {\n scalar_moment = 1.0;\n if (nmech == 7){scalar_moment = mech[6];}\n Mech_out[0][0] = scalar_moment*mech[0];\n Mech_out[1][1] = scalar_moment*mech[1];\n Mech_out[2][2] = scalar_moment*mech[2];\n Mech_out[0][1] = Mech_out[1][0] = scalar_moment*mech[3];\n Mech_out[0][2] = Mech_out[2][0] = scalar_moment*mech[4];\n Mech_out[1][2] = Mech_out[2][1] = scalar_moment*mech[5];\n }\n // Strike dip rake; conventions from Jost and Herrmann; NED-basis\n else if (nmech == 3 || nmech == 4)\n {\n scalar_moment = 1.0;\n if (nmech == 4){scalar_moment = mech[3];}\n // Set matrix as function of Euler angles\n strike = mech[0]*pi180;\n dip = mech[1]*pi180;\n rake = mech[2]*pi180;\n cmopad_eulerToMatrix(dip, strike, -rake, Mech_out);\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n m_unrot[3*j + i] = 0.0;\n rotmat[3*j + i] = Mech_out[i][j];\n mtemp1[3*j + i] = 0.0;\n mtemp2[3*j + i] = 0.0;\n }\n }\n m_unrot[6] =-1.0;\n m_unrot[2] =-1.0;\n // Multiply trans(Rotmat)*m_unrot*Rotmat \n cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n3, n3, n3,\n alpha, rotmat, n3, m_unrot, n3, beta,\n mtemp1, n3);\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n3, n3, n3,\n alpha, rotmat, n3, mtemp1, n3, beta,\n mtemp2, n3);\n // Copy back and include scalar moment\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n Mech_out[i][j] = scalar_moment*mtemp2[3*j + i]; \n }\n }\n // Assure right basis system\n input_basis = NED;\n }\n // Unknown mechanism\n else\n {\n printf(\"%s: Invalid mechanism!\\n\", fcnm);\n return -1;\n }\n // Rotate into NED basis for local processing\n ierr = cmopad_basis_transformMatrixM33(Mech_out, input_basis, NED);\n if (ierr != 0)\n {\n printf(\"%s: Error transforming matrix\\n\", fcnm);\n return -1;\n }\n return 0;\n}\n//============================================================================//\n/*! \n * @brief Sorts eigenvalues/eigenvectors of a matrix into ascending order.\n * Optionally, can sort based on the absolute magnitude of eigenvalues\n *\n * @param[in] isabs if true then sort on absolute value of eigenvalues\n * \n * @param[in,out] e eigenvalues sorted in ascending order [3]\n * @param[in,out] ev corresponding eigenvectors sorted along with eigenvalues\n * [3 x 3]\n *\n * @result 0 indicates success\n *\n */\nint cmopad_sortEigenvAscending(bool isabs, double e[3], double ev[3][3])\n{\n const char *fcnm = \"cmopad_sortEigenvAscending\\0\";\n const int n = 3;\n double evwork[3][3], ework[3], esave[3];\n int iperm[3], i, ierr, j;\n ierr = 0;\n for (i=0; iM[i][j] = M[i][j];\n src->M_iso[i][j] = M_iso[i][j];\n src->M_devi[i][j] = M_devi[i][j];\n }\n }\n \n // Eigenvalues and eigenvectors\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n eigenvtot[i][j] = M_devi[i][j]; //I dont understand this\n eigenvdevi[i][j]= M_devi[i][j];\n }\n }\n ierr = __cmopad_Eigs3x3(eigenvtot, ival, eigenwtot);\n if (ierr != 0)\n {\n printf(\"%s: Error computing eigs (a)!\\n\",fcnm);\n return -1;\n } \n ierr = __cmopad_Eigs3x3(eigenvdevi, ival, eigenwdevi);\n if (ierr != 0)\n {\n printf(\"%s: Error computing eigs (b)!\\n\",fcnm);\n return -1;\n }\n\n // Eigenvalues in ascending order\n ierr = ierr + cmopad_sortEigenvAscending(true, eigenwtot , eigenvtot);\n ierr = ierr + cmopad_sortEigenvAscending(true, eigenwdevi, eigenvdevi);\n if (ierr != 0)\n {\n printf(\"%s: Error sorting eigenvalues/eigenvectors\\n\", fcnm);\n return -1;\n }\n\n /* TODO: Email Lars Krieger; confirm this is a mistake\n : Jost and Herrmann Eqn 19 \n M0_devi =-1.0;\n for (i=0; i<3; i++){\n M0_devi = fmax(M0_devi, fabs(eigenwdevi[i]));\n }\n */\n // Compute mangnitude (Jost and Herrmann Eqn 19 noting the eigenvalues are\n // in ascending order)\n M0_devi = 0.5*(fabs(eigenwdevi[1]) + fabs(eigenwdevi[2])); \n\n // Named according to Jost and Herrmann\n for (i=0; i<3; i++)\n {\n a1[i] = eigenvtot[i][0];\n a2[i] = eigenvtot[i][1];\n a3[i] = eigenvtot[i][2];\n }\n\n // If only isotropic part exists\n if (M0_devi < epsilon)\n {\n F = 0.5;\n }\n else\n {\n F =-eigenwdevi[0]/eigenwdevi[2]; \n }\n\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n a3out = a3[i]*a3[j];\n a2out = a2[i]*a2[j];\n a1out = a1[i]*a1[j];\n // Second term of eqn 37 Jost and Herrmann\n M_DC[i][j] = eigenwdevi[2]*(1.0 - 2.0*F)*(a3out - a2out);\n // Remainder of deviatoric is CLVD (could do 3rd term of eqn 37) \n lsub = 1;\n if (lsub == 1)\n {\n M_CLVD[i][j] = M_devi[i][j] - M_DC[i][j];\n }\n else\n {\n M_CLVD[i][j] = eigenwdevi[2]*F\n *(2.0*a3out - a2out - a1out);\n }\n }\n }\n\n //according to Bowers & Hudson:\n M0 = M0_iso + M0_devi;\n\n // Really shouldn't be rounding \n /* \n M_iso_percentage = mathRound(M0_iso/M0*100.0,6);\n //cmopad.iso_percentage = M_iso_percentage;\n M_DC_percentage = ( mathRound( (1.0 - 2.0*fabs(F))\n *(1.0 - M_iso_percentage/100.0)*100,6));\n */\n M_iso_percentage = M0_iso/M0*100.0;\n M_DC_percentage = (1.0 - 2.0*fabs(F))*(1.0 - M_iso_percentage/100.0)*100.0;\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n src->DC[i][j] = M_DC[i][j];\n src->CLVD[i][j] = M_CLVD[i][j];\n }\n }\n src->DC_percentage = M_DC_percentage;\n src->ISO_percentage = M_iso_percentage;\n src->DEV_percentage = 100.0 - src->ISO_percentage;\n src->CLVD_percentage = 100.0 - src->ISO_percentage - src->DC_percentage;\n ////src->seismic_moment = sqrt(1./2.0*(pow(eigenw[0],2) + pow(eigenw[0],2) + pow(eigenw[0],2))); \n src->seismic_moment = M0;\n src->moment_magnitude = log10(src->seismic_moment*1.0e7)/1.5 - 16.1/1.5;\n\n return 0;\n}\n//============================================================================//\n/*! \n * @brief Return 6-tuple containing entries of M, calculated from fault plane \n * angles (defined as in Jost&Herman), given in degrees.\n * Basis for output is NED (= X,Y,Z)\n *\n * @param[in] strike angle clockwise between north and plane (in [0,360])\n * @param[in] dip angle between surface and dipping plane (in [0,90]) \n * 0 = horizontal, 90 = vertical\n * @param[in] rake angle on the rupture plane between strike vector \n * and actual movement (defined mathematically \n * counter-clockwise rotation is positive)\n *\n * @param[out] moments M = {M_nn, M_ee, M_dd, M_ne, M_nd, M_ed}\n *\n */\nvoid cmopad_strikeDipRake2MT6(double strike, double dip, double rake,\n double moments[6])\n{\n double M1,M2,M3,M4,M5,M6;\n double S_rad = strike/rad2deg;\n double D_rad = dip/rad2deg;\n double R_rad = rake/rad2deg;\n //-------------------------------------------------------------------------//\n if (fabs(S_rad) < epsilon){S_rad = 0.0;}\n if (fabs(D_rad) < epsilon){D_rad = 0.0;}\n if (fabs(R_rad) < epsilon){R_rad = 0.0;}\n\n M1 =-( sin(D_rad)*cos(R_rad)*sin(2.0*S_rad) \n + sin(2.0*D_rad)*sin(R_rad)*pow(sin(S_rad),2) );\n M2 = ( sin(D_rad)*cos(R_rad)*sin(2.0*S_rad) \n - sin(2.0*D_rad)*sin(R_rad)*pow(cos(S_rad),2) );\n M3 = sin(2.0*D_rad)*sin(R_rad);\n M4 = sin(D_rad)*cos(R_rad)*cos(2.0*S_rad) \n + 0.5*sin(2.0*D_rad)*sin(R_rad)*sin(2.0*S_rad);\n M5 =-( cos(D_rad)*cos(R_rad)*cos(S_rad) \n + cos(2.0*D_rad)*sin(R_rad)*sin(S_rad) );\n M6 =-( cos(D_rad)*cos(R_rad)*sin(S_rad) \n - cos(2.0*D_rad)*sin(R_rad)*cos(S_rad));\n\n moments[0] = M1; \n moments[1] = M2; \n moments[2] = M3; \n moments[3] = M4; \n moments[4] = M5; \n moments[5] = M6;\n return;\n}\n//============================================================================//\n/*!\n * @brief Uniquify euler angle triplet.\n *\n * Puts euler angles into ranges compatible with (dip,strike,-rake) in\n * seismology:\n *\n * @param[in,out] alpha dip angle to put into range [0, pi/2]\n * @param[in,out] beta strike angle to put into range [0, 2*pi)\n * @param[in,out] gamma -rake angle to put into range [-pi, pi)\n *\n * @note If alpha is near to zero, beta is replaced by beta+gamma and gamma is\n * set to zero, to prevent that additional ambiguity.\n *\n * If alpha is near to pi/2, beta is put into the range [0,pi).\n *\n */\nvoid cmopad_uniqueEuler(double *alpha, double *beta, double *gamma)\n{\n const char *fcnm = \"cmopad_uniqueEuler\\0\";\n\n *alpha = numpy_mod(*alpha, 2.0*M_PI);\n\n if (0.5*M_PI < *alpha && *alpha <= M_PI)\n {\n *alpha = M_PI - *alpha;\n *beta = *beta + M_PI;\n *gamma = 2.0*M_PI - *gamma;\n }\n else if(M_PI < *alpha && *alpha <= 1.5*M_PI)\n {\n *alpha = *alpha - M_PI;\n *gamma = M_PI - *gamma;\n }\n else if(1.5*M_PI < *alpha && *alpha <= 2.0*M_PI)\n {\n *alpha = 2.0*M_PI - *alpha;\n *beta = *beta + M_PI;\n *gamma = M_PI + *gamma;\n }\n\n *alpha = numpy_mod(*alpha, 2.0*M_PI);\n *beta = numpy_mod(*beta, 2.0*M_PI);\n *gamma = numpy_mod(*gamma+M_PI, 2.0*M_PI) - M_PI;\n\n // If dip is exactly 90 degrees, one is still\n // free to choose between looking at the plane from either side.\n // Choose to look at such that beta is in the range [0,180)\n\n // This should prevent some problems, when dip is close to 90 degrees:\n if (fabs(*alpha - 0.5*M_PI) < 1e-10){*alpha = 0.5*M_PI;}\n if (fabs(*beta - M_PI) < 1e-10){*beta = M_PI;}\n if (fabs(*beta - 2.*M_PI) < 1e-10){*beta = 0.;}\n if (fabs(*beta) < 1e-10){*beta = 0.;}\n\n if ((fabs(*alpha - 0.5*M_PI) < 1.e-14) && *beta >= M_PI)\n {\n *gamma =-*gamma;\n *beta = numpy_mod(*beta-M_PI, 2.0*M_PI);\n *gamma = numpy_mod(*gamma+M_PI, 2.0*M_PI) - M_PI;\n if (!(0. <= *beta && *beta < M_PI))\n {\n printf(\"%s: Warning on bounds on beta!\", fcnm);\n }\n if (!(-M_PI <= *gamma && *gamma < M_PI))\n {\n printf(\"%s: Warning on bounds on gamma!\", fcnm);\n }\n }\n\n if (*alpha < 1e-7)\n {\n *beta = numpy_mod(*beta + *gamma, 2.0*M_PI);\n *gamma = 0.;\n }\n return;\n}\n//============================================================================//\n/*!\n * @brief Ascending argument sort for three numbers. For more information:\n * http://stackoverflow.com/questions/4367745/simpler-way-of-sorting-three-numbers\n *\n * @param[in] x array to sort into ascending[3]\n *\n * @param[out] iperm permutation such that x3[iperm[:]] is in ascending\n * order\n *\n */\nstatic int __cmopad_argsort3(double x[3], int iperm[3])\n{\n const char *fcnm = \"__cmopad_argsort3\\0\";\n int i, temp;\n const int a = 0;\n const int b = 1;\n const int c = 2;\n // Copy\n iperm[a] = a;\n iperm[b] = b;\n iperm[c] = c;\n if (x[iperm[a]] > x[iperm[c]])\n {\n temp = iperm[c];\n iperm[c] = iperm[a];\n iperm[a] = temp;\n }\n if (x[iperm[a]] > x[iperm[b]])\n {\n temp = iperm[b];\n iperm[b] = iperm[a];\n iperm[a] = temp;\n }\n //Now the smallest element is the first one. Just check the 2-nd and 3-rd\n if (x[iperm[b]] > x[iperm[c]])\n {\n temp = iperm[c];\n iperm[c] = iperm[b];\n iperm[b] = temp;\n }\n // Verify\n for (i=1; i<3; i++)\n {\n if (x[iperm[i-1]] > x[iperm[i]])\n {\n printf(\"%s: Failed to sort numbers in ascending order\\n\", fcnm);\n return -1;\n }\n }\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Determinant of a 3 x 3 matrix\n *\n * @result determinant of a 3 x 3 matrix\n *\n */\nstatic double __cmopad_determinant3x3(double A[3][3])\n{\n double determinant;\n determinant = A[0][0]*( A[1][1]*A[2][2] - A[1][2]*A[2][1]) \n - A[0][1]*( A[1][0]*A[2][2] - A[1][2]*A[2][0])\n + A[0][2]*( A[1][0]*A[2][1] - A[1][1]*A[2][0]);\n return determinant;\n}\n//============================================================================//\n/*!\n * @brief Computes the inverse of a 3 x 3 matrix\n *\n * @param[in,out] Amat on input the 3 x 3 matrix to invert.\n * on output the inverted matrix\n *\n * @result 0 indicates success\n *\n */\nstatic int __cmopad_inv3(double Amat[3][3])\n{\n const char *fcnm = \"__cmopad_inv3\\0\";\n double a11, a12, a13, a21, a22, a23, a31, a32, a33, detA, detAi;\n // Determinant of a\n detA = __cmopad_determinant3x3(Amat);\n if (detA == 0.0)\n {\n printf(\"%s: Error matrix is singular!\\n\", fcnm);\n return -1;\n }\n detAi = 1.0/detA;\n a11 = Amat[0][0]; a12 = Amat[0][1]; a13 = Amat[0][2];\n a21 = Amat[1][0]; a22 = Amat[1][1]; a23 = Amat[1][2];\n a31 = Amat[2][0]; a32 = Amat[2][1]; a33 = Amat[2][2];\n // Row 1\n Amat[0][0] = detAi*(a22*a33 - a32*a23);\n Amat[0][1] = detAi*(a13*a32 - a12*a33);\n Amat[0][2] = detAi*(a12*a23 - a13*a22);\n // Row 2\n Amat[1][0] = detAi*(a23*a31 - a21*a33);\n Amat[1][1] = detAi*(a11*a33 - a13*a31);\n Amat[1][2] = detAi*(a13*a21 - a11*a23);\n // Row 3\n Amat[2][0] = detAi*(a21*a32 - a22*a31);\n Amat[2][1] = detAi*(a12*a31 - a11*a32);\n Amat[2][2] = detAi*(a11*a22 - a12*a21); \n return 0;\n}\n//============================================================================//\n/*!\n * @brief Computes the trace (sum of diagonal) of a 3x3 matrix\n *\n * @param[in] M matrix of which to compute trace\n *\n * @result trace of matrix\n *\n */\nstatic double __cmopad_trace3(double M[3][3])\n{\n double trace;\n trace = M[0][0] + M[1][1] + M[2][2]; \n return trace;\n}\n//===========================================================================//\n/*! \n * @brief Calculates all eigenvalues and eigenvectors (job = 0) of a\n * symmetric 3 x 3 matrix using LAPACK. \n *\n * @param[in,out] a on input matrix of which to calculate eigenvalues\n * and optionally eigenvectors.\n * on output if the eigenvectors are desired they are\n * stored on a \n *\n * @param[in] job = 0 calculate eigenvectors, otherwise, just eigenvalues\n * \n * @param[out] eigs eigenvalues of matrix a [3]\n *\n * @result 0 indicates success\n * \n * @author B. Baker (ISTI)\n * @date April 2016\n */\nstatic int __cmopad_Eigs3x3(double a[3][3], int job, double eigs[3])\n{\n const char *fcnm = \"__cmopad_Eigs3x3\\0\";\n double avec[9];\n int n = 3;\n int i, j, indx, ierr;\n int lda = n;\n for (i = 0; i < n; i++)\n {\n for (j = i; j < n; j++)\n {\n // fill lower half\n if (i != j)\n {\n indx = i * lda + j;\n avec[indx] = a[j][i];\n }\n indx = j * lda + i;\n avec[indx] = a[i][j];\n }\n }\n // Calculate eigenvalues/eigenvectors\n if (job != 0)\n {\n ierr = LAPACKE_dsyev(LAPACK_COL_MAJOR, 'N', 'L', n, avec, lda, eigs);\n }\n else\n {\n ierr = LAPACKE_dsyev(LAPACK_COL_MAJOR, 'V', 'L', n, avec, lda, eigs);\n }\n if (ierr != 0)\n {\n printf(\"%s: Error computing eigenvalues\\n\", fcnm);\n ierr = 1;\n }\n // Copy eigenvectors back onto A\n if (job == 0 && ierr == 0)\n {\n indx = 0;\n for (j = 0; j < n; j++)\n {\n for (i = 0; i < n; i++)\n {\n indx = j * lda + i;\n a[i][j] = avec[indx];\n }\n }\n }\n return 0;\n}\n/*!\n * @brief Function for swapping to two numbers a, b\n *\n * @param[in,out] a on input a = a, on output a = b\n * @param[in,out] b on input b = b, on output b = a\n *\n */\nstatic void __cmopad_swap8(double *a, double *b)\n{\n double temp;\n temp = *a;\n *a = *b;\n *b = temp;\n return;\n}\n", "meta": {"hexsha": "fffe93dabcae2db33b27ed8f59be55e424960289", "size": 57857, "ext": "c", "lang": "C", "max_stars_repo_path": "c_src/unit_tests/cmopad.c", "max_stars_repo_name": "OUCyf/mtbeach", "max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z", "max_issues_repo_path": "c_src/unit_tests/cmopad.c", "max_issues_repo_name": "carltape/mtbeach", "max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z", "max_forks_repo_path": "c_src/unit_tests/cmopad.c", "max_forks_repo_name": "carltape/mtbeach", "max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z", "avg_line_length": 31.2571582928, "max_line_length": 103, "alphanum_fraction": 0.4963271514, "num_tokens": 18438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4269016340104356}} {"text": "#ifndef Single_Pin_Conduction_h\n#define Single_Pin_Conduction_h\n\n#include \n\n// Trilinos includes\n#include \"Teuchos_ParameterList.hpp\"\n#include \"Teuchos_RCP.hpp\"\n#include \"Teuchos_SerialDenseMatrix.hpp\"\n#include \"Teuchos_SerialDenseSolver.hpp\"\n#include \"Teuchos_SerialDenseVector.hpp\"\n\n// vendored includes\n#include \n\nnamespace enrico {\n\n//===========================================================================//\n/*!\n * \\class Single_Pin_Conduction\n * \\brief Solve thermal conduction in single fuel pin.\n *\n * This class implements a simple 1-D radial thermal conduction equation\n * for each axial level of a fuel pin. Axial conduction is ignored and there\n * is currently no gap conductance model. This model should only be used for\n * very approximate qualitative behavior.\n */\n//===========================================================================//\n\nclass Single_Pin_Conduction {\npublic:\n //@{\n //! Typedefs\n using RCP_PL = Teuchos::RCP;\n using Matrix = Teuchos::SerialDenseMatrix;\n using Vector = Teuchos::SerialDenseVector;\n using Solver = Teuchos::SerialDenseSolver;\n //@}\n\nprivate:\n // >>> DATA\n\n // Geometry\n double d_fuel_radius;\n double d_clad_radius;\n double d_delta_r_fuel;\n double d_delta_r_clad;\n std::vector d_delta_z;\n\n // Thermal conductivities\n double d_k_fuel;\n double d_k_clad;\n\npublic:\n // Constructor\n Single_Pin_Conduction(RCP_PL& parameters, const std::vector& delta_z);\n\n // Set fuel radius (cm)\n void set_fuel_radius(double r)\n {\n Expects(r > 0.0);\n Expects(r < 2.0);\n d_fuel_radius = r;\n }\n\n // Set clad radius (cm)\n void set_clad_radius(double r)\n {\n Expects(r > 0.0);\n Expects(r < 2.0);\n d_clad_radius = r;\n }\n\n // Solve conduction equation at each axial level\n void solve(const std::vector& power,\n const std::vector& channel_temperature,\n std::vector& fuel_temperature);\n};\n\n//---------------------------------------------------------------------------//\n} // end namespace enrico\n\n//---------------------------------------------------------------------------//\n#endif // Single_Pin_Conduction_h\n\n//---------------------------------------------------------------------------//\n// end of Single_Pin_Conduction.h\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "542c4c6c99c4b4d5beb26f0b9d4eb1f18dc7f8dc", "size": 2427, "ext": "h", "lang": "C", "max_stars_repo_path": "include/smrt/Single_Pin_Conduction.h", "max_stars_repo_name": "pshriwise/enrico", "max_stars_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/smrt/Single_Pin_Conduction.h", "max_issues_repo_name": "pshriwise/enrico", "max_issues_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smrt/Single_Pin_Conduction.h", "max_forks_repo_name": "pshriwise/enrico", "max_forks_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2696629213, "max_line_length": 80, "alphanum_fraction": 0.5760197775, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4268682198569925}} {"text": "/*\n * Copyright 2020 Makani Technologies LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef SIM_PHYSICS_ROTOR_DATABASE_H_\n#define SIM_PHYSICS_ROTOR_DATABASE_H_\n\n#include \n#include \n\n#include \n\n#include \"common/macros.h\"\n\nclass RotorDatabase {\n public:\n explicit RotorDatabase(const std::string &filename);\n virtual ~RotorDatabase();\n\n // Calculates the rotor's thrust [N], applied torque [N-m], or\n // generated power [W] based on the angular rate, freestream\n // velocity, and air density. Torque and power are defined to be\n // negative during thrusting.\n double CalcThrust(double angular_rate, double freestream_vel,\n double air_density) const;\n double CalcTorque(double angular_rate, double freestream_vel,\n double air_density) const;\n double CalcPower(double angular_rate, double freestream_vel,\n double air_density) const;\n\n // Looks-up the value of the rotor's thrust, torque, or power\n // coefficients [#] at a given angular rate and freestream velocity\n // in a 2-D look-up table. Values are interpolated linearly between\n // points and the inputs are saturated to the limits of the table.\n double LookupThrustCoeff(double angular_rate, double freestream_vel) const;\n double LookupTorqueCoeff(double angular_rate, double freestream_vel) const;\n double LookupPowerCoeff(double angular_rate, double freestream_vel) const;\n\n private:\n // Returns true if the rotor database follows our sign conventions:\n //\n // - Power coefficient decreases with increasing angular rate for\n // the low freestream velocity case, i.e. power is positive in\n // generation.\n //\n // - Thrust coefficient increases with increasing angular rate for\n // the low freestream velocity case.\n bool IsValid() const;\n\n // Diameter of the propeller [m].\n double diameter_;\n\n // Vector of angular rates [rad/s], which define the rows of the\n // look-up table.\n gsl_vector *angular_rates_;\n\n // Vector of freestream velocities [m/s], which define the columns\n // of the look-up table.\n gsl_vector *freestream_vels_;\n\n // Matrix of thrust coefficients [#] defined over a tensor grid of\n // freestream velocities and angular rates. The thrust coefficient\n // is defined as:\n //\n // thrust_coeff = thrust / (air_density * angular_rate_hz^2 * diameter^4)\n //\n // See Eq. 9.18, Houghton & Carpenter, 4th ed.\n gsl_matrix *thrust_coeffs_;\n\n // Matrix of power coefficients [#] defined over a tensor grid of\n // freestream velocities and angular rates. The power coefficient\n // is defined as:\n //\n // power_coeff = power / (air_density * angular_rate_hz^3 * diameter^5)\n //\n // See Eq. 9.22, Houghton & Carpenter, 4th ed.\n gsl_matrix *power_coeffs_;\n\n DISALLOW_COPY_AND_ASSIGN(RotorDatabase);\n};\n\n#endif // SIM_PHYSICS_ROTOR_DATABASE_H_\n", "meta": {"hexsha": "42c3bf91c5c31fc9aaea2e0bf7c11fc1cdf495bd", "size": 3393, "ext": "h", "lang": "C", "max_stars_repo_path": "sim/physics/rotor_database.h", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "sim/physics/rotor_database.h", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "sim/physics/rotor_database.h", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 35.7157894737, "max_line_length": 77, "alphanum_fraction": 0.7259062776, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.42670258471834704}} {"text": "/* BRAINS\n * (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling\n * Yan-Rong Li, liyanrong@ihep.ac.cn\n * Thu, Aug 4, 2016\n */\n\n/*!\n * \\file user_blr_model.c\n * \\brief allow users to define their own BLR models.\n * \n * User should provide: 1) number of parameters in 1D and 2D; \n * 2) struct for BLR model;\n * 3) function for setting parameter range\n * 4) function for calculating clouds' lag and weight in 1D\n * 5) function for calculating clouds' lag, velocity, and weight in 2D\n * 6) function for setting the parameter values used in simulation (if flag_dim<0)\n *\n * The following is an example. The users can make modification with their own BLR models.\n *\n */\n\n#include \n#include \"brains.h\"\n\nconst int num_params_MyBLRmodel1d = 8; /*!< number of parameters for 1D model */\nconst int num_params_MyBLRmodel2d = 17; /*!< number of parameters for 2D model */\n\n\n/*!\n * set parameter range\n */\nvoid set_blr_range_mymodel()\n{\n int i;\n \n i = 0;\n //mu\n blr_range_model[i][0] = log(0.1);\n blr_range_model[i++][1] = log(rcloud_max_set*0.5);\n //beta\n blr_range_model[i][0] = 0.001;\n blr_range_model[i++][1] = 2.0;\n //F\n blr_range_model[i][0] = 0.0;\n blr_range_model[i++][1] = 1.0;\n //inc\n blr_range_model[i][0] = 0.0; //in cosine\n blr_range_model[i++][1] = 1.0;\n //opn\n blr_range_model[i][0] = 0.0; // in rad\n blr_range_model[i++][1] = 90.0;\n //k\n blr_range_model[i][0] = -0.5;\n blr_range_model[i++][1] = 0.5;\n //gamma\n blr_range_model[i][0] = 1.0;\n blr_range_model[i++][1] = 5.0;\n //xi\n blr_range_model[i][0] = 0.0;\n blr_range_model[i++][1] = 1.0;\n //mbh\n blr_range_model[i][0] = log(0.1);\n blr_range_model[i++][1] = log(1.0e3);\n //fellip\n blr_range_model[i][0] = 0.0;\n blr_range_model[i++][1] = 1.0;\n //fflow\n blr_range_model[i][0] = 0.0;\n blr_range_model[i++][1] = 1.0;\n //sigr_circ\n blr_range_model[i][0] = log(0.001);\n blr_range_model[i++][1] = log(0.1);\n //sigthe_circ\n blr_range_model[i][0] = log(0.001);\n blr_range_model[i++][1] = log(1.0);\n //sigr_rad\n blr_range_model[i][0] = log(0.001);\n blr_range_model[i++][1] = log(0.1);\n //sigthe_rad\n blr_range_model[i][0] = log(0.001);\n blr_range_model[i++][1] = log(1.0);\n //theta_rot\n blr_range_model[i][0] = 0.0;\n blr_range_model[i++][1] = 90.0;\n //sig_turb\n blr_range_model[i][0] = log(0.0001);\n blr_range_model[i++][1] = log(0.1);\n\n return;\n}\n\n/* \n * This function caclulate 2d transfer function.\n *\n * The clouds' lag, velocity, and weight are stored in arrays \"clouds_tau\", \"clouds_vel\", \"clouds_weight\",\n * which must be provided.\n */\nvoid gen_cloud_sample_mymodel(const void *pm, int flag_type, int flag_save)\n{\n int i, j, nc;\n double r, phi, cos_phi, sin_phi, dis, Lopn_cos;\n double x, y, z, xb, yb, zb, zb0, vx, vy, vz, vxb, vyb, vzb;\n double V, rhoV, theV, Vr, Vph, Vkep, Rs, g;\n double inc, F, beta, mu, k, gam, xi, a, s, sig, rin;\n double mbh, fellip, fflow, sigr_circ, sigthe_circ, sigr_rad, sigthe_rad, theta_rot, sig_turb;\n double Lphi, Lthe, sin_Lphi, cos_Lphi, sin_Lthe, cos_Lthe, sin_inc_cmp, cos_inc_cmp;\n double weight, rnd, rnd_xi;\n MyBLRmodel *model = (MyBLRmodel *)pm;\n\n Lopn_cos = cos(model->opn*PI/180.0); /* cosine of openning angle */\n inc = acos(model->inc); /* inclination angle in rad */\n beta = model->beta; \n F = model->F;\n mu = exp(model->mu); /* mean radius */\n k = model->k; \n gam = model-> gam;\n xi = model->xi;\n\n mbh = exp(model->mbh);\n fellip = model->fellip;\n fflow = model->fflow;\n sigr_circ = exp(model->sigr_circ);\n sigthe_circ = exp(model->sigthe_circ);\n sigr_rad = exp(model->sigr_rad);\n sigthe_rad = exp(model->sigthe_rad);\n theta_rot = model->theta_rot*PI/180.0;\n sig_turb = exp(model->sig_turb);\n\n Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days\n\n a = 1.0/beta/beta;\n s = mu/a;\n rin=mu*F + Rs; // include Scharzschild radius\n sig=(1.0-F)*s;\n \n sin_inc_cmp = cos(inc); //sin(PI/2.0 - inc);\n cos_inc_cmp = sin(inc); //cos(PI/2.0 - inc);\n \n for(i=0; ircloud_max_set || r 1000)\n {\n printf(\"# Error, too many tries in generating ridial location of clouds.\\n\");\n exit(0);\n }\n rnd = gsl_ran_gamma(gsl_r, a, 1.0);\n// r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu);\n r = rin + sig * rnd;\n nc++;\n }\n phi = 2.0*PI * gsl_rng_uniform(gsl_r);\n cos_phi = cos(phi);\n sin_phi = sin(phi);\n\n /* Polar coordinates to Cartesian coordinate */\n x = r * cos_phi; \n y = r * sin_phi;\n z = 0.0;\n\n/* right-handed framework\n * first rotate around y axis by an angle of Lthe, then rotate around z axis \n * by an angle of Lphi\n */\n /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z;\n yb =-cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z;\n zb = sin(Lthe) * x + cos(Lthe) * z; */\n \n xb = cos_Lthe*cos_Lphi * x + sin_Lphi * y;\n yb =-cos_Lthe*sin_Lphi * x + cos_Lphi * y;\n zb = sin_Lthe * x;\n\n zb0 = zb;\n rnd_xi = gsl_rng_uniform(gsl_r);\n if( (rnd_xi < 1.0 - xi) && zb0 < 0.0)\n zb = -zb;\n\n// counter-rotate around y, LOS is x-axis \n /* x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc);\n y = yb;\n z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc); */\n \n x = xb * cos_inc_cmp + zb * sin_inc_cmp;\n y = yb;\n z =-xb * sin_inc_cmp + zb * cos_inc_cmp;\n\n weight = 0.5 + k*(x/r);\n clouds_weight[i] = weight;\n\n#ifndef SA\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_type == 1)\n {\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n }\n#else\n switch(flag_type) \n {\n case 1: /* 1D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n break;\n \n case 2: /* 2D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n break;\n\n case 3: /* SA */\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 4: /* 1D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 5: /* 2D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n }\n \n#endif\n\n Vkep = sqrt(mbh/r);\n \n for(j=0; j= C_Unit) // make sure that the velocity is smaller than speed of light\n V = 0.9999*C_Unit * (V>0.0?1.0:-1.0);\n\n g = sqrt( (1.0 + V/C_Unit) / (1.0 - V/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects\n V = (g-1.0)*C_Unit;\n\n clouds_vel[i*parset.n_vel_per_cloud + j] = V;\n\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight);\n }\n }\n }\n\n return;\n}\n\n/*!\n * set parameter values used in simulation (if flag_dim < 0).\n */\nvoid set_par_value_mymodel_sim(double *pm)\n{\n int i;\n\n\ti=0;\n pm[i++] = log(4.0); // mu\n pm[i++] = 1.0; // beta\n pm[i++] = 0.25; // F\n pm[i++] = cos(20.0/180.0*PI); // inc\n pm[i++] = 40.0; // opn\n pm[i++] = -0.4; // kappa\n pm[i++] = 5.0; // gamma\n pm[i++] = 0.5; // obscuration\n pm[i++] = log(2.0); //mbh\n pm[i++] = 0.5; //fellip\n pm[i++] = 0.4; //fflow\n pm[i++] = log(0.01); //\n pm[i++] = log(0.1); //\n pm[i++] = log(0.01); //\n pm[i++] = log(0.1); //\n pm[i++] = 0.0; // theta_rot\n pm[i++] = log(0.001); // sig_turb\n pm[i++] = 0.0; // parameter for spectral broadening \n}\n\n#ifdef SA\n/*!\n * set parameter range\n */\nvoid set_sa_blr_range_mymodel()\n{\n int i;\n \n i = 0;\n //mu\n sa_blr_range_model[i][0] = log(0.1);\n sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5);\n //beta\n sa_blr_range_model[i][0] = 0.001;\n sa_blr_range_model[i++][1] = 2.0;\n //F\n sa_blr_range_model[i][0] = 0.0;\n sa_blr_range_model[i++][1] = 1.0;\n //inc\n sa_blr_range_model[i][0] = 0.0; //in cosine\n sa_blr_range_model[i++][1] = 1.0;\n //opn\n sa_blr_range_model[i][0] = 0.0; // in rad\n sa_blr_range_model[i++][1] = 90.0;\n //k\n sa_blr_range_model[i][0] = -0.5;\n sa_blr_range_model[i++][1] = 0.5;\n //gamma\n sa_blr_range_model[i][0] = 1.0;\n sa_blr_range_model[i++][1] = 5.0;\n //xi\n sa_blr_range_model[i][0] = 0.0;\n sa_blr_range_model[i++][1] = 1.0;\n \n //mbh\n sa_blr_range_model[i][0] = log(0.1);\n sa_blr_range_model[i++][1] = log(1.0e3);\n //fellip\n sa_blr_range_model[i][0] = 0.0;\n sa_blr_range_model[i++][1] = 1.0;\n //fflow\n sa_blr_range_model[i][0] = 0.0;\n sa_blr_range_model[i++][1] = 1.0;\n //sigr_circ\n sa_blr_range_model[i][0] = log(0.001);\n sa_blr_range_model[i++][1] = log(0.1);\n //sigthe_circ\n sa_blr_range_model[i][0] = log(0.001);\n sa_blr_range_model[i++][1] = log(1.0);\n //sigr_rad\n sa_blr_range_model[i][0] = log(0.001);\n sa_blr_range_model[i++][1] = log(0.1);\n //sigthe_rad\n sa_blr_range_model[i][0] = log(0.001);\n sa_blr_range_model[i++][1] = log(1.0);\n //theta_rot\n sa_blr_range_model[i][0] = 0.0;\n sa_blr_range_model[i++][1] = 90.0;\n //sig_turb\n sa_blr_range_model[i][0] = log(0.0001);\n sa_blr_range_model[i++][1] = log(0.1);\n \n return;\n}\n\n/*!\n * set parameter values used in simulation (if flag_dim < 0).\n */\nvoid set_sa_par_value_mymodel_sim(double *pm)\n{\n int i;\n\n\ti=0;\n pm[i++] = log(4.0); // mu\n pm[i++] = 1.0; // beta\n pm[i++] = 0.25; // F\n pm[i++] = cos(20.0/180.0*PI); // inc\n pm[i++] = 40.0; // opn\n pm[i++] = -0.4; // kappa\n pm[i++] = 5.0; // gamma\n pm[i++] = 0.5; // obscuration\n pm[i++] = log(2.0); //mbh\n pm[i++] = 0.5; //fellip\n pm[i++] = 0.4; //fflow\n pm[i++] = log(0.01); //\n pm[i++] = log(0.1); //\n pm[i++] = log(0.01); //\n pm[i++] = log(0.1); //\n pm[i++] = 0.0; // theta_rot\n pm[i++] = log(0.001); // sig_turb\n pm[i++] = 0.0; // parameter for spectral broadening \n}\n#endif\n", "meta": {"hexsha": "d2fba4a232de79a917e42263578ac23e60bcff9a", "size": 12433, "ext": "c", "lang": "C", "max_stars_repo_path": "src/user_blr_model.c", "max_stars_repo_name": "yzxamos/BRAINS", "max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/user_blr_model.c", "max_issues_repo_name": "yzxamos/BRAINS", "max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/user_blr_model.c", "max_forks_repo_name": "yzxamos/BRAINS", "max_forks_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4459161148, "max_line_length": 115, "alphanum_fraction": 0.5519987131, "num_tokens": 4756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4260825718880456}} {"text": "/* rng/rand48.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n/* This is the Unix rand48() generator. The generator returns the\n upper 32 bits from each term of the sequence,\n\n x_{n+1} = (a x_n + c) mod m \n\n using 48-bit unsigned arithmetic, with a = 0x5DEECE66D , c = 0xB\n and m = 2^48. The seed specifies the upper 32 bits of the initial\n value, x_1, with the lower 16 bits set to 0x330E.\n\n The theoretical value of x_{10001} is 244131582646046.\n\n The period of this generator is ? FIXME (probably around 2^48). */\n\nstatic inline void rand48_advance (void *vstate);\nstatic unsigned long int rand48_get (void *vstate);\nstatic double rand48_get_double (void *vstate);\nstatic void rand48_set (void *state, unsigned long int s);\n\nstatic const unsigned short int a0 = 0xE66D ;\nstatic const unsigned short int a1 = 0xDEEC ;\nstatic const unsigned short int a2 = 0x0005 ;\n\nstatic const unsigned short int c0 = 0x000B ;\n\ntypedef struct\n {\n unsigned short int x0, x1, x2;\n }\nrand48_state_t;\n\nstatic inline void\nrand48_advance (void *vstate)\n{\n rand48_state_t *state = (rand48_state_t *) vstate;\n\n /* work with unsigned long ints throughout to get correct integer\n promotions of any unsigned short ints */\n\n const unsigned long int x0 = (unsigned long int) state->x0 ;\n const unsigned long int x1 = (unsigned long int) state->x1 ;\n const unsigned long int x2 = (unsigned long int) state->x2 ;\n\n unsigned long int a ;\n \n a = a0 * x0 + c0 ;\n state->x0 = (a & 0xFFFF) ;\n \n a >>= 16 ;\n\n /* although the next line may overflow we only need the top 16 bits\n in the following stage, so it does not matter */\n\n a += a0 * x1 + a1 * x0 ; \n state->x1 = (a & 0xFFFF) ;\n\n a >>= 16 ;\n a += a0 * x2 + a1 * x1 + a2 * x0 ;\n state->x2 = (a & 0xFFFF) ;\n}\n\nstatic unsigned long int \nrand48_get (void *vstate)\n{\n unsigned long int x1, x2;\n\n rand48_state_t *state = (rand48_state_t *) vstate;\n rand48_advance (state) ;\n\n x2 = (unsigned long int) state->x2;\n x1 = (unsigned long int) state->x1;\n\n return (x2 << 16) + x1;\n}\n\nstatic double\nrand48_get_double (void * vstate)\n{\n rand48_state_t *state = (rand48_state_t *) vstate;\n\n rand48_advance (state) ; \n\n return (ldexp((double) state->x2, -16)\n + ldexp((double) state->x1, -32) \n + ldexp((double) state->x0, -48)) ;\n}\n\nstatic void\nrand48_set (void *vstate, unsigned long int s)\n{\n rand48_state_t *state = (rand48_state_t *) vstate;\n\n if (s == 0) /* default seed */\n {\n state->x0 = 0x330E ;\n state->x1 = 0xABCD ;\n state->x2 = 0x1234 ;\n }\n else \n {\n state->x0 = 0x330E ;\n state->x1 = s & 0xFFFF ;\n state->x2 = (s >> 16) & 0xFFFF ;\n }\n\n return;\n}\n\nstatic const gsl_rng_type rand48_type =\n{\"rand48\", /* name */\n 0xffffffffUL, /* RAND_MAX */\n 0, /* RAND_MIN */\n sizeof (rand48_state_t),\n &rand48_set,\n &rand48_get,\n &rand48_get_double\n};\n\nconst gsl_rng_type *gsl_rng_rand48 = &rand48_type;\n", "meta": {"hexsha": "f01a351f0210a6c9298cd7d3100e6190ee2e2e32", "size": 3857, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/rng/rand48.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/rng/rand48.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/rng/rand48.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 26.7847222222, "max_line_length": 81, "alphanum_fraction": 0.6593207156, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4258868953910294}} {"text": "#include \"coneOS.h\"\n#include \n#include \n\n\n// x = b*a\ninline void setAsScaledArray(double *x, const double * a,const double b,int len) {\n int i;\n for( i=0;i max) max = tmp;\n\t}\n\treturn max;\n}\n\n// ||v||_2^2\ninline double calcNormSq(const double * v,int len){\n double nrm = calcNorm(v,len);\n return nrm*nrm;\n}\n\n// daxpy a += sc*b\ninline void addScaledArray(double * a, const double * b, int n, const double sc){\n //b_daxpy(n, sc, b, 1, a, 1);\n cblas_daxpy(n, sc, b, 1, a, 1);\n}\n\ninline double calcNormDiff(const double *a,const double *b, int l) {\n double nmDiff = 0.0, tmp;\n int i;\n for ( i=0; i max) max = tmp;\n\t}\n\treturn max;\n}\n\ninline void accumByAtrans(Data * d, const double *x, double *y) \n{\n\tcblas_dgemv(CblasColMajor, CblasTrans, d->m, d->n, 1.0, d->Ax, d->m, x, 1, 1.0, y, 1);\n}\n\ninline void accumByA(Data * d, const double *x, double *y) \n{\n \tcblas_dgemv(CblasColMajor, CblasNoTrans, d->m, d->n, 1.0, d->Ax, d->m, x, 1, 1.0, y, 1);\n}\n\n/*\n\ninline void b_daxpy(const int n, const double alpha, const double *x, const int incx, double *y, const int incy)\n{\n daxpy(&n,&alpha,x,&incx,y,&incy);\n //cblas_daxpy(n,alpha,x,incx,y,incy);\n}\n\ninline void b_dsyr(char Uplo, const int N, const double alpha, const double *X, const int incX, double *A, const int lda)\n{\n //dsyr(&Uplo,&N,&alpha,X,&incX,A,&lda);\n cblas_dsyr(CblasColMajor, Uplo, N, alpha, X, incX, A, lda);\n}\n\ninline void b_dscal(const int N, const double alpha, double *X, const int incX)\n{\n //dscal(&N,&alpha,X,&incX);\n cblas_dscal(N,alpha,X,incX);\n}\n\ninline double b_ddot(const int n, const double *x, const int incx, const double *y, const int incy)\n{\n //return ddot(&n,x,&incx,y,&incy);\n return cblas_ddot(n,x,incx,y,incy);\n}\n\ninline double b_dnrm2(const int N, const double *X, const int incX)\n{\n return cblas_dnrm2(N,X,incX);\n //return dnrm2(&N,X,&incX);\n}\n\ninline void b_dgemm(\n char TransA,\n char TransB, \n const int M, \n const int N,\n const int K,\n const double alpha, \n const double *A, \n const int lda, \n const double *B, \n const int ldb, \n const double beta, \n double *C, \n const int ldc){\n dgemm(&TransA, &TransB, &M, &N, &K,&alpha,A,&lda,B,&ldb,&beta,C,&ldc);\n //cblas_dgemm();\n}\n\ninline void b_dgemv(char Trans, \n const int m,\n const int n,\n const double alpha, \n const double *a, \n const int lda, \n const double *x,\n const int incx, \n const double beta, \n double *y, \n const int incy){\n dgemv(&Trans,&m,&n,&alpha,a,&lda,x,&incx,&beta,y,&incy);\n}\n\ninline void b_dtrsv(char Uplo, char TransA, char Diag, const int N, const double *A, const int lda, double *X, const int incX)\n{\n dtrsv(&Uplo, &TransA, &Diag, &N, A, &lda, X, &incX);\n}\n\ninline void b_dsymv(char Uplo, const int N, const double alpha, const double *A, \n const int lda, const double *X, const int incX, const double beta,\n double *Y, const int incY){\n dsymv(&Uplo, &N, &alpha, A, &lda, X, &incX, beta, Y, &incY);\n}\n\n*/\n", "meta": {"hexsha": "ed5f27ba056a3b3bb5045211afe875d21676ff3b", "size": 4119, "ext": "c", "lang": "C", "max_stars_repo_path": "coneOSdense/linAlg.c", "max_stars_repo_name": "cvxgrp/coneos", "max_stars_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-29T07:42:29.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-29T07:42:29.000Z", "max_issues_repo_path": "coneOSdense/linAlg.c", "max_issues_repo_name": "cvxgrp/coneos", "max_issues_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coneOSdense/linAlg.c", "max_forks_repo_name": "cvxgrp/coneos", "max_forks_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T23:10:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-20T19:38:22.000Z", "avg_line_length": 26.0696202532, "max_line_length": 126, "alphanum_fraction": 0.571255159, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.42588689539102936}} {"text": "/* eigen/schur.c\n * \n * Copyright (C) 2006 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"schur.h\"\n\n/*\n * This module contains some routines related to manipulating the\n * Schur form of a matrix which are needed by the eigenvalue solvers\n *\n * This file contains routines based on original code from LAPACK\n * which is distributed under the modified BSD license. The LAPACK\n * routine used is DLANV2.\n */\n\nstatic inline void schur_standard_form(gsl_matrix *A, gsl_complex *eval1,\n gsl_complex *eval2, double *cs,\n double *sn);\n\n/*\ngsl_schur_standardize()\n Wrapper function for schur_standard_form - convert a 2-by-2 eigenvalue\nblock to standard form and then update the Schur form and\nSchur vectors.\n\nInputs: T - Schur form\n row - row of T of 2-by-2 block to be updated\n eval1 - where to store eigenvalue 1\n eval2 - where to store eigenvalue 2\n update_t - 1 = update the entire matrix T with the transformation\n 0 = do not update rest of T\n Z - (optional) if non-null, accumulate transformation\n*/\n\nvoid\ngsl_schur_standardize(gsl_matrix *T, size_t row, gsl_complex *eval1,\n gsl_complex *eval2, int update_t, gsl_matrix *Z)\n{\n const size_t N = T->size1;\n gsl_matrix_view m;\n double cs, sn;\n\n m = gsl_matrix_submatrix(T, row, row, 2, 2);\n schur_standard_form(&m.matrix, eval1, eval2, &cs, &sn);\n\n if (update_t)\n {\n gsl_vector_view xv, yv, v;\n\n /*\n * The above call to schur_standard_form transformed a 2-by-2 block\n * of T into upper triangular form via the transformation\n *\n * U = [ CS -SN ]\n * [ SN CS ]\n *\n * The original matrix T was\n *\n * T = [ T_{11} | T_{12} | T_{13} ]\n * [ 0* | A | T_{23} ]\n * [ 0 | 0* | T_{33} ]\n *\n * where 0* indicates all zeros except for possibly\n * one subdiagonal element next to A.\n *\n * After schur_standard_form, T looks like this:\n *\n * T = [ T_{11} | T_{12} | T_{13} ]\n * [ 0* | U^t A U | T_{23} ]\n * [ 0 | 0* | T_{33} ]\n *\n * since only the 2-by-2 block of A was changed. However,\n * in order to be able to back transform T at the end,\n * we need to apply the U transformation to the rest\n * of the matrix T since there is no way to apply a\n * similarity transformation to T and change only the\n * middle 2-by-2 block. In other words, let\n *\n * M = [ I 0 0 ]\n * [ 0 U 0 ]\n * [ 0 0 I ]\n *\n * and compute\n *\n * M^t T M = [ T_{11} | T_{12} U | T_{13} ]\n * [ U^t 0* | U^t A U | U^t T_{23} ]\n * [ 0 | 0* U | T_{33} ]\n *\n * So basically we need to apply the transformation U\n * to the i x 2 matrix T_{12} and the 2 x (n - i + 2)\n * matrix T_{23}, where i is the index of the top of A\n * in T.\n *\n * The BLAS routine drot() is suited for this.\n */\n\n if (row < (N - 2))\n {\n /* transform the 2 rows of T_{23} */\n\n v = gsl_matrix_row(T, row);\n xv = gsl_vector_subvector(&v.vector,\n row + 2,\n N - row - 2);\n\n v = gsl_matrix_row(T, row + 1);\n yv = gsl_vector_subvector(&v.vector,\n row + 2,\n N - row - 2);\n\n gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);\n }\n\n if (row > 0)\n {\n /* transform the 2 columns of T_{12} */\n\n v = gsl_matrix_column(T, row);\n xv = gsl_vector_subvector(&v.vector,\n 0,\n row);\n\n v = gsl_matrix_column(T, row + 1);\n yv = gsl_vector_subvector(&v.vector,\n 0,\n row);\n\n gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);\n }\n } /* if (update_t) */\n\n if (Z)\n {\n gsl_vector_view xv, yv;\n\n /*\n * Accumulate the transformation in Z. Here, Z -> Z * M\n *\n * So:\n *\n * Z -> [ Z_{11} | Z_{12} U | Z_{13} ]\n * [ Z_{21} | Z_{22} U | Z_{23} ]\n * [ Z_{31} | Z_{32} U | Z_{33} ]\n *\n * So we just need to apply drot() to the 2 columns\n * starting at index 'row'\n */\n\n xv = gsl_matrix_column(Z, row);\n yv = gsl_matrix_column(Z, row + 1);\n\n gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);\n } /* if (Z) */\n} /* gsl_schur_standardize() */\n\n/*******************************************************\n * INTERNAL ROUTINES *\n *******************************************************/\n\n/*\nschur_standard_form()\n Compute the Schur factorization of a real 2-by-2 matrix in\nstandard form:\n\n[ A B ] = [ CS -SN ] [ T11 T12 ] [ CS SN ]\n[ C D ] [ SN CS ] [ T21 T22 ] [-SN CS ]\n\nwhere either:\n1) T21 = 0 so that T11 and T22 are real eigenvalues of the matrix, or\n2) T11 = T22 and T21*T12 < 0, so that T11 +/- sqrt(|T21*T12|) are\n complex conjugate eigenvalues\n\nInputs: A - 2-by-2 matrix\n eval1 - where to store eigenvalue 1\n eval2 - where to store eigenvalue 2\n cs - where to store cosine parameter of rotation matrix\n sn - where to store sine parameter of rotation matrix\n\nNotes: based on LAPACK routine DLANV2\n*/\n\nstatic inline void\nschur_standard_form(gsl_matrix *A, gsl_complex *eval1, gsl_complex *eval2,\n double *cs, double *sn)\n{\n double a, b, c, d; /* input matrix values */\n double tmp;\n double p, z;\n double bcmax, bcmis, scale;\n double tau, sigma;\n double cs1, sn1;\n double aa, bb, cc, dd;\n double sab, sac;\n\n a = gsl_matrix_get(A, 0, 0);\n b = gsl_matrix_get(A, 0, 1);\n c = gsl_matrix_get(A, 1, 0);\n d = gsl_matrix_get(A, 1, 1);\n\n if (c == 0.0)\n {\n /*\n * matrix is already upper triangular - set rotation matrix\n * to the identity\n */\n *cs = 1.0;\n *sn = 0.0;\n }\n else if (b == 0.0)\n {\n /* swap rows and columns to make it upper triangular */\n\n *cs = 0.0;\n *sn = 1.0;\n\n tmp = d;\n d = a;\n a = tmp;\n b = -c;\n c = 0.0;\n }\n else if (((a - d) == 0.0) && (GSL_SIGN(b) != GSL_SIGN(c)))\n {\n /* the matrix has complex eigenvalues with a == d */\n *cs = 1.0;\n *sn = 0.0;\n }\n else\n {\n tmp = a - d;\n p = 0.5 * tmp;\n bcmax = GSL_MAX(fabs(b), fabs(c));\n bcmis = GSL_MIN(fabs(b), fabs(c)) * GSL_SIGN(b) * GSL_SIGN(c);\n scale = GSL_MAX(fabs(p), bcmax);\n z = (p / scale) * p + (bcmax / scale) * bcmis;\n\n if (z >= 4.0 * GSL_DBL_EPSILON)\n {\n /* real eigenvalues, compute a and d */\n\n z = p + GSL_SIGN(p) * fabs(sqrt(scale) * sqrt(z));\n a = d + z;\n d -= (bcmax / z) * bcmis;\n\n /* compute b and the rotation matrix */\n\n tau = gsl_hypot(c, z);\n *cs = z / tau;\n *sn = c / tau;\n b -= c;\n c = 0.0;\n }\n else\n {\n /*\n * complex eigenvalues, or real (almost) equal eigenvalues -\n * make diagonal elements equal\n */\n\n sigma = b + c;\n tau = gsl_hypot(sigma, tmp);\n *cs = sqrt(0.5 * (1.0 + fabs(sigma) / tau));\n *sn = -(p / (tau * (*cs))) * GSL_SIGN(sigma);\n\n /*\n * Compute [ AA BB ] = [ A B ] [ CS -SN ]\n * [ CC DD ] [ C D ] [ SN CS ]\n */\n aa = a * (*cs) + b * (*sn);\n bb = -a * (*sn) + b * (*cs);\n cc = c * (*cs) + d * (*sn);\n dd = -c * (*sn) + d * (*cs);\n\n /*\n * Compute [ A B ] = [ CS SN ] [ AA BB ]\n * [ C D ] [-SN CS ] [ CC DD ]\n */\n a = aa * (*cs) + cc * (*sn);\n b = bb * (*cs) + dd * (*sn);\n c = -aa * (*sn) + cc * (*cs);\n d = -bb * (*sn) + dd * (*cs);\n\n tmp = 0.5 * (a + d);\n a = d = tmp;\n\n if (c != 0.0)\n {\n if (b != 0.0)\n {\n if (GSL_SIGN(b) == GSL_SIGN(c))\n {\n /*\n * real eigenvalues: reduce to upper triangular\n * form\n */\n sab = sqrt(fabs(b));\n sac = sqrt(fabs(c));\n p = GSL_SIGN(c) * fabs(sab * sac);\n tau = 1.0 / sqrt(fabs(b + c));\n a = tmp + p;\n d = tmp - p;\n b -= c;\n c = 0.0;\n\n cs1 = sab * tau;\n sn1 = sac * tau;\n tmp = (*cs) * cs1 - (*sn) * sn1;\n *sn = (*cs) * sn1 + (*sn) * cs1;\n *cs = tmp;\n }\n }\n else\n {\n b = -c;\n c = 0.0;\n tmp = *cs;\n *cs = -(*sn);\n *sn = tmp;\n }\n }\n }\n }\n\n /* set eigenvalues */\n\n GSL_SET_REAL(eval1, a);\n GSL_SET_REAL(eval2, d);\n if (c == 0.0)\n {\n GSL_SET_IMAG(eval1, 0.0);\n GSL_SET_IMAG(eval2, 0.0);\n }\n else\n {\n tmp = sqrt(fabs(b) * fabs(c));\n GSL_SET_IMAG(eval1, tmp);\n GSL_SET_IMAG(eval2, -tmp);\n }\n\n /* set new matrix elements */\n\n gsl_matrix_set(A, 0, 0, a);\n gsl_matrix_set(A, 0, 1, b);\n gsl_matrix_set(A, 1, 0, c);\n gsl_matrix_set(A, 1, 1, d);\n} /* schur_standard_form() */\n", "meta": {"hexsha": "b2b7adb3ab3824993cca8c6542cbbc8eda929a7b", "size": 10772, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/eigen/schur.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/eigen/schur.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/eigen/schur.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 28.8793565684, "max_line_length": 81, "alphanum_fraction": 0.4662086892, "num_tokens": 3067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4258617905388055}} {"text": "// Ref:\n// G.P. Lepage, LQCD for Novices\n#include \"su3_utils.c\"\n#include \n#include \n#include \n\n// globals\nconst gsl_rng_type *T;\ngsl_rng *r; // random generator\nsu3_matrix links[4*N*N*N*N]; // link variables\nsu3_matrix rands[50]; // random unitary matrices\n\nFILE *output;\n\n// prototypes\nvoid setup();\nvoid cleanup();\n\nint\nmain (int argc, char** argv)\n{\n setup();\n\n int O[4]={0,0,0,0};\n\n for(int n=0;n pol_thres){\n hb_update(links,r,rands); //thermalize\n }\n }\n\n printf(\"Thermalized! \\n\");\n\n for(int n=0;n\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#ifdef __linux__\n#include /* arc4random() */\n#endif\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"extern.h\"\n\n/*\n * For a given point \"x\" in the domain, fit ourselves to the polynomial\n * coefficients of degree \"fitpoly + 1\".\n */\nstatic double\nfitpoly(const double *fits, size_t poly, double x)\n{\n\tdouble\t y, v;\n\tsize_t\t i, j;\n\n\tfor (y = 0.0, i = 0; i < poly; i++) {\n\t\tv = fits[i];\n\t\tfor (j = 0; j < i; j++)\n\t\t\tv *= x;\n\t\ty += v;\n\t}\n\treturn(y);\n}\n\n/*\n * Copy the \"hotlsb\" data into \"warm\" holding.\n * While here, set our simulation's \"work\" parameter (if \"fitpoly\" is\n * set) to contain the necessary dependent variable.\n * We're guaranteed to be the only ones in here, and the only ones with\n * a lock on the LBS data.\n */\nstatic void\nsnapshot(struct sim *sim, struct simwarm *warm, \n\tuint64_t truns, uint64_t tgens)\n{\n\tdouble\t \tv, chisq, x, y;\n\tstruct kpair\tkp;\n\tint\t\trc;\n\tsize_t\t \ti, j, k;\n\n\t/* Warm copy is already up to date. */\n\tif (warm->truns == truns) {\n\t\tg_assert(warm->tgens == tgens);\n\t\treturn;\n\t}\n\n\t/* Copy out: we have a lock. */\n\tsimbuf_copy_warm(sim->bufs.times);\n\tsimbuf_copy_warm(sim->bufs.imeans);\n\tsimbuf_copy_warm(sim->bufs.istddevs);\n\tsimbuf_copy_warm(sim->bufs.islandmeans);\n\tsimbuf_copy_warm(sim->bufs.islandstddevs);\n\tsimbuf_copy_warm(sim->bufs.means);\n\tsimbuf_copy_warm(sim->bufs.stddevs);\n\tsimbuf_copy_warm(sim->bufs.mextinct);\n\tsimbuf_copy_warm(sim->bufs.iextinct);\n\twarm->truns = truns;\n\twarm->tgens = tgens;\n\n\t/*\n\t * If we're going to fit to a polynomial, set the dependent\n\t * variable within the conditional.\n\t */\n\tif (sim->fitpoly)\n\t\tfor (i = 0; i < sim->dims; i++) {\n\t\t\trc = kdata_get(sim->bufs.means->warm, i, &kp);\n\t\t\tg_assert(0 != rc);\n\t\t\tgsl_vector_set(sim->work.y, i, kp.y);\n\t\t}\n\n\t/*\n\t * If we're going to run a weighted polynomial multifit, then\n\t * use the variance as the weight.\n\t */\n\tif (sim->fitpoly && sim->weighted)\n\t\tfor (i = 0; i < sim->dims; i++) {\n\t\t\trc = kdata_get(sim->bufs.stddevs->warm, i, &kp);\n\t\t\tg_assert(0 != rc);\n\t\t\tgsl_vector_set(sim->work.w, i, kp.y);\n\t\t}\n\n\t/*\n\t * If we're not fitting to a polynomial, simply notify that\n\t * we've copied out and continue on our way.\n\t */\n\tif (0 == sim->fitpoly)\n\t\treturn;\n\n\t/* \n\t * If we're fitting to a polynomial, initialise our independent\n\t * variables now.\n\t */\n\tfor (i = 0; i < sim->dims; i++) {\n\t\tgsl_matrix_set(sim->work.X, i, 0, 1.0);\n\t\tfor (j = 0; j < sim->fitpoly; j++) {\n\t\t\tv = sim->xmin +\n\t\t\t\t(sim->xmax -\n\t\t\t\t sim->xmin) *\n\t\t\t\t(i / (double)sim->dims);\n\t\t\tfor (k = 0; k < j; k++)\n\t\t\t\tv *= v;\n\t\t\tgsl_matrix_set(sim->work.X, i, j + 1, v);\n\t\t}\n\t}\n\n\t/*\n\t * Now perform the actual fitting.\n\t * We either use weighted (weighted with the variance) or\n\t * non-weighted fitting algorithms.\n\t */\n\tif (sim->weighted) \n\t\tgsl_multifit_wlinear(sim->work.X, sim->work.w, \n\t\t\tsim->work.y, sim->work.c, sim->work.cov, \n\t\t\t&chisq, sim->work.work);\n\telse\n\t\tgsl_multifit_linear(sim->work.X, sim->work.y, \n\t\t\tsim->work.c, sim->work.cov, &chisq, \n\t\t\tsim->work.work);\n\n\t/*\n\t * Now snapshot the fitted polynomial coefficients and compute\n\t * the fitted approximation for all incumbents (along with the\n\t * minimum value).\n\t */\n\tfor (i = 0; i < sim->fitpoly + 1; i++)\n\t\tsim->work.coeffs[i] = gsl_vector_get(sim->work.c, i);\n\n\tfor (i = 0; i < sim->dims; i++) {\n\t\tx = sim->xmin + (sim->xmax - sim->xmin) *\n\t\t\ti / (double)sim->dims;\n\t\ty = fitpoly(sim->work.coeffs, \n\t\t\tsim->fitpoly + 1, x);\n\t\tkdata_array_set(sim->bufs.fitpoly, i, x, y);\n\t}\n}\n\n/*\n * In a given simulation, compute the next mutant/incumbent pair.\n * We make sure that incumbents are striped evenly in any given\n * simulation but that mutants are randomly selected from within the\n * strategy domain.\n */\nstatic int\non_sim_next(struct sim *sim, const gsl_rng *rng, \n\tsize_t *islandidx, double *mutantp, double *incumbentp, \n\tsize_t *incumbentidx, double *vp, const size_t *islands,\n\tsize_t gen)\n{\n\tint\t\t dosnap, rc;\n\tsize_t\t\t mutant;\n\tuint64_t\t truns, tgens;\n\n\tif (sim->terminate)\n\t\treturn(0);\n\n\ttruns = tgens = 0; /* Silence compiler. */\n\n\t/* This is set if we \"own\" the LSB->warm process. */\n\tdosnap = 0;\n\n\tg_assert(*incumbentidx < sim->dims);\n\tg_assert(*islandidx < sim->islands);\n\tg_mutex_lock(&sim->hot.mux);\n\n\t/*\n\t * If we're entering this with a result value, then plug it into\n\t * the index associated with the run and increment our count.\n\t * This prevents us from overwriting others' results.\n\t */\n\tif (NULL != vp) {\n\t\trc = kdata_array_add\n\t\t\t(sim->bufs.times->hot, gen, 1.0);\n\t\tg_assert(0 != rc);\n\t\trc = kdata_array_fill_ysizes\n\t\t\t(sim->bufs.islands, islands);\n\t\tg_assert(0 != rc);\n\t\trc = kdata_array_set(sim->bufs.fractions, \n\t\t\t*incumbentidx, *incumbentp, *vp);\n\t\tg_assert(0 != rc);\n\t\trc = kdata_array_set(sim->bufs.ifractions, \n\t\t\t*islandidx, *islandidx, *vp);\n\t\tg_assert(0 != rc);\n\t\trc = kdata_array_set(sim->bufs.mutants, \n\t\t\t*incumbentidx, *incumbentp, 0.0 == *vp);\n\t\tg_assert(0 != rc);\n\t\trc = kdata_array_set(sim->bufs.incumbents, \n\t\t\t*incumbentidx, *incumbentp, 1.0 == *vp);\n\t\tg_assert(0 != rc);\n\t\tsim->hot.tgens += gen;\n\t\tsim->hot.truns++;\n\t}\n\n\t/*\n\t * Check if we've been requested to pause.\n\t * If so, wait for a broadcast on our condition.\n\t * This will unlock the mutex for others to process.\n\t */\n\tif (1 == sim->hot.pause)\n\t\tg_cond_wait(&sim->hot.cond, &sim->hot.mux);\n\n\t/*\n\t * Check if we've been instructed by the main thread of\n\t * execution to snapshot hot data into warm storage.\n\t * We do this in two parts: first, we register that we're in a\n\t * copyout (it's now 2) and then actually do the copyout outside\n\t * of the hot mutex.\n\t */\n\tif (1 == sim->hot.copyout) {\n\t\tsimbuf_copy_hotlsb(sim->bufs.times);\n\t\tsimbuf_copy_hotlsb(sim->bufs.islandmeans);\n\t\tsimbuf_copy_hotlsb(sim->bufs.islandstddevs);\n\t\tsimbuf_copy_hotlsb(sim->bufs.imeans);\n\t\tsimbuf_copy_hotlsb(sim->bufs.istddevs);\n\t\tsimbuf_copy_hotlsb(sim->bufs.means);\n\t\tsimbuf_copy_hotlsb(sim->bufs.stddevs);\n\t\tsimbuf_copy_hotlsb(sim->bufs.mextinct);\n\t\tsimbuf_copy_hotlsb(sim->bufs.iextinct);\n\t\ttruns = sim->hot.truns;\n\t\ttgens = sim->hot.tgens;\n\t\tsim->hot.copyout = dosnap = 2;\n\t} \n\n\t/*\n\t * Reassign our mutant and incumbent from the ring sized by the\n\t * configured lattice dimensions.\n\t * These both increment in single movements until the end of the\n\t * lattice, then wrap around.\n\t */\n\t*islandidx = sim->hot.island;\n\tmutant = sim->hot.mutant;\n\t*incumbentidx = sim->hot.incumbent;\n\tsim->hot.mutant++;\n\tif (sim->hot.mutant == sim->dims) {\n\t\tsim->hot.incumbent++;\n\t\tif (sim->hot.incumbent == sim->dims) {\n\t\t\tsim->hot.incumbent = 0;\n\t\t\tif (MAPINDEX_STRIPED == sim->mapindex)\n\t\t\t\tsim->hot.island = \n\t\t\t\t\t(sim->hot.island + 1) % \n\t\t\t\t\tsim->islands;\n\t\t}\n\t\tsim->hot.mutant = 0;\n\t}\n\t\n\tg_mutex_unlock(&sim->hot.mux);\n\n\t/*\n\t * Assign our incumbent and mutant.\n\t * The incumbent just gets the current lattice position,\n\t * ensuring an even propogation.\n\t * The mutant is either assigned the same way or from a Gaussian\n\t * distribution around the current incumbent.\n\t */\n\t*incumbentp = sim->xmin + (sim->xmax - sim->xmin) * \n\t\t(*incumbentidx / (double)sim->dims);\n\n\tif (MUTANTS_GAUSSIAN == sim->mutants) {\n\t\tdo {\n\t\t\t*mutantp = *incumbentp + \n\t\t\t\tgsl_ran_gaussian\n\t\t\t\t(rng, sim->mutantsigma);\n\t\t} while (*mutantp < sim->ymin ||\n\t\t\t *mutantp >= sim->ymax);\n\t} else\n\t\t*mutantp = sim->xmin + \n\t\t\t(sim->xmax - \n\t\t\t sim->xmin) * \n\t\t\t(mutant / (double)sim->dims);\n\n\t/*\n\t * If we were the ones to set the copyout bit, then do the\n\t * copyout right now.\n\t * When we're finished, lower the copyout semaphor.\n\t */\n\tif (dosnap) {\n\t\tsnapshot(sim, &sim->warm, truns, tgens);\n\t\tg_mutex_lock(&sim->hot.mux);\n\t\tg_assert(2 == sim->hot.copyout);\n\t\tsim->hot.copyout = 0;\n\t\tg_mutex_unlock(&sim->hot.mux);\n\t}\n\n\treturn(1);\n}\n\n/*\n * For a given island (size \"pop\") player's strategy \"x\" where mutants\n * (numbering \"mutants\") have strategy \"mutant\" and incumbents\n * (numbering \"incumbents\") have strategy \"incumbent\", compute the\n * a(1 + delta(pi(x, X)) function.\n */\nstatic double\nreproduce(const struct sim *sim, double x, \n\tdouble mutant, double incumbent, size_t mutants, size_t pop)\n{\n\tdouble\t v;\n\n\tif (0 == pop)\n\t\treturn(0.0);\n\n\tv = hnode_exec\n\t\t((const struct hnode *const *)\n\t\t sim->exp, x,\n\t\t (mutants * mutant) + ((pop - mutants) * incumbent),\n\t\t pop);\n\tg_assert( ! (isnan(v) || isinf(v)));\n\treturn(sim->alpha * (1.0 + sim->delta * v));\n}\n\nstatic size_t\nmigrate(const struct sim *sim, const gsl_rng *rng, size_t cur)\n{\n\tdouble\t v;\n\tsize_t\t i;\n\nagain:\n\twhile (0.0 == (v = gsl_rng_uniform(rng)))\n\t\t/* Loop. */ ;\n\n\tfor (i = 0; i < sim->islands - 1; i++)\n\t\tif ((v -= sim->ms[cur][i]) <= 0.0)\n\t\t\tbreak;\n\n\t/*\n\t * This can occur due to floating-point rounding.\n\t * If it does, re-run the algorithm.\n\t */\n\tif (i == sim->islands - 1 && i == cur) {\n\t\tg_debug(\"Degenerate probability: re-running\");\n\t\tgoto again;\n\t}\n\n\tg_assert(cur != i);\n\treturn(i);\n}\n\n/*\n * Run a simulation.\n * This can be one thread of many within the same simulation.\n */\nvoid *\nsimulation(void *arg)\n{\n\tstruct simthr\t *thr = arg;\n\tstruct sim\t *sim = thr->sim;\n\tdouble\t\t mutant, incumbent, v, lambda, prob;\n\tunsigned int\t offs;\n\tunsigned long\t seed;\n\tdouble\t\t *vp, *icache, *mcache;\n\tdouble\t\t***icaches, ***mcaches;\n\tsize_t\t\t *kids[2], *migrants[2], *imutants, *npops,\n\t\t\t *ndeaths;\n\tsize_t\t\t t, i, j, k, new, mutants, incumbents,\n\t\t\t len1, len2, incumbentidx, islandidx,\n\t\t\t ntotalpop;\n\tint\t\t mutant_old, mutant_new;\n\tgsl_rng\t\t *rng;\n\n\trng = gsl_rng_alloc(gsl_rng_default);\n\tseed = arc4random();\n\tgsl_rng_set(rng, seed);\n\n\tg_debug(\"%p: Thread (simulation %p) \"\n\t\t\"start\", g_thread_self(), sim);\n\n\ticache = mcache = NULL;\n\ticaches = mcaches = NULL;\n\tkids[0] = g_malloc0_n(sim->islands, sizeof(size_t));\n\tkids[1] = g_malloc0_n(sim->islands, sizeof(size_t));\n\tndeaths = g_malloc0_n(sim->islands, sizeof(size_t));\n\tmigrants[0] = g_malloc0_n(sim->islands, sizeof(size_t));\n\tmigrants[1] = g_malloc0_n(sim->islands, sizeof(size_t));\n\timutants = g_malloc0_n(sim->islands, sizeof(size_t));\n\tvp = NULL;\n\tnpops = NULL;\n\tincumbentidx = 0;\n\tislandidx = MAPINDEX_FIXED == sim->mapindex ? \n\t\tsim->mapindexfix : 0;\n\tmutant = incumbent = 0.0;\n\tt = 0;\n\n\t/*\n\t * Set up our mutant and incumbent payoff caches.\n\t * These consist of all possible payoffs with a given number of\n\t * mutants and incumbents on an island.\n\t * We have two ways of doing this: with non-uniform island sizes\n\t * (icaches and mcaches) and uniform sizes (icache and mcache,\n\t * notice the singular).\n\t * The non-uniform island size can also change, so we precompute\n\t * for all possible populations as well.\n\t */\n\tif (NULL != sim->pops) {\n\t\tg_assert(0 == sim->pop);\n\t\tnpops = g_malloc0_n(sim->islands, sizeof(size_t));\n\t\tfor (i = 0; i < sim->islands; i++) \n\t\t\tnpops[i] = sim->pops[i];\n\t\ticaches = g_malloc0_n(sim->islands, sizeof(double **));\n\t\tmcaches = g_malloc0_n(sim->islands, sizeof(double **));\n\t\tfor (i = 0; i < sim->islands; i++) {\n\t\t\ticaches[i] = g_malloc0_n\n\t\t\t\t(sim->pops[i] + 1, sizeof(double *));\n\t\t\tmcaches[i] = g_malloc0_n\n\t\t\t\t(sim->pops[i] + 1, sizeof(double *));\n\t\t\tfor (j = 0; j <= sim->pops[i]; j++) {\n\t\t\t\ticaches[i][j] = g_malloc0_n(j + 1, sizeof(double));\n\t\t\t\tmcaches[i][j] = g_malloc0_n(j + 1, sizeof(double));\n\t\t\t}\n\t\t}\n\t} else {\n\t\tg_assert(sim->pop > 0);\n\t\ticache = g_malloc0_n(sim->pop + 1, sizeof(double));\n\t\tmcache = g_malloc0_n(sim->pop + 1, sizeof(double));\n\t}\nagain:\n\t/* \n\t * Repeat til we're instructed to terminate. \n\t * We also pass in our last result for processing.\n\t */\n\tif ( ! on_sim_next(sim, rng, &islandidx, &mutant, \n\t\t&incumbent, &incumbentidx, vp, imutants, t)) {\n\t\tg_debug(\"%p: Thread (simulation %p) exiting\", \n\t\t\tg_thread_self(), sim);\n\t\t/*\n\t\t * Upon termination, free up all of the memory\n\t\t * associated with our simulation.\n\t\t */\n\t\tg_free(ndeaths);\n\t\tg_free(imutants);\n\t\tg_free(kids[0]);\n\t\tg_free(kids[1]);\n\t\tg_free(migrants[0]);\n\t\tg_free(migrants[1]);\n\t\tif (NULL != sim->pops)\n\t\t\tfor (i = 0; i < sim->islands; i++) {\n\t\t\t\tfor (j = 0; j <= sim->pops[i]; j++) {\n\t\t\t\t\tg_free(icaches[i][j]);\n\t\t\t\t\tg_free(mcaches[i][j]);\n\t\t\t\t}\n\t\t\t\tg_free(icaches[i]);\n\t\t\t\tg_free(mcaches[i]);\n\t\t\t}\n\t\tg_free(icaches);\n\t\tg_free(mcaches);\n\t\tg_free(icache);\n\t\tg_free(mcache);\n\t\treturn(NULL);\n\t}\n\n\t/* \n\t * Initialise a random island to have one mutant. \n\t * The rest are all incumbents.\n\t */\n\tmemset(imutants, 0, sim->islands * sizeof(size_t));\n\timutants[islandidx] = 1;\n\tmutants = 1;\n\tincumbents = sim->totalpop - mutants;\n\tntotalpop = sim->totalpop;\n\n\t/*\n\t * Precompute all possible payoffs.\n\t * This allows us not to re-run the lambda calculation for each\n\t * individual.\n\t * If we have only a single island size, then avoid allocating\n\t * for each island by using only the first mcaches index.\n\t */\n\tif (NULL != sim->pops)\n\t\tfor (i = 0; i < sim->islands; i++) {\n\t\t\tfor (j = 0; j <= sim->pops[i]; j++) {\n\t\t\t\tfor (k = 0; k <= j; k++) {\n\t\t\t\t\tmcaches[i][j][k] = reproduce\n\t\t\t\t\t\t(sim, mutant, mutant, \n\t\t\t\t\t\t incumbent, k, j);\n\t\t\t\t\ticaches[i][j][k] = reproduce\n\t\t\t\t\t\t(sim, incumbent, mutant, \n\t\t\t\t\t\t incumbent, k, j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\telse\n\t\tfor (i = 0; i <= sim->pop; i++) {\n\t\t\tmcache[i] = reproduce(sim, mutant,\n\t\t\t\tmutant, incumbent, i, sim->pop);\n\t\t\ticache[i] = reproduce(sim, incumbent,\n\t\t\t\tmutant, incumbent, i, sim->pop);\n\t\t}\n\n\tfor (t = 0; t < sim->stop; t++) {\n\t\tif (NULL != sim->pops && sim->ideathmean > 0) {\n\t\t\t/*\n\t\t\t * If we're a non-uniform population and have an\n\t\t\t * island death mean, then see if we're supposed\n\t\t\t * to kill off islands, then re-set the shot\n\t\t\t * clock.\n\t\t\t */\n\t\t\tfor (i = 0; i < sim->islands; i++) {\n\t\t\t\t/* \n\t\t\t\t * If the shot-clock has not been\n\t\t\t\t * started OR the island is already\n\t\t\t\t * dead, set it again.\n\t\t\t\t */\n\t\t\t\tif (0 == ndeaths[i] || 0 == npops[i]) {\n\t\t\t\t\tndeaths[i] = t + 1 +\n\t\t\t\t\t\tgsl_ran_poisson\n\t\t\t\t\t\t(rng, sim->ideathmean);\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (t != ndeaths[i])\n\t\t\t\t\tcontinue;\n\n\t\t\t\tndeaths[i] = t + 1 +\n\t\t\t\t\tgsl_ran_poisson\n\t\t\t\t\t(rng, sim->ideathmean);\n\n\t\t\t\t/* \n\t\t\t\t * What's the sum of our payoffs?\n\t\t\t\t * Compute the probability that we're\n\t\t\t\t * going to be killed from that and our\n\t\t\t\t * coefficient.\n\t\t\t\t */\n\t\t\t\tg_assert(npops[i] > 0);\n\t\t\t\tv = mcaches[i][npops[i]][imutants[i]] *\n\t\t\t\t\timutants[i] +\n\t\t\t\t icaches[i][npops[i]][imutants[i]] *\n\t\t\t\t \t(npops[i] - imutants[i]);\n\t\t\t\tprob = sim->ideathcoef * exp(-v);\n\t\t\t\tif (gsl_rng_uniform(rng) >= prob)\n\t\t\t\t\tcontinue;\n\t\t\t\tmutants -= imutants[i];\n\t\t\t\tincumbents -= (npops[i] - imutants[i]);\n\t\t\t\tntotalpop -= npops[i];\n\t\t\t\tnpops[i] = 0;\n\t\t\t\timutants[i] = 0;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Birth process: have each individual (first mutants,\n\t\t * then incumbents) give birth.\n\t\t * Use a Poisson process with the given mean in order to\n\t\t * properly compute this.\n\t\t * We need two separate versions for whichever type of\n\t\t * mcache we decide to use.\n\t\t */\n\t\tif (NULL != sim->pops)\n\t\t\tfor (j = 0; j < sim->islands; j++) {\n\t\t\t\tif (0 == npops[j])\n\t\t\t\t\tcontinue;\n\t\t\t\tg_assert(0 == kids[0][j]);\n\t\t\t\tg_assert(0 == kids[1][j]);\n\t\t\t\tg_assert(0 == migrants[0][j]);\n\t\t\t\tg_assert(0 == migrants[1][j]);\n\t\t\t\tg_assert(imutants[j] <= npops[j]);\n\t\t\t\tlambda = mcaches[j]\n\t\t\t\t\t[npops[j]][imutants[j]];\n\t\t\t\tfor (k = 0; k < imutants[j]; k++) {\n\t\t\t\t\toffs = gsl_ran_poisson\n\t\t\t\t\t\t(rng, lambda);\n\t\t\t\t\tkids[0][j] += offs;\n\t\t\t\t}\n\t\t\t\tlambda = icaches[j]\n\t\t\t\t\t[npops[j]][imutants[j]];\n\t\t\t\tfor ( ; k < npops[j]; k++) {\n\t\t\t\t\toffs = gsl_ran_poisson\n\t\t\t\t\t\t(rng, lambda);\n\t\t\t\t\tkids[1][j] += offs;\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\tfor (j = 0; j < sim->islands; j++) {\n\t\t\t\tg_assert(0 == kids[0][j]);\n\t\t\t\tg_assert(0 == kids[1][j]);\n\t\t\t\tg_assert(0 == migrants[0][j]);\n\t\t\t\tg_assert(0 == migrants[1][j]);\n\t\t\t\tlambda = mcache[imutants[j]];\n\t\t\t\tfor (k = 0; k < imutants[j]; k++) {\n\t\t\t\t\toffs = gsl_ran_poisson\n\t\t\t\t\t\t(rng, lambda);\n\t\t\t\t\tkids[0][j] += offs;\n\t\t\t\t}\n\t\t\t\tlambda = icache[imutants[j]];\n\t\t\t\tfor ( ; k < sim->pop; k++) {\n\t\t\t\t\toffs = gsl_ran_poisson\n\t\t\t\t\t\t(rng, lambda);\n\t\t\t\t\tkids[1][j] += offs;\n\t\t\t\t}\n\t\t\t}\n\n\t\t/*\n\t\t * Determine whether we're going to migrate and, if\n\t\t * migration is stipulated, to where.\n\t\t */\n\t\tif (NULL != sim->ms)\n\t\t\tfor (j = 0; j < sim->islands; j++) {\n\t\t\t\tfor (k = 0; k < kids[0][j]; k++) {\n\t\t\t\t\tnew = j;\n\t\t\t\t\tif (gsl_rng_uniform(rng) < sim->m)\n\t\t\t\t\t\tnew = migrate(sim, rng, j);\n\t\t\t\t\tmigrants[0][new]++;\n\t\t\t\t}\n\t\t\t\tfor (k = 0; k < kids[1][j]; k++) {\n\t\t\t\t\tnew = j;\n\t\t\t\t\tif (gsl_rng_uniform(rng) < sim->m)\n\t\t\t\t\t\tnew = migrate(sim, rng, j);\n\t\t\t\t\tmigrants[1][new]++;\n\t\t\t\t}\n\t\t\t\tkids[0][j] = kids[1][j] = 0;\n\t\t\t}\n\t\telse\n\t\t\tfor (j = 0; j < sim->islands; j++) {\n\t\t\t\tfor (k = 0; k < kids[0][j]; k++) {\n\t\t\t\t\tnew = j;\n\t\t\t\t\tif (gsl_rng_uniform(rng) < sim->m) do \n\t\t\t\t\t\tnew = gsl_rng_uniform_int\n\t\t\t\t\t\t\t(rng, sim->islands);\n\t\t\t\t\twhile (new == j);\n\t\t\t\t\tmigrants[0][new]++;\n\t\t\t\t}\n\t\t\t\tfor (k = 0; k < kids[1][j]; k++) {\n\t\t\t\t\tnew = j;\n\t\t\t\t\tif (gsl_rng_uniform(rng) < sim->m) do \n\t\t\t\t\t\tnew = gsl_rng_uniform_int\n\t\t\t\t\t\t\t(rng, sim->islands);\n\t\t\t\t\twhile (new == j);\n\t\t\t\t\tmigrants[1][new]++;\n\t\t\t\t}\n\t\t\t\tkids[0][j] = kids[1][j] = 0;\n\t\t\t}\n\n\t\t/*\n\t\t * Perform the migration itself.\n\t\t * We randomly select an individual on the destination\n\t\t * island as well as one from the migrant queue.\n\t\t * We then replace one with the other.\n\t\t */\n\t\tif (NULL != sim->pops) \n\t\t\tfor (j = 0; j < sim->islands; j++) {\n\t\t\t\tif (npops[j] < sim->pops[j]) {\n\t\t\t\t\t/*\n\t\t\t\t\t * This is the case where a\n\t\t\t\t\t * given island has had its\n\t\t\t\t\t * population killed off.\n\t\t\t\t\t * Try to fill it up: don't\n\t\t\t\t\t * replace anybody.\n\t\t\t\t\t */\n\t\t\t\t\twhile (npops[j] < sim->pops[j]) {\n\t\t\t\t\t\tlen1 = migrants[0][j] + \n\t\t\t\t\t\t\tmigrants[1][j];\n\t\t\t\t\t\tif (0 == len1)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tlen2 = gsl_rng_uniform_int\n\t\t\t\t\t\t\t(rng, len1);\n\t\t\t\t\t\tif (len2 < migrants[0][j]) {\n\t\t\t\t\t\t\tmigrants[0][j]--;\n\t\t\t\t\t\t\timutants[j]++;\n\t\t\t\t\t\t\tmutants++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmigrants[1][j]--;\n\t\t\t\t\t\t\tincumbents++;\n\t\t\t\t\t\t} \n\t\t\t\t\t\tnpops[j]++;\n\t\t\t\t\t\tntotalpop++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlen1 = migrants[0][j] + \n\t\t\t\t\t\tmigrants[1][j];\n\t\t\t\t\tif (0 == len1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tlen2 = gsl_rng_uniform_int\n\t\t\t\t\t\t(rng, npops[j]);\n\t\t\t\t\tmutant_old = len2 < imutants[j];\n\t\t\t\t\tlen2 = gsl_rng_uniform_int(rng, len1);\n\t\t\t\t\tmutant_new = len2 < migrants[0][j];\n\t\t\t\t\tif (mutant_old && ! mutant_new) {\n\t\t\t\t\t\timutants[j]--;\n\t\t\t\t\t\tmutants--;\n\t\t\t\t\t\tincumbents++;\n\t\t\t\t\t} else if ( ! mutant_old && mutant_new) {\n\t\t\t\t\t\timutants[j]++;\n\t\t\t\t\t\tmutants++;\n\t\t\t\t\t\tincumbents--;\n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t\tmigrants[0][j] = migrants[1][j] = 0;\n\t\t\t}\n\t\telse\n\t\t\tfor (j = 0; j < sim->islands; j++) {\n\t\t\t\tlen1 = migrants[0][j] + migrants[1][j];\n\t\t\t\tif (0 == len1)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tlen2 = gsl_rng_uniform_int(rng, sim->pop);\n\t\t\t\tmutant_old = len2 < imutants[j];\n\t\t\t\tlen2 = gsl_rng_uniform_int(rng, len1);\n\t\t\t\tmutant_new = len2 < migrants[0][j];\n\n\t\t\t\tif (mutant_old && ! mutant_new) {\n\t\t\t\t\timutants[j]--;\n\t\t\t\t\tmutants--;\n\t\t\t\t\tincumbents++;\n\t\t\t\t} else if ( ! mutant_old && mutant_new) {\n\t\t\t\t\timutants[j]++;\n\t\t\t\t\tmutants++;\n\t\t\t\t\tincumbents--;\n\t\t\t\t} \n\n\t\t\t\tmigrants[0][j] = migrants[1][j] = 0;\n\t\t\t}\n\n\t\t/* Stop when a population goes extinct. */\n\t\tif (0 == mutants || 0 == incumbents) \n\t\t\tbreak;\n\t}\n\n\t/*\n\t * Assign the result pointer to the last population fraction.\n\t * This will be processed by on_sim_next().\n\t */\n\tif (incumbents == 0) {\n\t\tg_assert(mutants == ntotalpop);\n\t\tv = 1.0;\n\t} else if (mutants == 0) {\n\t\tg_assert(incumbents == ntotalpop);\n\t\tv = 0.0;\n\t} else\n\t\tv = mutants / (double)ntotalpop;\n\t\n\tvp = &v;\n\tgoto again;\n}\n\n", "meta": {"hexsha": "015892ec93e7cb6a80d10215865e5ed4bc2d456c", "size": 20150, "ext": "c", "lang": "C", "max_stars_repo_path": "simulation.c", "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_issues_repo_path": "simulation.c", "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation.c", "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5831134565, "max_line_length": 75, "alphanum_fraction": 0.6063027295, "num_tokens": 6695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4254963818004155}} {"text": "/******************************************************************************\nCosmoLike Configuration Space Covariances for Projected Galaxy 2-Point Statistics\nhttps://github.com/CosmoLike/CosmoCov\nby CosmoLike developers\n******************************************************************************/\n\n#include \n#include \n#if !defined(__APPLE__)\n#include \n#endif\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \n\n#include \"../cosmolike_core/2dfftlog/twobessel.h\"\n#include \"../cosmolike_core/2dfftlog/utils.h\"\n\n#include \"../cosmolike_core/theory/basics.c\"\n#include \"../cosmolike_core/theory/structs.c\"\n#include \"../cosmolike_core/theory/recompute.c\"\n#include \"../cosmolike_core/theory/cosmo3D.c\"\n#include \"../cosmolike_core/theory/redshift_spline.c\"\n#include \"../cosmolike_core/theory/halo.c\"\n#include \"../cosmolike_core/theory/cosmo2D_fourier.c\"\n\n#include \"../cosmolike_core/theory/covariances_3D.c\"\n#include \"../cosmolike_core/theory/covariances_fourier.c\"\n#include \"../cosmolike_core/theory/covariances_real_bin_fft.c\"\n#include \"../cosmolike_core/theory/run_covariances_real_bin_fft.c\"\n#include \"init.c\"\n\n#include \"../cosmolike_core/2dfftlog/utils_complex.h\"\n\n#include \n\nint main(int argc, char** argv)\n{\n\n if (argc != 3){\n fprintf(stderr, \"Syntax: %s block_number config_file\\n\", argv[0]);\n exit(1);\n }\n\n int hit=atoi(argv[1]);\n char *inifile;\n inifile = argv[2];\n\n FILE *F1,*F2;\n int i,l,m,n,o,s,p,output;\n double ktmp;\n char OUTFILE[400],filename[400];\n\n // set this to one to output details about inputs for diagnostics\n output = 0;\n FILE *F;\n\n set_cosmological_parameters(inifile,1);\n set_survey_parameters(inifile,1);\n set_cov_parameters(inifile,1);\n\n init_source_sample(redshift.shear_REDSHIFT_FILE,tomo.shear_Nbin);\n init_lens_sample(redshift.clustering_REDSHIFT_FILE,tomo.clustering_Nbin);\n\n if (covparams.lin_bins){\n printf(\"covariances_real_flat_fft does not support linear angular binning\\nEXIT\\n\");exit(1);\n }\n if (covparams.full_tomo){\n printf(\"covariances_real_flat_fft does not support full cross-zbins clustering yet\\nEXIT\\n\");exit(1);\n }\n\n int NG, cNG;\n if (covparams.ng==1){\n NG = 1;\n if (covparams.cng==1){\n cNG = 1;\n }\n else{\n cNG = 0;\n }\n }\n else {\n NG = 0;\n cNG = 0;\n }\n\n printf(\"running multi_covariance_real with NG = %d, cNG = %d\\n\",NG, cNG);\n\n like.Ntheta=covparams.ntheta;\n like.vtmin = covparams.tmin;\n like.vtmax = covparams.tmax;\n int Ntheta = like.Ntheta;\n double *thetamin,*dtheta,*theta;\n thetamin=create_double_vector(0,Ntheta);\n dtheta=create_double_vector(0,Ntheta-1);\n theta=create_double_vector(0,Ntheta-1);\n set_angular_binning(thetamin,dtheta);\n for (i =0; i< Ntheta; i++){\n theta[i] = 2./3.*(pow(thetamin[i+1],3.)-pow(thetamin[i],3.))/(pow(thetamin[i+1],2.)-pow(thetamin[i],2.));\n }\n\n\n int k=1;\n if (strcmp(covparams.ss,\"true\")==0)\n {\n sprintf(OUTFILE,\"%s_ssss_++_cov_Ntheta%d_Ntomo%d\",covparams.filename,Ntheta,tomo.shear_Nbin);\n\n for (l=0;l\n#include \n#include \n#include \n\n#include \"egsl.h\"\n\n\n\nval egsl_sub(val v1,val v2){\n\treturn egsl_sum(v1, egsl_scale(-1.0,v2));\n}\n\nval egsl_compose_col(val v1, val v2){\n\tgsl_matrix *m1 = egsl_gslm(v1);\n\tgsl_matrix *m2 = egsl_gslm(v2);\n\tegsl_expect_size(v2, 0, m1->size2);\n\tval v3 = egsl_alloc(m1->size1+m2->size1,m1->size2);\n\tgsl_matrix *m3 = egsl_gslm(v3);\n\tsize_t i,j;\n\tfor(j=0;jsize2;j++) {\n\t\tfor(i=0;isize1;i++)\n\t\t\tgsl_matrix_set(m3, i, j, gsl_matrix_get(m1,i,j));\n\t\t\n\t\tfor(i=0;isize1;i++)\n\t\t\tgsl_matrix_set(m3, m1->size1+i, j, gsl_matrix_get(m2,i,j));\n\t}\n\treturn v3;\n}\n\nval egsl_compose_row(val v1, val v2){\n\tgsl_matrix *m1 = egsl_gslm(v1);\n\tgsl_matrix *m2 = egsl_gslm(v2);\n\tegsl_expect_size(v2, m1->size1, 0);\n\tval v3 = egsl_alloc(m1->size1, m1->size2 + m2->size2);\n\tgsl_matrix *m3 = egsl_gslm(v3);\n\tsize_t i,j;\n\tfor(i=0;isize1;i++) {\n\t\tfor(j=0;jsize2;j++) \n\t\t\tgsl_matrix_set(m3, i, j, gsl_matrix_get(m1,i,j));\n\t\t\n\t\tfor(j=0;jsize2;j++) \n\t\t\tgsl_matrix_set(m3, i, m1->size2+j, gsl_matrix_get(m2,i,j));\n\t}\n\treturn v3;\n}\n\nvoid egsl_add_to(val v1, val v2) {\n\tgsl_matrix * m1 = egsl_gslm(v1); \n\tgsl_matrix * m2 = egsl_gslm(v2);\n\tgsl_matrix_add(m1,m2);\t\n}\n\nvoid egsl_add_to_col(val v1, size_t j, val v2) {\n/*\tegsl_print(\"m1\",v1);\n\tegsl_print(\"m2\",v2); */\n\tgsl_matrix * m1 = egsl_gslm(v1); \n\tgsl_matrix * m2 = egsl_gslm(v2);\n\t\n/*\tprintf(\"m1 size = %d,%d j = %d\\n\",m1->size1,m1->size2,j); */\n\tegsl_expect_size(v2, m1->size1, 1);\n\tsize_t i;\n\tfor(i=0;isize1;i++) {\n\t\t*gsl_matrix_ptr(m1, i, j) += gsl_matrix_get(m2,i,0);\n\t}\n}\n\n\nval egsl_copy_val(val v1) {\n\tgsl_matrix * m1 = egsl_gslm(v1);\n\tval v2 = egsl_alloc(m1->size1,m1->size2);\n\tgsl_matrix * m2 = egsl_gslm(v2);\n\tgsl_matrix_memcpy(m2,m1);\n\treturn v2;\n}\n\nval egsl_scale(double s, val v1){\n\tval v2 = egsl_copy_val(v1);\n\tgsl_matrix * m2 = egsl_gslm(v2);\n\tgsl_matrix_scale(m2, s);\n\treturn v2;\n}\n\nval egsl_sum(val v1, val v2){\n\tgsl_matrix * m1 = egsl_gslm(v1);\n\tgsl_matrix * m2 = egsl_gslm(v2);\n\tval v3 = egsl_alloc(m1->size1,m1->size2);\n\tgsl_matrix * m3 = egsl_gslm(v3);\n\tgsl_matrix_memcpy(m3,m1);\n\tgsl_matrix_add(m3,m2);\t\n\treturn v3;\n}\n\nval egsl_sum3(val v1, val v2, val v3){\n\treturn egsl_sum(v1, egsl_sum(v2,v3));\n}\n\nval egsl_mult(val v1, val v2){\n\tgsl_matrix * a = egsl_gslm(v1);\n\tgsl_matrix * b = egsl_gslm(v2);\n\tval v = egsl_alloc(a->size1,b->size2);\n\tgsl_matrix * ab = egsl_gslm(v); \n\tgsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,a,b,0.0,ab);\n\treturn v;\n}\n\nval egsl_transpose(val v1){\n\tgsl_matrix * m1 = egsl_gslm(v1);\n\tval v2 = egsl_alloc(m1->size2,m1->size1);\n\tgsl_matrix * m2 = egsl_gslm(v2);\n\tgsl_matrix_transpose_memcpy(m2,m1);\n\treturn v2;\n}\n\nval egsl_inverse(val v1){\n\tgsl_matrix*A = egsl_gslm(v1);\n\tval v2 = egsl_alloc(A->size1,A->size1);\n\tgsl_matrix*invA = egsl_gslm(v2);\n\tsize_t n = A->size1;\n\tgsl_matrix * m = gsl_matrix_alloc(n,n);\n\tgsl_matrix_memcpy(m,A);\n\tgsl_permutation * perm = gsl_permutation_alloc (n);\n\t/* Make LU decomposition of matrix m */\n\tint s;\n\tgsl_linalg_LU_decomp (m, perm, &s);\n\t/* Invert the matrix m */\n\tgsl_linalg_LU_invert (m, perm, invA);\n\tgsl_permutation_free(perm);\n\tgsl_matrix_free(m);\n\treturn v2;\n}\n\nvoid egsl_symm_eig(val v, double* eigenvalues, val* eigenvectors) {\n\tgsl_matrix *m = egsl_gslm(v);\n\tsize_t N = m->size1;\n\t/* Check for v to be square */\n\t\n\tgsl_matrix *A = gsl_matrix_alloc(N,N);\n\tgsl_matrix_memcpy(A, m);\n\t\n\tgsl_vector *eval = gsl_vector_alloc(N); \n\tgsl_matrix *evec = gsl_matrix_alloc(N,N);\n\t\n\tgsl_eigen_symmv_workspace * ws = gsl_eigen_symmv_alloc(N);\n\tgsl_eigen_symmv(A, eval, evec, ws);\n\tgsl_eigen_symmv_free(ws);\t\n\n\t\n\tgsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_VAL_DESC);\n\t\n\tsize_t j;\n\tfor(j=0;j\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#define MAX(a, b) \\\n\t({ __typeof__ (a) x = (a); \\\n\t\t__typeof__ (b) y = (b); \\\n\t\tx > y ? x : y; })\n#define MIN(a, b) \\\n\t({ __typeof__ (a) x = (a); \\\n\t\t__typeof__ (b) y = (b); \\\n\t\tx <= y ? x : y; })\n#define CLAMP(a, min, max) \\\n\t({ __typeof__ (a) hilim = (max); \\\n\t\t__typeof__ (a) lolim = (min); \\\n\t\t__typeof__ (a) x = (a); \\\n\t\tx = x <= hilim ? x : hilim; \\\n\t\tx > lolim ? x : lolim; })\n#define EXPEL(a, leftbound, rightbound) \\\n\t({ __typeof__ (a) l = (leftbound); \\\n\t\t__typeof__ (a) r = (rightbound); \\\n\t\t__typeof__ (a) x = (a); \\\n\t\t__typeof__ (a) Two = 2; \\\n\t\tx >= r || x <= l ? x : ((Two * (x - leftbound) >= \\\n\t\t\trightbound - leftbound) ? rightbound : leftbound); })\n\n#ifdef FP_FAST_FMA\n\t#define FMA_m(a, b, c) fma(a, b, c)\n#else\n\t#define FMA_m(a, b, c) ( (a) * (b) + (c) )\n#endif\n\n//Function prototypes (because we don't export everything)\nstatic double NotImplementedFunc(struct UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr);\nstatic double NotImplementedInvFunc(struct UniverseLCDM *uni, double Dc, unsigned int branchNum,\n\tdouble epsrel, unsigned int maxiter);\n\n//interpolation functions\nstatic void LtEdgeBases(double, double, double *restrict);\nstatic inline void RtEdgeBases(double, double, double *restrict);\nstatic void centerBases(double, double, double *restrict);\nstatic void Dc0Derivatives(UniverseLCDM *, double, double *);\nstatic void tL0Derivatives(UniverseLCDM *, double, double *);\nstatic double MeanValueInterval(double, double *, double *, double *);\n\n//integration functions\nstatic inline double Einv(UniverseLCDM *, double);\nstatic inline double dDc0_dz_gsl(double, void *);\nstatic inline double dtL0_dz_gsl(double, void *);\n\n//Cosmology functions\nstatic inline double DcT0Flat(struct UniverseLCDM *, double, bool, double, double, size_t, double *);\nstatic double DcT0NegK(struct UniverseLCDM *, double, bool, double, double, size_t, double *);\nstatic double DcT0PosK(struct UniverseLCDM *, double, bool, double, double, size_t, double *);\nstatic inline double Vc0Flat(struct UniverseLCDM *, double, bool, double, double, size_t, double *);\nstatic double Vc0NegK(struct UniverseLCDM *, double, bool, double, double, size_t, double *);\nstatic double Vc0PosK(struct UniverseLCDM *, double, bool, double, double, size_t, double *);\n\n//Inverse cosmology functions\nstatic double FindDa0Max(UniverseLCDM *, double, unsigned int);\nstatic double DcT0InvFlat(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\nstatic double DcT0InvNegK(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\nstatic double DcT0InvPosK(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\nstatic double Da0InvFlat(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\nstatic double Da0InvNegK(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\nstatic double Da0InvPosK(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\nstatic double Dl0InvFlat(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\nstatic double Dl0InvNegK(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\nstatic double Dl0InvPosK(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\nstatic double Vc0InvFlat(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\nstatic double Vc0InvNegK(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\nstatic double Vc0InvPosK(struct UniverseLCDM *, double, unsigned int, double, unsigned int);\n\n\n//Constants\nconst double clight = 299792458.0;\nconst double MeterPerAu = 0.149598e12;\nconst double AuPerMeter = 0x1.d662b65385936p-38; //1.0 / MeterPerAu;\nconst double MeterPerParsec = 0x1.b68064bc05bf1p+54; //MeterPerAu / tan( pi / (3600.0 * 180.0) );\nconst double ParsecPerMeter = 0x1.2ae8abdcb93c6p-55; //1.0 / MeterPerParsec;\nconst double MeterPerMpc = 0x1.a2300a115feaep+74; //1e6 * MeterPerParsec;\nconst double MpcPerMeter = 0x1.396dbd4dbf44bp-75; //1.0 / MpcPerMeter;\nconst double SecPerYear = 31557600.0; //365.25 * 24.0 * 3600.0;\nconst double YearPerSec = 0x1.1032d78f1540bp-25; //1.0 / SecPerYear;\nconst double SecPerGyear = 31557600.0e9; //1e9 * SecPerYear;\nconst double GyearPerSec = 0x1.244561c42c152p-55; //1.0 / SecPerGyear;\n\nconst double Pi = 0x1.921fb54442d18p+1;\n\n\nstatic double NotImplementedFunc(struct UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\tfprintf(stderr, \"Error: calling a function that isn't implemented yet.\");\n\texit(EXIT_FAILURE);\n\n\treturn NAN;\n}\n\nstatic double NotImplementedInvFunc(struct UniverseLCDM *uni, double Dc, unsigned int branchNum,\n\tdouble epsrel, unsigned int maxiter) {\n\tfprintf(stderr, \"Error: calling an inverse function that isn't implemented yet.\");\n\texit(EXIT_FAILURE);\n\n\treturn NAN;\n}\n\n\n/* Define the Hermite interpolation basis functions, with x the distance from\n * the central point in units of h, the distance between points.\n * Assumes equidistance points. results written to yvals, which must have length 4.*/\n\nstatic void LtEdgeBases(double x, double h, double *restrict yvals) {\n\tdouble *res = yvals;\n\tdouble scale = x*x;\n\tscale *= scale;\n\n\t//zeroth derivative basis polynomial\n\t*res = FMA_m(FMA_m(FMA_m(105.0/32.0, x, -2.0), x, -385.0/32.0), x, 15.0/2.0);\n\t*res = FMA_m(FMA_m(FMA_m(*res, x, 495/32.0), x, -10.0), x, -231.0/32.0);\n\t*res = FMA_m(*res, x, 5.0) * scale;\n\n\t//first derivative basis polynomial\n\t++res;\n\tscale *= h;\n\t*res = FMA_m(FMA_m(FMA_m(41.0/32.0, x, -29.0/32.0), x, -145.0/32.0), x, 105.0/32.0);\n\t*res = FMA_m(FMA_m(FMA_m(*res, x, 175.0/32.0), x, -131.0/32.0), x, -71.0/32.0);\n\t*res = FMA_m(*res, x, 55.0/32.0) * scale;\n\n\t//second derivative basis polynomial\n\t++res;\n\tscale *= h;\n\t*res = FMA_m(FMA_m(FMA_m(3.0/16.0, x, -5.0/32.0), x, -5.0/8.0), x, 17.0/32.0);\n\t*res = FMA_m(FMA_m(FMA_m(*res, x, 11.0/16.0), x, -19.0/32.0), x, -1.0/4.0);\n\t*res = FMA_m(*res, x, 7.0/32.0) * scale;\n\n\t//third derivative basis polynomial\n\t++res;\n\tscale *= h;\n\t*res = FMA_m(FMA_m(FMA_m(1.0/96.0, x, -1.0/96.0), x, -1.0/32.0), x, 1.0/32.0);\n\t*res = FMA_m(FMA_m(FMA_m(*res, x, 1.0/32.0), x, -1.0/32.0), x, -1.0/96.0);\n\t*res = FMA_m(*res, x, 1.0/96.0) * scale;\n\n\treturn;\n}\n\nstatic inline void RtEdgeBases(double x, double h, double *restrict yvals) {\n\tLtEdgeBases(-x, h, yvals);\n\tyvals[1] *= -1.0;\n\tyvals[3] *= -1.0;\n\n\treturn;\n}\n\nstatic void centerBases(double x, double h, double *restrict yvals) {\n\tdouble *res = yvals;\n\tdouble x2 = x*x;\n\tdouble scale = h;\n\n\t//zeroth derivative basis polynomial\n\t*res = FMA_m(FMA_m(FMA_m(4.0, x2, -15.0), x2, 20.0), x2, -10.0);\n\t*res = FMA_m(*res, x2*x2, 1.0);\n\n\t//first derivative basis polynomial\n\t++res;\n\t*res = (*(res-1)) * x * h;\n\n\t//second derivative basis polynomial\n\t++res;\n\tscale *= h;\n\t*res = FMA_m(FMA_m(FMA_m(0.5, x2, -2.0), x2, 3.0), x2, -2.0);\n\t*res = FMA_m(*res, x2, 0.5) * x2 * scale;\n\n\t//third derivative basis polynomial\n\t++res;\n\t*res = (*(res-1)) * x * h / 3.0;\n\n\treturn;\n}\n\n\n//Computes Einverse and its first two derivatives\nstatic void Dc0Derivatives(UniverseLCDM *uni, double invscale, double *results) {\n\tdouble rootarg, E, scale;\n\tdouble *res, *coeff;\n\n\tif ( uni->flat ) {\n\t\trootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter);\n\t\trootarg = FMA_m(rootarg, invscale * invscale * invscale, uni->OmegaLambda );\n\t}\n\telse {\n\t\trootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter);\n\t\trootarg = FMA_m(rootarg, invscale, uni->OmegaCurvature);\n\t\trootarg = FMA_m(rootarg, invscale * invscale, uni->OmegaLambda );\n\t}\n\n\tE = sqrt(rootarg);\n\tres = results;\n\n\t//First order derivative\n\tscale = E / rootarg;\n\t*res = scale;\n\n\t//Second order derivative\n\t++res;\n\tcoeff = uni->Dc0_2ndDerCoeffs;\n\t*res = FMA_m(FMA_m(coeff[2], invscale, coeff[1]), invscale, coeff[0]) * invscale;\n\tscale /= rootarg;\n\t*res *= scale;\n\n\t//Third order derivative\n\t++res;\n\tcoeff = uni->Dc0_3rdDerCoeffs;\n\t*res = FMA_m(FMA_m(FMA_m(coeff[6], invscale, coeff[5]), invscale, coeff[4]), invscale, coeff[3]);\n\t*res = FMA_m(FMA_m(FMA_m(*res, invscale, coeff[2]), invscale, coeff[1]), invscale, coeff[0]);\n\tscale /= rootarg;\n\t*res *= scale;\n\n\treturn;\n}\n\n\n//Computes the first four derivatives of tL0\nstatic void tL0Derivatives(UniverseLCDM *uni, double invscale, double *results) {\n\tdouble rootarg, E, scale, scalestep;\n\tdouble *res, *coeffs;\n\n\tif ( uni->flat ) {\n\t\trootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter);\n\t\trootarg = FMA_m(rootarg, invscale * invscale * invscale, uni->OmegaLambda );\n\t}\n\telse {\n\t\trootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter);\n\t\trootarg = FMA_m(rootarg, invscale, uni->OmegaCurvature);\n\t\trootarg = FMA_m(rootarg, invscale * invscale, uni->OmegaLambda );\n\t}\n\n\tE = sqrt(rootarg);\n\tres = results;\n\n\t//First order derivative\n\tscalestep = invscale * rootarg;\n\tscale = E / scalestep;\n\t*res = scale;\n\n\t//Second order derivative\n\t++res;\n\tcoeffs = uni->tL0_2ndDerCoeffs;\n\t*res = FMA_m(FMA_m(coeffs[4], invscale, coeffs[3]), invscale, coeffs[2]);\n\t*res = FMA_m(FMA_m(*res, invscale, coeffs[1]), invscale, coeffs[0]);\n\tscale /= scalestep;\n\t*res *= scale;\n\n\t//Third order derivative\n\t++res;\n\tcoeffs = uni->tL0_3rdDerCoeffs;\n\t*res = FMA_m(FMA_m(FMA_m(coeffs[8], invscale, coeffs[7]), invscale, coeffs[6]), invscale, coeffs[5]);\n\t*res = FMA_m(FMA_m(FMA_m(*res, invscale, coeffs[4]), invscale, coeffs[3]), invscale, coeffs[2]);\n\t*res = FMA_m(FMA_m(*res, invscale, coeffs[1]), invscale, coeffs[0]);\n\tscale /= scalestep;\n\t*res *= scale;\n\n\treturn;\n}\n\n\n//Used for computing the cached integral values\nstatic double MeanValueInterval(double sampleSpacing, double *leftFuncDirs,\n\t\t\t\t\t\tdouble *centerFuncDirs, double *rightFuncDirs) {\n\tdouble result;\n\tdouble x = sampleSpacing * sampleSpacing;\n\n\tresult = (-FMA_m(-32.0, centerFuncDirs[2], leftFuncDirs[2] + rightFuncDirs[2] ) \\\n\t\t* (1.0/630.0));\n\n\tresult = FMA_m(result, x, \\\n\t\tFMA_m(32.0, centerFuncDirs[0], 5.0*(leftFuncDirs[0] + rightFuncDirs[0])) \\\n\t\t* (1.0/42.0));\n\n\treturn result;\n}\n\n\nstatic double Einv(UniverseLCDM *uni, double invscale) {\n\tdouble rootarg;\n\n\tif ( uni->flat ) {\n\t\trootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter);\n\t\trootarg = FMA_m(rootarg, invscale * invscale * invscale, uni->OmegaLambda );\n\t}\n\telse {\n\t\trootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter);\n\t\trootarg = FMA_m(rootarg, invscale, uni->OmegaCurvature);\n\t\trootarg = FMA_m(rootarg, invscale * invscale, uni->OmegaLambda );\n\t}\n\n\treturn sqrt(rootarg) / rootarg;\n}\n\nstatic double dDc0_dz_gsl(double ainv, void *p) {\n\treturn Einv((UniverseLCDM *)p, ainv);\n}\n\ndouble dDc0_dz_Cosmic(UniverseLCDM *uni, double z) {\n\treturn Einv(uni, 1.0 + z);\n}\n\ndouble dDc_dz_Cosmic(UniverseLCDM *uni, double z) {\n\treturn Einv(uni, 1.0 + z) * uni->DH;\n}\n\n\ndouble dtL0_dz_Cosmic(UniverseLCDM *uni, double z) {\n\tdouble invscale = 1.0 + z;\n\treturn Einv(uni, invscale) / invscale;\n}\n\nstatic double dtL0_dz_gsl(double ainv, void *p) {\n\treturn Einv((UniverseLCDM *)p, ainv) / ainv;\n}\n\n\ndouble dtL_dz_Cosmic(UniverseLCDM *uni, double z) {\n\tdouble invscale = 1.0 + z;\n\treturn Einv(uni, invscale) / invscale * uni->tH;\n}\n\n\nbool InitUniverse(UniverseLCDM *uni, double H0, double OmegaL,\n\t\t\t\t\tdouble OmegaM, double OmegaR, bool flat, bool GSLcache ) {\n\tdouble OmegaK;\n\n\tuni->F_DcT0 = &NotImplementedFunc;\n\tuni->F_Vc0 = &NotImplementedFunc;\n\tuni->F_DcT0Inv = &NotImplementedInvFunc;\n\tuni->F_Vc0Inv = &NotImplementedInvFunc;\n\n\tif ( H0 < 0.0 || OmegaM < 0.0 || OmegaR < 0.0 ) {\n\t\tdouble *f;\n\n\t\tfprintf(stderr, \"InitUniverse: unphysical universe.%s\",\n\t\t\t\" All of the following must be positive:\\n\");\n\t\tfprintf(stderr, \"H0 = %.4g, OmegaM=%.4g, OmegaR=%.4g\\n\", H0, OmegaM, OmegaR);\n\n\t\tuni->OmegaLambda = NAN;\n\t\tuni->OmegaMatter = NAN;\n\t\tuni->OmegaRelativistic = NAN;\n\t\tuni->OmegaCurvature = NAN;\n\t\tuni->H0 = NAN;\n\t\tuni->h = NAN;\n\t\tuni->tH = NAN;\n\t\tuni->DH = NAN;\n\t\tuni->VH = NAN;\n\t\tuni->age0 = NAN;\n\t\tuni->zLastTurn = NAN;\n\t\tuni->zNextTurn = NAN;\n\t\tuni->CacheValid = false;\n\n\t\tfor (f = uni->Dc0_2ndDerCoeffs; f < uni->Dc0_2ndDerCoeffs+3; ++f) {\n\t\t\t*f = NAN;\n\t\t}\n\n\t\tfor (f = uni->Dc0_3rdDerCoeffs; f < uni->Dc0_3rdDerCoeffs+7; ++f) {\n\t\t\t*f = NAN;\n\t\t}\n\n\t\tfor (f = uni->tL0_2ndDerCoeffs; f < uni->tL0_2ndDerCoeffs+5; ++f) {\n\t\t\t*f = NAN;\n\t\t}\n\n\t\tfor (f = uni->tL0_3rdDerCoeffs; f < uni->tL0_3rdDerCoeffs+9; ++f) {\n\t\t\t*f = NAN;\n\t\t}\n\n\t\tfor (f = uni->Dc0_TaylorCoeffs; f < uni->Dc0_TaylorCoeffs+5; ++f) {\n\t\t\t*f = NAN;\n\t\t}\n\n\t\tfor (f = uni->tL0_TaylorCoeffs; f < uni->tL0_TaylorCoeffs+5; ++f) {\n\t\t\t*f = NAN;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tuni->H0 = H0;\n\tuni->OmegaMatter = OmegaM;\n\tuni->OmegaRelativistic = OmegaR;\n\tuni->flat = flat;\n\n\tif ( flat == true ) {\n\t\tOmegaL = 1.0 - OmegaM - OmegaR;\n\t\tOmegaK = 0.0;\n\t}\n\telse {\n\t\tOmegaK = 1.0 - ( OmegaM + OmegaL + OmegaR );\n\t}\n\tuni->OmegaCurvature = OmegaK;\n\tuni->OmegaLambda = OmegaL;\n\n\tuni->h = H0 * 0.01 * 1e-3 * MeterPerMpc;\n\tuni->tH = 1.0 / H0;\n\tuni->DH = clight / H0;\n\tuni->VH = uni->DH * uni->DH * uni->DH;\n\n\t{\n\t\t//Find the turning points (if they exist)\n\t\tint polyorder;\n\n\t\tgsl_poly_complex_workspace *scratch;\n\n\t\tconst double poly[5] = { OmegaL, 0.0, uni->OmegaCurvature, OmegaM, OmegaR };\n\t\tdouble roots[8];\n\t\tint err;\n\t\tdouble *iPart, *rPart;\n\n\t\tif (OmegaR > 0.0) {\n\t\t\tpolyorder = 4;\n\t\t} else if (OmegaM > 0.0) {\n\t\t\tpolyorder = 3;\n\t\t} else if (fabs(OmegaK) > NumericallyFlat) {\n\t\t\tpolyorder = 2;\n\t\t} else {\n\t\t\tpolyorder = 0;\n\t\t}\n\n\t\tif (polyorder > 0) {\n\t\t\tscratch = gsl_poly_complex_workspace_alloc( polyorder + 1 );\n\t\t\terr = gsl_poly_complex_solve( poly, polyorder + 1, scratch, roots );\n\t\t\tif ( err == GSL_EFAILED ) {\n\t\t\t\tfprintf(stderr, \"GSL failed to find all of the candidate turning points%s\",\n\t\t\t\t\t\"for this cosmology:\\n\");\n\t\t\t\tfprintf(stderr, \"OmegaL = %.4f, OmegaK = %.4f, OmegaM = %.4f, OmegaR = %.4f\\n\",\n\t\t\t\t\tOmegaL, uni->OmegaCurvature, OmegaM, OmegaR);\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tuni->zLastTurn = INFINITY;\n\t\tuni->zNextTurn = -1.0;\n\n\t\tfor (rPart = roots; rPart < roots + 2*polyorder-1; rPart += 2) {\n\t\t\tiPart = rPart + 1;\n\n\t\t\tif (fabs(*iPart) < IMAGINARYTOL && *rPart > 0.0) {\n\t\t\t\t*rPart -= 1.0; //convert inverse scale to z\n\n\t\t\t\tif (*rPart < uni->zLastTurn && *rPart > 0.0) {\n\t\t\t\t\tuni->zLastTurn = *rPart;\n\t\t\t\t}\n\t\t\t\telse if (*rPart > uni->zNextTurn && *rPart <= 0.0) {\n\t\t\t\t\tuni->zNextTurn = *rPart;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t{\n\t\t//Init the derivative parameters\n\t\tdouble *f;\n\t\tdouble OmegaK = uni->OmegaCurvature;\n\n\t\t//Dc0 Second derivative parameters\n\t\tf = &(uni->Dc0_2ndDerCoeffs[0]);\n\t\tf[0] = - OmegaK;\n\t\tf[1] = - 1.5 * OmegaM;\n\t\tf[2] = -2.0 * OmegaR;\n\n\t\t//Dc0 Third derivative parameters\n\t\tf = uni->Dc0_3rdDerCoeffs;\n\t\tf[0] = - OmegaK * OmegaL;\n\t\tf[1] = -3.0 * OmegaL * OmegaM;\n\t\tf[2] = 2.0 * OmegaK * OmegaK - 6.0 * OmegaL * OmegaR;\n\t\tf[3] = 5.0 * OmegaK * OmegaM;\n\t\tf[4] = 5.0 * OmegaK * OmegaR + 3.75 * OmegaM * OmegaM;\n\t\tf[5] = 9.0 * OmegaM * OmegaR;\n\t\tf[6] = 6.0 * OmegaR * OmegaR;\n\n\n\t\t//tL0 Second derivative parameters\n\t\tf = uni->tL0_2ndDerCoeffs;\n\t\tf[0] = -OmegaL;\n\t\tf[1] = 0.0;\n\t\tf[2] = -2.0 * OmegaK;\n\t\tf[3] = -2.5 * OmegaM;\n\t\tf[4] = -3.0 * OmegaR;\n\n\t\t//tL0 Third derivative parameters\n\t\tf = uni->tL0_3rdDerCoeffs;\n\t\tf[0] = 2.0 * OmegaL * OmegaL;\n\t\tf[1] = 0.0;\n\t\tf[2] = 5.0 * OmegaK * OmegaL;\n\t\tf[3] = 4.0 * OmegaL * OmegaM;\n\t\tf[4] = 2.0 * OmegaL * OmegaR + 6.0 * OmegaK * OmegaK;\n\t\tf[5] = 14.0 * OmegaK * OmegaM;\n\t\tf[6] = 15.0 * OmegaK * OmegaR + 8.75 * OmegaM * OmegaM;\n\t\tf[7] = 20.0 * OmegaM * OmegaR;\n\t\tf[8] = 12.0 * OmegaR * OmegaR;\n\n\t\t//Dc0 Low redshift Taylor expansion parameters\n\t\tf = uni->Dc0_TaylorCoeffs;\n\t\tf[0] = 1.0;\n\n\t\tf[1] = (- OmegaR \\\n\t\t\t\t- 0.5 * OmegaM \\\n\t\t\t\t+ OmegaL \\\n\t\t\t\t- 1.0) * 0.5;\n\n\t\tf[2] = (1.5 * OmegaR * OmegaR \\\n\t\t\t\t+ 1.5 * OmegaR * OmegaM \\\n\t\t\t\t- 3.0 * OmegaL * OmegaR \\\n\t\t\t\t+ 0.5 * OmegaR \\\n\t\t\t\t+ 0.375 * OmegaM * OmegaM \\\n\t\t\t\t- 1.5 * OmegaL * OmegaM \\\n\t\t\t\t+ 0.5 * OmegaM \\\n\t\t\t\t+ 1.5 * OmegaL * OmegaL \\\n\t\t\t\t- 2.5 * OmegaL \\\n\t\t\t\t+ 1.0 ) / 3.0;\n\n\t\tf[3] = ( - 2.5 * OmegaR * OmegaR * OmegaR \\\n\t\t\t\t- 3.75 * OmegaR * OmegaR * OmegaM \\\n\t\t\t\t+ 7.5 * OmegaR * OmegaR * OmegaL \\\n\t\t\t\t- 1.875 * OmegaR * OmegaM * OmegaM \\\n\t\t\t\t+ 7.5 * OmegaR * OmegaM * OmegaL \\\n\t\t\t\t- 0.75 * OmegaR * OmegaM \\\n\t\t\t\t- 7.5 * OmegaR * OmegaL * OmegaL \\\n\t\t\t\t+ 6.0 * OmegaR * OmegaL \\\n\t\t\t\t- 0.5 * OmegaR \\\n\t\t\t\t- 0.3125 * OmegaM * OmegaM * OmegaM \\\n\t\t\t\t+ 1.875 * OmegaM * OmegaM * OmegaL \\\n\t\t\t\t- 0.375 * OmegaM * OmegaM \\\n\t\t\t\t- 3.75 * OmegaM * OmegaL * OmegaL \\\n\t\t\t\t+ 3.75 * OmegaM * OmegaL \\\n\t\t\t\t- 0.5 * OmegaM \\\n\t\t\t\t+ 2.5 * OmegaL * OmegaL * OmegaL \\\n\t\t\t\t- 6.0 * OmegaL * OmegaL \\\n\t\t\t\t+ 4.5 * OmegaL \\\n\t\t\t\t- 1.0 ) * 0.25;\n\n\t\tf[4] = ( 4.375 * OmegaR * OmegaR * OmegaR * OmegaR \\\n\t\t\t\t+ 8.75 * OmegaM * OmegaR * OmegaR * OmegaR \\\n\t\t\t\t- 17.5 * OmegaL * OmegaR * OmegaR * OmegaR \\\n\t\t\t\t- 1.25 * OmegaR * OmegaR * OmegaR \\\n\t\t\t\t+ 6.5625 * OmegaM * OmegaM * OmegaR * OmegaR \\\n\t\t\t\t- 26.25 * OmegaM * OmegaL * OmegaR * OmegaR \\\n\t\t\t\t+ 26.25 * OmegaL * OmegaL * OmegaR * OmegaR \\\n\t\t\t\t- 11.25 * OmegaL * OmegaR * OmegaR \\\n\t\t\t\t+ 0.375 * OmegaR * OmegaR \\\n\t\t\t\t+ 2.1875 * OmegaM * OmegaM * OmegaM * OmegaR \\\n\t\t\t\t- 13.125 * OmegaL * OmegaM * OmegaM * OmegaR \\\n\t\t\t\t+ 0.9375 * OmegaM * OmegaM * OmegaR \\\n\t\t\t\t+ 26.25 * OmegaL * OmegaL * OmegaM * OmegaR \\\n\t\t\t\t- 15.0 * OmegaL * OmegaM * OmegaR \\\n\t\t\t\t+ 0.75 * OmegaM * OmegaR \\\n\t\t\t\t- 17.5 * OmegaL * OmegaL * OmegaL * OmegaR \\\n\t\t\t\t+ 26.25 * OmegaL * OmegaL * OmegaR \\\n\t\t\t\t- 9.75 * OmegaL * OmegaR \\\n\t\t\t\t+ 0.5 * OmegaR \\\n\t\t\t\t+ 0.2734375 * OmegaM * OmegaM * OmegaM * OmegaM \\\n\t\t\t\t- 2.1875 * OmegaL * OmegaM * OmegaM * OmegaM \\\n\t\t\t\t+ 0.3125 * OmegaM * OmegaM * OmegaM \\\n\t\t\t\t+ 6.5625 * OmegaL * OmegaL * OmegaM * OmegaM \\\n\t\t\t\t- 4.6875 * OmegaL * OmegaM * OmegaM \\\n\t\t\t\t+ 0.375 * OmegaM * OmegaM \\\n\t\t\t\t- 8.75 * OmegaL * OmegaL * OmegaL * OmegaM \\\n\t\t\t\t+ 15.0 * OmegaL * OmegaL * OmegaM \\\n\t\t\t\t- 6.75 * OmegaL * OmegaM \\\n\t\t\t\t+ 0.5 * OmegaM \\\n\t\t\t\t+ 4.375 * OmegaL * OmegaL * OmegaL * OmegaL \\\n\t\t\t\t- 13.75 * OmegaL * OmegaL * OmegaL \\\n\t\t\t\t+ 15.375 * OmegaL * OmegaL \\\n\t\t\t\t- 7.0 * OmegaL \\\n\t\t\t\t+ 1.0 ) / 5.0;\n\n\t\t//tL0 Low redshift Taylor expansion parameters\n\t\tf = uni->tL0_TaylorCoeffs;\n\t\tf[0] = 1.0;\n\n\t\tf[1] = ( - OmegaR \\\n\t\t\t\t- 0.5 * OmegaM \\\n\t\t\t\t+ OmegaL \\\n\t\t\t\t- 2.0 ) * 0.5;\n\n\t\tf[2] = ( 0.5 * OmegaR * OmegaR \\\n\t\t\t\t+ 0.5 * OmegaM * OmegaR \\\n\t\t\t\t- OmegaL * OmegaR \\\n\t\t\t\t+ 0.5 * OmegaR \\\n\t\t\t\t+ 0.125 * OmegaM * OmegaM \\\n\t\t\t\t- 0.5 * OmegaL * OmegaM \\\n\t\t\t\t+ OmegaM / 3.0 \\\n\t\t\t\t+ 0.5 * OmegaL * OmegaL \\\n\t\t\t\t- 7.0 * OmegaL / 6.0 \\\n\t\t\t\t+ 1.0 );\n\n\t\tf[3] = ( - 2.5 * OmegaR * OmegaR * OmegaR \\\n\t\t\t\t- 3.75 * OmegaM * OmegaR * OmegaR \\\n\t\t\t\t+ 7.5 * OmegaL * OmegaR * OmegaR \\\n\t\t\t\t- 1.5 * OmegaR * OmegaR \\\n\t\t\t\t- 1.875 * OmegaM * OmegaM * OmegaR \\\n\t\t\t\t+ 7.5 * OmegaL * OmegaM * OmegaR \\\n\t\t\t\t+ 2.25 * OmegaM * OmegaR \\\n\t\t\t\t- 7.5 * OmegaL * OmegaL * OmegaR \\\n\t\t\t\t+ 9.0 * OmegaL * OmegaR \\\n\t\t\t\t- 2.0 * OmegaR \\\n\t\t\t\t- 0.3125 * OmegaM * OmegaM * OmegaM \\\n\t\t\t\t+ 1.875 * OmegaL * OmegaM * OmegaM \\\n\t\t\t\t- 0.75 * OmegaM * OmegaM \\\n\t\t\t\t- 3.75 * OmegaL * OmegaL * OmegaM \\\n\t\t\t\t+ 5.25 * OmegaL * OmegaM \\\n\t\t\t\t- 1.5 * OmegaM \\\n\t\t\t\t+ 2.5 * OmegaL * OmegaL * OmegaL \\\n\t\t\t\t- 7.5 * OmegaL * OmegaL \\\n\t\t\t\t+ 8.0 * OmegaL \\\n\t\t\t\t- 4.0 ) * 0.25;\n\n\t\tf[4] = ( 4.375 * OmegaR * OmegaR * OmegaR * OmegaR \\\n\t\t\t\t+ 8.75 * OmegaM * OmegaR * OmegaR * OmegaR \\\n\t\t\t\t- 17.5 * OmegaL * OmegaR * OmegaR * OmegaR \\\n\t\t\t\t+ 1.25 * OmegaR * OmegaR * OmegaR \\\n\t\t\t\t+ 6.5625 * OmegaM * OmegaM * OmegaR * OmegaR \\\n\t\t\t\t- 26.25 * OmegaL * OmegaM * OmegaR * OmegaR \\\n\t\t\t\t+ 3.75 * OmegaM * OmegaR * OmegaR \\\n\t\t\t\t+ 26.25 * OmegaL * OmegaL * OmegaR * OmegaR \\\n\t\t\t\t- 18.75 * OmegaL * OmegaR * OmegaR \\\n\t\t\t\t+ 1.875 * OmegaR * OmegaR \\\n\t\t\t\t+ 2.1875 * OmegaM * OmegaM * OmegaM * OmegaR \\\n\t\t\t\t- 13.125 * OmegaL * OmegaM * OmegaM * OmegaR \\\n\t\t\t\t+ 2.8125 * OmegaM * OmegaM * OmegaR \\\n\t\t\t\t+ 26.25 * OmegaL * OmegaL * OmegaM * OmegaR \\\n\t\t\t\t- 22.5 * OmegaL * OmegaM * OmegaR \\\n\t\t\t\t+ 3.0 * OmegaM * OmegaR \\\n\t\t\t\t- 17.5 * OmegaL * OmegaL * OmegaL * OmegaR \\\n\t\t\t\t+ 33.75 * OmegaL * OmegaL * OmegaR \\\n\t\t\t\t- 18.75 * OmegaL * OmegaR \\\n\t\t\t\t+ 2.5 * OmegaR \\\n\t\t\t\t+ 0.2734375 * OmegaM * OmegaM * OmegaM * OmegaM \\\n\t\t\t\t- 2.1875 * OmegaL * OmegaM * OmegaM * OmegaM \\\n\t\t\t\t+ 0.625 * OmegaM * OmegaM * OmegaM \\\n\t\t\t\t+ 6.5625 * OmegaL * OmegaL * OmegaM * OmegaM \\\n\t\t\t\t- 6.5625 * OmegaL * OmegaM * OmegaM \\\n\t\t\t\t+ 1.125 * OmegaM * OmegaM \\\n\t\t\t\t- 8.75 * OmegaL * OmegaL * OmegaL * OmegaM \\\n\t\t\t\t+ 18.75 * OmegaL * OmegaL * OmegaM \\\n\t\t\t\t- 12.0 * OmegaL * OmegaM \\\n\t\t\t\t+ 2.0 * OmegaM \\\n\t\t\t\t+ 4.375 * OmegaL * OmegaL * OmegaL * OmegaL \\\n\t\t\t\t- 16.25 * OmegaL * OmegaL * OmegaL \\\n\t\t\t\t+ 22.875 * OmegaL * OmegaL \\\n\t\t\t\t- 15.0 * OmegaL \\\n\t\t\t\t+ 5.0 ) / 5.0;\n\t}\n\n\n\t//Cache only works if there are no turning points in the cache interval\n\tif (uni->zLastTurn > zMaxInterp && uni->zLastTurn > zMinInterp && \\\n\t\tuni->zNextTurn < zMaxInterp && uni->zNextTurn < zMinInterp ) {\n\n\t\tdouble errest;\n\t\tdouble cur_Dc0, cur_tL0;\n\t\tCachePoint *curPt_Dc0, *curPt_tL0;\n\t\tdouble curAinv = 1.0 + zMinInterp;\n\t\tint idx;\n\t\tint DcintegratorStatus, tLintegratorStatus;\n\t\tgsl_integration_workspace *scratch;\n\t\tgsl_function Dintegrand, tLintegrand;\n\n\t\t//Integrate to the left side of the cache using GSL\n\t\tscratch = gsl_integration_workspace_alloc( MaxGSLlevel );\n\n\t\tDintegrand.function = &dDc0_dz_gsl;\n\t\tDintegrand.params = (void *)uni;\n\t\tDcintegratorStatus = gsl_integration_qag( &Dintegrand, \\\n\t\t\t1.0, curAinv, \\\n\t\t\tGSLCacheEpsabs, GSLCacheEpsrel, MaxGSLlevel, GSL_INTEG_GAUSS51, \\\n\t\t\tscratch, &cur_Dc0, &errest);\n\n\t\ttLintegrand.function = &dtL0_dz_gsl;\n\t\ttLintegrand.params = (void *)uni;\n\t\ttLintegratorStatus = gsl_integration_qag( &tLintegrand, \\\n\t\t\t1.0, curAinv, \\\n\t\t\tGSLCacheEpsabs, GSLCacheEpsrel, MaxGSLlevel, GSL_INTEG_GAUSS51, \\\n\t\t\tscratch, &cur_tL0, &errest);\n\n\t\tif (DcintegratorStatus == GSL_EFAILED || tLintegratorStatus==GSL_EFAILED){\n\t\t\tuni->CacheValid = false;\n\t\t}\n\n\t\telse if (GSLcache) {\n\t\t\tdouble Dc0ders[3], tL0ders[3];\n\n\t\t\tuni->CacheValid = true;\n\t\t\tcurPt_Dc0 = uni->Dc0Cache;\n\t\t\tcurPt_tL0 = uni->tL0Cache;\n\t\t\tcurPt_Dc0->ders[0] = cur_Dc0;\n\t\t\tcurPt_tL0->ders[0] = cur_tL0;\n\t\t\tfor (idx = 1; idx < InterpIntervals + 1; ++idx) {\n\t\t\t\t++curPt_Dc0;\n\t\t\t\t++curPt_tL0;\n\t\t\t\tcurAinv = 1.0 + zMinInterp + zInterpCellWidth * (double) idx;\n\n\t\t\t\tDcintegratorStatus = gsl_integration_qag( &Dintegrand, \\\n\t\t\t\t1.0, curAinv, \\\n\t\t\t\tGSLCacheEpsabs, GSLCacheEpsrel, MaxGSLlevel, GSL_INTEG_GAUSS51, \\\n\t\t\t\tscratch, &cur_Dc0, &errest);\n\n\t\t\t\ttLintegratorStatus = gsl_integration_qag( &tLintegrand, \\\n\t\t\t\t1.0, curAinv, \\\n\t\t\t\tGSLCacheEpsabs, GSLCacheEpsrel, MaxGSLlevel, GSL_INTEG_GAUSS51, \\\n\t\t\t\tscratch, &cur_tL0, &errest);\n\n\t\t\t\tif (DcintegratorStatus == GSL_EFAILED || \\\n\t\t\t\t\ttLintegratorStatus == GSL_EFAILED) {\n\t\t\t\t\tuni->CacheValid = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcurPt_Dc0->ders[0] = cur_Dc0;\n\t\t\t\tcurPt_tL0->ders[0] = cur_tL0;\n\n\t\t\t\tDc0Derivatives(uni, curAinv, Dc0ders);\n\t\t\t\ttL0Derivatives(uni, curAinv, tL0ders);\n\t\t\t\tmemcpy( &(curPt_Dc0->ders[1]), Dc0ders, 3 * sizeof(double) );\n\t\t\t\tmemcpy( &(curPt_tL0->ders[1]), tL0ders, 3 * sizeof(double) );\n\t\t\t}\n\t\t}\n\n\t\telse {\n\t\t\tdouble deltaDc0, deltatL0;\n\t\t\tint intervalsPerCell = 4;\n\t\t\tdouble deltazinteg = zInterpCellWidth / (double) (intervalsPerCell << 1);\n\t\t\tdouble deltazinteg2 = 2.0 * deltazinteg;\n\t\t\tdouble Diffs_Dc0[9], Diffs_tL0[9];\n\t\t\tdouble *leftDiffs_Dc0, *centDiffs_Dc0, *rightDiffs_Dc0;\n\t\t\tdouble *leftDiffs_tL0, *centDiffs_tL0, *rightDiffs_tL0;\n\t\t\tdouble *temp;\n\t\t\tint cacheInt = 0;\n\n\t\t\t//Do a rolling integral using a 3 point 0-3 derivative rule to accumulate\n\t\t\t//the cache.\n\t\t\tleftDiffs_Dc0 = Diffs_Dc0;\n\t\t\tcentDiffs_Dc0 = leftDiffs_Dc0 + 3;\n\t\t\trightDiffs_Dc0 = centDiffs_Dc0 + 3;\n\t\t\tleftDiffs_tL0 = Diffs_tL0;\n\t\t\tcentDiffs_tL0 = leftDiffs_tL0 + 3;\n\t\t\trightDiffs_tL0 = centDiffs_tL0 + 3;\n\n\t\t\tDc0Derivatives(uni, curAinv, rightDiffs_Dc0);\n\t\t\ttL0Derivatives(uni, curAinv, rightDiffs_tL0);\n\n\t\t\tcurPt_Dc0 = uni->Dc0Cache;\n\t\t\tcurPt_tL0 = uni->tL0Cache;\n\t\t\tcurPt_Dc0->ders[0] = cur_Dc0;\n\t\t\tcurPt_tL0->ders[0] = cur_tL0;\n\t\t\tmemcpy( &(curPt_Dc0->ders[1]), rightDiffs_Dc0, 3 * sizeof(double) );\n\t\t\tmemcpy( &(curPt_tL0->ders[1]), rightDiffs_tL0, 3 * sizeof(double) );\n\n\t\t\tdeltaDc0 = 0.0;\n\t\t\tdeltatL0 = 0.0;\n\t\t\tfor (idx = 0; idx < InterpIntervals * intervalsPerCell; ++idx) {\n\t\t\t\t//swap left and right diffs pointers\n\t\t\t\ttemp = leftDiffs_Dc0;\n\t\t\t\tleftDiffs_Dc0 = rightDiffs_Dc0;\n\t\t\t\trightDiffs_Dc0 = temp;\n\n\t\t\t\ttemp = leftDiffs_tL0;\n\t\t\t\tleftDiffs_tL0 = rightDiffs_tL0;\n\t\t\t\trightDiffs_tL0 = temp;\n\n\t\t\t\t//Fill in the center and right Diffs pointers\n\t\t\t\tcurAinv += deltazinteg;\n\t\t\t\tDc0Derivatives(uni, curAinv, centDiffs_Dc0);\n\t\t\t\ttL0Derivatives(uni, curAinv, centDiffs_tL0);\n\n\t\t\t\tcurAinv += deltazinteg;\n\t\t\t\tDc0Derivatives(uni, curAinv, rightDiffs_Dc0);\n\t\t\t\ttL0Derivatives(uni, curAinv, rightDiffs_tL0);\n\n\t\t\t\tdeltaDc0 = FMA_m(deltazinteg2, \\\n\t\t\t\t\tMeanValueInterval(deltazinteg, \\\n\t\t\t\t\t\tleftDiffs_Dc0, centDiffs_Dc0, rightDiffs_Dc0), deltaDc0);\n\t\t\t\tdeltatL0 = FMA_m(deltazinteg2, \\\n\t\t\t\t\tMeanValueInterval(deltazinteg, \\\n\t\t\t\t\t\tleftDiffs_tL0, centDiffs_tL0, rightDiffs_tL0), deltatL0);\n\n\t\t\t\tcacheInt += 1;\n\t\t\t\tif (cacheInt == intervalsPerCell) {\n\t\t\t\t\t//Cache the right hand side.\n\t\t\t\t\tcacheInt = 0;\n\n\t\t\t\t\tcur_Dc0 += deltaDc0;\n\t\t\t\t\tcur_tL0 += deltatL0;\n\t\t\t\t\tdeltaDc0 = 0.0;\n\t\t\t\t\tdeltatL0 = 0.0;\n\n\t\t\t\t\t++curPt_Dc0;\n\t\t\t\t\t++curPt_tL0;\n\n\t\t\t\t\tcurPt_Dc0->ders[0] = cur_Dc0;\n\t\t\t\t\tcurPt_tL0->ders[0] = cur_tL0;\n\t\t\t\t\tmemcpy( &(curPt_Dc0->ders[1]), rightDiffs_Dc0, 3 * sizeof(double) );\n\t\t\t\t\tmemcpy( &(curPt_tL0->ders[1]), rightDiffs_tL0, 3 * sizeof(double) );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tuni->CacheValid = true;\n\t\t}\n\n\t\tgsl_integration_workspace_free( scratch );\n\t}\n\n\telse {\n\t\tfprintf(stderr, \"Warning: InitUniverse cannot produce an integration cache\\n%s\",\n\t\t\t\"if the cosmology has a turning point in the cache interval.\\n\");\n\t\tuni->CacheValid = false;\n\t}\n\n\n\t{ //Assign function pointers\n\t\tif (uni->flat || fabs(OmegaK) <= NumericallyFlat) {\n\t\t\tuni->F_DcT0 = &DcT0Flat;\n\t\t\tuni->F_Vc0\t= &Vc0Flat;\n\t\t\tuni->F_DcT0Inv = &DcT0InvFlat;\n\t\t\tuni->F_Da0Inv = &Da0InvFlat;\n\t\t\tuni->F_Dl0Inv = &Dl0InvFlat;\n\t\t\tuni->F_Vc0Inv = &Vc0InvFlat;\n\t\t}\n\n\t\telse if (OmegaK < 0.0) {\n\t\t\tuni->F_DcT0 = &DcT0NegK;\n\t\t\tuni->F_Vc0 = &Vc0NegK;\n\t\t\tuni->F_DcT0Inv = &DcT0InvNegK;\n\t\t\tuni->F_Da0Inv = &Da0InvNegK;\n\t\t\tuni->F_Dl0Inv = &Dl0InvNegK;\n\t\t\tuni->F_Vc0Inv = &Vc0InvNegK;\n\t\t}\n\n\t\telse {\n\t\t\tuni->F_DcT0 = &DcT0PosK;\n\t\t\tuni->F_Vc0 = &Vc0PosK;\n\t\t\tuni->F_DcT0Inv = &DcT0InvPosK;\n\t\t\tuni->F_Da0Inv = &Da0InvPosK;\n\t\t\tuni->F_Dl0Inv = &Dl0InvPosK;\n\t\t\tuni->F_Vc0Inv = &Vc0InvPosK;\n\t\t}\n\n\t}\n\n\n\t{//Calculate vital statistics\n\t\tdouble dummy;\n\t\tif (isinf(uni->zLastTurn)) {\n\t\t\tuni->age0 = tL0_Cosmic(uni, INFINITY, true,\n\t\t\t\t1e-6, 1e-6, MaxGSLlevel, &dummy);\n\t\t\tuni->Dc0Max = Dc0_Cosmic(uni, INFINITY, true,\n\t\t\t\t1e-6, 1e-6, MaxGSLlevel, &dummy);\n\n\n\t\t\tuni->tL0LastTurn = NAN;\n\t\t\tuni->Dc0LastTurn = NAN;\n\t\t\tuni->Dc0InvD0max = uni->Dc0Max;\n\t\t}\n\t\telse {\n\t\t\tuni->age0 = INFINITY;\n\t\t\tuni->Dc0Max = INFINITY;\n\n\t\t\tuni->tL0LastTurn = tL0_Cosmic(uni, uni->zLastTurn, true,\n\t\t\t\t1e-6, 1e-6, MaxGSLlevel, &dummy);\n\t\t\tuni->Dc0LastTurn = Dc0_Cosmic(uni, uni->zLastTurn, true,\n\t\t\t\t1e-6, 1e-6, MaxGSLlevel, &dummy);\n\t\t\tuni->Dc0InvD0max = uni->Dc0LastTurn;\n\t\t}\n\n\t\tif (uni->zNextTurn <= -1.0) {\n\t\t\tuni->tL0NextTurn = INFINITY;\n\t\t}\n\t\telse {\n\t\t\tuni->tL0NextTurn = tL0_Cosmic(uni, uni->zNextTurn, true,\n\t\t\t\t1e-6, 1e-6, MaxGSLlevel, &dummy);\n\t\t}\n\n\t\tuni->z_DaMax = FindDa0Max(uni, 0x1.0p-20, 1024);\n\n\t\tif (uni->flat || fabs(OmegaK) <= NumericallyFlat) {\n\t\t\tuni->DcT0Max = uni->Dc0Max;\n\n\t\t\tuni->Vc0Universe = Vc0Flat(uni, uni->zLastTurn, true, \\\n\t\t\t\t1e-6, 1e-6, MaxGSLlevel, &dummy );\n\t\t\tuni->Da0Max = Dc0_Cosmic(uni, uni->z_DaMax, true, \\\n\t\t\t\t1e-6, 1e-6, 128, &dummy) / (1.0 + uni->z_DaMax);\n\t\t}\n\t\telse if (OmegaK < 0.0) {\n\t\t\tdouble N = sqrt(-OmegaK);\n\t\t\tuni->DcT0Max = uni->DH * N / (-OmegaK);\n\t\t\tuni->DcT0Max = MIN( uni->DcT0Max,\n\t\t\t\tsin( N * uni->DcT0Max ) * N / (-OmegaK) );\n\n\t\t\tuni->Vc0Universe = Vc0NegK(uni, uni->zLastTurn, true, \\\n\t\t\t\t1e-6, 1e-6, MaxGSLlevel, &dummy );\n\t\t\tuni->Da0Max = DcT0NegK(uni, uni->z_DaMax, true, \\\n\t\t\t\t1e-6, 1e-6, 128, &dummy) / (1.0 + uni->z_DaMax);\n\t\t}\n\t\telse { //OmegaK > 0.0\n\t\t\tdouble N = sqrt(OmegaK);\n\t\t\tuni->DcT0Max = sinh( N * uni->Dc0Max ) * N / OmegaK;\n\n\t\t\tuni->Vc0Universe = Vc0PosK(uni, uni->zLastTurn, true, \\\n\t\t\t\t1e-6, 1e-6, MaxGSLlevel, &dummy );\n\t\t\tuni->Da0Max = DcT0PosK(uni, uni->z_DaMax, true, \\\n\t\t\t\t1e-6, 1e-6, 128, &dummy) / (1.0 + uni->z_DaMax);\n\t\t}\n\n\t}\n\n\treturn true;\n}\n\n\nUniverseLCDM *MakeUniverse(double H0, double OmegaL,\n\t\t\t\t\tdouble OmegaM, double OmegaR, bool flat, bool GSLcache) {\n\tUniverseLCDM *uni;\n\tbool unigood;\n\n\tif ( H0 < 0.0 || OmegaM < 0.0 || OmegaR < 0.0 ) {\n\t\tuni = NULL;\n\t}\n\telse {\n\t\tuni = (UniverseLCDM *) malloc( sizeof (UniverseLCDM) );\n\t\tunigood = InitUniverse(uni, H0, OmegaL, OmegaM, OmegaR, flat,\\\n\t\t\t\t\t\t\t\tGSLcache);\n\n\t\tif (unigood == false) {\n\t\t\tfree(uni);\n\t\t\tuni = NULL;\n\t\t}\n\t}\n\n\treturn uni;\n}\n\n\nvoid FreeUniverse(UniverseLCDM *uni) {\n\t/*if (uni != NULL) {\n\t\tfree(uni);\n\t}*/\n\treturn;\n}\n\n\ndouble Dc0_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\tdouble result, weight, zpos;\n\n\tif (z < -1.0) {\n\t\tfprintf(stderr, \"Dc0_Cosmic: invalid redshift. Redshifts must be >= -1.0\\n\");\n\t\tfprintf(stderr, \"z = %.16e\\n\", z);\n\n\t\treturn NAN;\n\t}\n\telse if (z > uni->zLastTurn || z < uni->zNextTurn) {\n\t\tfprintf(stderr, \"Dc0_Cosmic: invalid redshift. Cannot integrate past turning points.\\n\");\n\t\tfprintf(stderr, \"z = %.16e, zNextTurn = %.16e, zLastTurn = %.16e\\n\",\n\t\t\tz, uni->zNextTurn, uni->zLastTurn );\n\n\t\treturn NAN;\n\t}\n\n\tzpos = fabs(z);\n\tresult = 0.0;\n\tweight = 1.0;\n\n\tif (zpos <= TaylorMaxZ) { //Perform the taylor series calculation\n\t\tdouble *coeffs = uni->Dc0_TaylorCoeffs;\n\n\t\tif (zpos > TaylorInterpMinZ) {\n\t\t\tweight = (TaylorMaxZ - zpos) * TaylorInterpInterval;\n\t\t}\n\t\telse {\n\t\t\tweight = 1.0;\n\t\t}\n\n\t\tresult = FMA_m(FMA_m(coeffs[4], z, coeffs[3]), z, coeffs[2]);\n\t\tresult = FMA_m(FMA_m(result, z, coeffs[1]), z, coeffs[0]) * z * weight;\n\n\t\tweight = 1.0 - weight;\n\t}\n\n\t*abserr = 0.0;\n\tif (fast && uni->CacheValid && z >= zMinInterp && z <= zMaxInterp \\\n\t\t&& zpos > TaylorInterpMinZ) {\n\t\tdouble tempres, zCenter, x;\n\t\tdouble bases[4], *ders;\n\t\tint centeridx;\n\t\tCachePoint *curPt;\n\n\t\t//Use the interpolation cache\n\t\tcenteridx = round((z - zMinInterp) / zInterpCellWidth);\n\t\tcenteridx = CLAMP(centeridx, 1, InterpIntervals);\n\n\t\tzCenter = ((double) centeridx) * zInterpCellWidth + zMinInterp;\n\t\tx = (z - zCenter) / zInterpCellWidth;\n\t\ttempres = 0.0;\n\n\t\tcurPt = uni->Dc0Cache + (centeridx - 1);\n\t\tders = curPt->ders;\n\t\tLtEdgeBases(x, zInterpCellWidth, bases);\n\t\ttempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres));\n\t\ttempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres));\n\n\t\t++curPt;\n\t\tders = curPt->ders;\n\t\tcenterBases(x, zInterpCellWidth, bases);\n\t\ttempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres));\n\t\ttempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres));\n\n\t\t++curPt;\n\t\tders = curPt->ders;\n\t\tRtEdgeBases(x, zInterpCellWidth, bases);\n\t\ttempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres));\n\t\ttempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres));\n\n\t\tresult = FMA_m(weight, tempres, result);\n\t\t*abserr = tempres * pow(x, 12.0);\n\t}\n\n\telse if ( ((zpos > TaylorInterpMinZ && (!fast || !uni->CacheValid)) ||\n\t\tz > zMaxInterp || z < zMinInterp) ) {\n\t\tgsl_integration_workspace *scratch;\n\t\tgsl_function integrand;\n\t\tint DcintegratorStatus;\n\t\tdouble tempres, temperr;\n\n\t\tscratch = gsl_integration_workspace_alloc( limit );\n\n\t\tintegrand.function = &dDc0_dz_gsl;\n\t\tintegrand.params = (void *)uni;\n\n\t\tif (!isinf(z) && \\\n\t\t\t(z >= uni->zLastTurn * 0x1.fffffff8p-1 || \\\n\t\t\t\tz <= uni->zNextTurn * 0x1.fffffff8p-1 || \\\n\t\t\t\tz <= -1.0 * 0x1.fffffff8p-1)) {\n\t\t\tDcintegratorStatus = gsl_integration_qags(&integrand, \\\n\t\t\t\t1.0, 1.0 + z, \\\n\t\t\t\tepsabs, epsrel, limit, \\\n\t\t\t\tscratch, &tempres, &temperr);\n\t\t}\n\n\t\telse if (isinf(z)) {\n\t\t\tDcintegratorStatus = gsl_integration_qagiu(&integrand, \\\n\t\t\t\t1.0, \\\n\t\t\t\tepsabs, epsrel, limit, \\\n\t\t\t\tscratch, &tempres, &temperr);\n\t\t}\n\n\t\telse {\n\t\t\tdouble z0 = 0.0;\n\t\t\tdouble Dc0_z0 = 0.0;\n\n\t\t\tif ( uni->CacheValid ) {\n\t\t\t\tif ( z > zMaxInterp ) {\n\t\t\t\t\tz0 = zMaxInterp;\n\t\t\t\t\tDc0_z0 = uni->Dc0Cache[InterpIntervals - 1].ders[0];\n\t\t\t\t}\n\t\t\t\telse if ( z < zMinInterp ) {\n\t\t\t\t\tz0 = zMinInterp;\n\t\t\t\t\tDc0_z0 = uni->Dc0Cache[0].ders[0];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tDcintegratorStatus = gsl_integration_qag(&integrand, \\\n\t\t\t\t1.0 + z0, 1.0 + z, \\\n\t\t\t\tepsabs, epsrel, limit, GSL_INTEG_GAUSS41, \\\n\t\t\t\tscratch, &tempres, &temperr);\n\n\t\t\ttempres += Dc0_z0;\n\t\t}\n\n\t\tgsl_integration_workspace_free( scratch );\n\n\t\tif (DcintegratorStatus == GSL_EFAILED) {\n\t\t\tfprintf(stderr, \"Dc0_Cosmic: gsl integrator failed.\\n\");\n\t\t\t*abserr = NAN;\n\t\t\treturn NAN;\n\t\t}\n\n\t\tresult = FMA_m(weight, tempres, result);\n\t\t*abserr = FMA_m(weight, temperr, *abserr);\n\t}\n\n\treturn result;\n}\n\n\ndouble Dc_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\treturn Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr) * uni->DH;\n}\n\n\ndouble tL0_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\tdouble result, weight, zpos;\n\n\tif (z < -1.0) {\n\t\tfprintf(stderr, \"tL0_Cosmic: invalid redshift. Redshifts must be >= -1.0\\n\");\n\t\tfprintf(stderr, \"z = %.16e\\n\", z);\n\n\t\treturn NAN;\n\t}\n\telse if (z > uni->zLastTurn || z < uni->zNextTurn) {\n\t\tfprintf(stderr, \"tL0_Cosmic: invalid redshift. Cannot integrate past turning points.\\n\");\n\t\tfprintf(stderr, \"z = %.16e, zNextTurn = %.16e, zLastTurn = %.16e\\n\",\n\t\t\tz, uni->zNextTurn, uni->zLastTurn );\n\n\t\treturn NAN;\n\t}\n\n\tzpos = fabs(z);\n\tresult = 0.0;\n\tweight = 1.0;\n\n\tif (zpos <= TaylorMaxZ) { //Perform the taylor series calculation\n\t\tdouble *coeffs = uni->tL0_TaylorCoeffs;\n\n\t\tif (zpos > TaylorInterpMinZ) {\n\t\t\tweight = (TaylorMaxZ - zpos) * TaylorInterpInterval;\n\t\t}\n\t\telse {\n\t\t\tweight = 1.0;\n\t\t}\n\n\t\tresult = FMA_m(FMA_m(coeffs[4], z, coeffs[3]), z, coeffs[2]);\n\t\tresult = FMA_m(FMA_m(result, z, coeffs[1]), z, coeffs[0]) * z * weight;\n\n\t\tweight = 1.0 - weight;\n\t}\n\n\t*abserr = 0.0;\n\n\tif (fast && uni->CacheValid && z >= zMinInterp && z <= zMaxInterp \\\n\t\t&& zpos > TaylorInterpMinZ) {\n\t\tdouble tempres, zCenter, x;\n\t\tdouble bases[4], *ders;\n\t\tint centeridx;\n\t\tCachePoint *curPt;\n\n\t\t//Use the interpolation cache\n\t\tcenteridx = round((z - zMinInterp) / zInterpCellWidth);\n\t\tif (centeridx < 1) {\n\t\t\tcenteridx = 1;\n\t\t}\n\n\t\telse if (centeridx >= InterpIntervals + 1) {\n\t\t\tcenteridx = InterpIntervals;\n\t\t}\n\n\t\tzCenter = ((double) centeridx) * zInterpCellWidth + zMinInterp;\n\t\tx = (z - zCenter) / zInterpCellWidth;\n\t\ttempres = 0.0;\n\n\t\tcurPt = uni->tL0Cache + centeridx - 1;\n\t\tders = curPt->ders;\n\t\tLtEdgeBases(x, zInterpCellWidth, bases);\n\t\ttempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres));\n\t\ttempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres));\n\n\t\t++curPt;\n\t\tders = curPt->ders;\n\t\tcenterBases(x, zInterpCellWidth, bases);\n\t\ttempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres));\n\t\ttempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres));\n\n\t\t++curPt;\n\t\tders = curPt->ders;\n\t\tRtEdgeBases(x, zInterpCellWidth, bases);\n\t\ttempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres));\n\t\ttempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres));\n\n\t\tresult = FMA_m(weight, tempres, result);\n\t\t*abserr = tempres * pow(x, 12.0);\n\t}\n\n\telse if ( ((zpos > TaylorInterpMinZ && !fast) ||\n\t\tz > zMaxInterp || z < zMinInterp) ) {\n\t\tgsl_integration_workspace *scratch;\n\t\tgsl_function integrand;\n\t\tint tLintegratorStatus;\n\t\tdouble tempres, temperr;\n\n\t\tscratch = gsl_integration_workspace_alloc( limit );\n\n\t\tintegrand.function = &dtL0_dz_gsl;\n\t\tintegrand.params = (void *)uni;\n\n\t\tif (!isinf(z) && \\\n\t\t\t(z >= uni->zLastTurn * 0x1.fffffff8p-1 || \\\n\t\t\t\tz <= uni->zNextTurn * 0x1.fffffff8p-1 || \\\n\t\t\t\tz <= -1.0 * 0x1.fffffff8p-1)) {\n\t\t\ttLintegratorStatus = gsl_integration_qags(&integrand, \\\n\t\t\t\t1.0, 1.0 + z, \\\n\t\t\t\tepsabs, epsrel, limit, \\\n\t\t\t\tscratch, &tempres, &temperr);\n\t\t}\n\n\t\telse if (isinf(z)) {\n\t\t\ttLintegratorStatus = gsl_integration_qagiu(&integrand, \\\n\t\t\t\t1.0, \\\n\t\t\t\tepsabs, epsrel, limit, \\\n\t\t\t\tscratch, &tempres, &temperr);\n\t\t}\n\n\t\telse {\n\t\t\tdouble z0 = 0.0;\n\t\t\tdouble tL0_z0 = 0.0;\n\n\t\t\tif ( uni->CacheValid ) {\n\t\t\t\tif ( z > zMaxInterp ) {\n\t\t\t\t\tz0 = zMaxInterp;\n\t\t\t\t\ttL0_z0 = uni->tL0Cache[InterpIntervals - 1].ders[0];\n\t\t\t\t}\n\t\t\t\telse if ( z < zMinInterp ) {\n\t\t\t\t\tz0 = zMinInterp;\n\t\t\t\t\ttL0_z0 = uni->tL0Cache[0].ders[0];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttLintegratorStatus = gsl_integration_qag(&integrand, \\\n\t\t\t\t1.0 + z0, 1.0 + z, \\\n\t\t\t\tepsabs, epsrel, limit, GSL_INTEG_GAUSS41, \\\n\t\t\t\tscratch, &tempres, &temperr);\n\n\t\t\ttempres += tL0_z0;\n\t\t}\n\n\t\tgsl_integration_workspace_free( scratch );\n\n\t\tif (tLintegratorStatus == GSL_EFAILED) {\n\t\t\tfprintf(stderr, \"tL0_Cosmic: gsl integrator failed.\\n\");\n\t\t\t*abserr = NAN;\n\t\t\treturn NAN;\n\t\t}\n\n\t\tresult = FMA_m(weight, tempres, result);\n\t\t*abserr = FMA_m(weight, temperr, *abserr);\n\t}\n\n\treturn result;\n}\n\n\ndouble tL_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\treturn tL0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr) * uni->tH;\n}\n\n\ndouble DcT_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\tdouble result;\n\n\tresult = (*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr);\n\n\tresult *= uni->DH;\n\t*abserr *= uni->DH;\n\n\treturn result;\n}\n\ndouble DcT0_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\n\treturn (*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr);\n}\n\nstatic inline double DcT0Flat(struct UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\n\treturn Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr);\n}\n\nstatic double DcT0NegK(struct UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\tdouble result, nrm;\n\tdouble OmegaKpos = -uni->OmegaCurvature;\n\n\tresult = Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr);\n\tnrm = sqrt(OmegaKpos);\n\tresult = sin(nrm * result) * nrm / OmegaKpos;\n\n\treturn result;\n}\n\nstatic double DcT0PosK(struct UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\tdouble result, nrm;\n\tdouble OmegaKpos = uni->OmegaCurvature;\n\n\tresult = Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr);\n\tnrm = sqrt(uni->OmegaCurvature);\n\n\tresult = sinh(nrm * result) * nrm / uni->OmegaCurvature;\n\n\treturn result;\n}\n\n\ndouble Da0_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\n\treturn ((*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr) \\\n\t\t/ (1.0 + z));\n}\n\ndouble Da_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\n\treturn ((*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr) \\\n\t\t* uni->DH / (1.0 + z));\n}\n\n\ndouble Dl0_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\n\treturn ((*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr) \\\n\t\t* (1.0 + z));\n}\n\ndouble Dl_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\n\treturn ((*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr) \\\n\t\t* (1.0 + z) * uni->DH);\n}\n\n\ndouble dVc_dzdOmega0_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\tdouble D = (*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr);\n\n\treturn D * D * Einv(uni, 1.0 + z);\n}\n\ndouble dVc_dzdOmega_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\tdouble D = (*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr);\n\n\treturn D * D * Einv(uni, 1.0 + z) * uni->VH;\n}\n\n\n\ndouble Vc_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\n\treturn ((*(uni->F_Vc0))(uni, z, fast, epsabs, epsrel, limit, abserr) \\\n\t\t* uni->VH);\n}\n\ndouble Vc0_Cosmic(UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\n\treturn (*(uni->F_Vc0))(uni, z, fast, epsabs, epsrel, limit, abserr);\n}\n\nstatic double Vc0Flat(struct UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\tdouble DcT = Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr);\n\tdouble result, scale;\n\n\tscale = 4.0*Pi * DcT * DcT;\n\tresult = DcT * scale / 3.0;\n\t*abserr *= scale;\n\n\treturn result;\n}\n\nstatic double Vc0NegK(struct UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\tdouble Dc = Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr);\n\tdouble OmegaKpos = -uni->OmegaCurvature;\n\tdouble x, nrm, result, scale;\n\n\tnrm = sqrt(OmegaKpos);\n\tx = 2.0 * Dc * nrm;\n\n\tif ( fabs(x) < 0x1.cp-2 ) { //Use Taylor expansion where more accurate\n\t\tdouble x2 = x*x;\n\t\tdouble errscale;\n\n\t\t//Taylor expansion for sin(x) - x\n\t\tresult = FMA_m(0x1.6124613a86d09p-33, x2, -0x1.ae64567f544e4p-26);\n\t\tresult = FMA_m(FMA_m(result, x2, 0x1.71de3a556c734p-19), x2, -0x1.a01a01a01a01ap-13);\n\t\tresult = FMA_m(FMA_m(result, x2, 0x1.1111111111111p-7), x2, -0x1.5555555555555p-3);\n\t\tresult *= x2 * x;\n\t}\n\n\telse {\n\t\tresult = sin(x) - x;\n\t}\n\n\t//First scaling of the abserr\n\tscale = sin(0.5 * x);\n\tscale *= 4.0 * Pi * scale / OmegaKpos;\n\t*abserr *= scale;\n\n\t//Final scaling of results\n\tresult *= -Pi * nrm / (OmegaKpos * OmegaKpos);\n\n\treturn result;\n}\n\nstatic double Vc0PosK(struct UniverseLCDM *uni, double z, bool fast,\n\tdouble epsabs, double epsrel, size_t limit, double *abserr) {\n\tdouble Dc = Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr);\n\tdouble OmegaKpos = uni->OmegaCurvature;\n\tdouble x, nrm, result, scale;\n\n\tnrm = sqrt(OmegaKpos);\n\tx = 2.0 * Dc * nrm;\n\n\tif ( fabs(x) < 0.5 ) { //Use Taylor expansion where more accurate\n\t\tdouble x2 = x*x;\n\n\t\t//Taylor expansion for sinh(x) - x\n\t\tresult = FMA_m(0x1.6124613a86d09p-33, x2, 0x1.ae64567f544e4p-26);\n\t\tresult = FMA_m(FMA_m(result, x2, 0x1.71de3a556c734p-19), x2, 0x1.a01a01a01a01ap-13);\n\t\tresult = FMA_m(FMA_m(result, x2, 0x1.1111111111111p-7), x2, 0x1.5555555555555p-3);\n\t\tresult *= x2 * x;\n\t}\n\n\telse {\n\t\tresult = sinh(x) - x;\n\t}\n\n\t//First scaling of the abserr\n\tscale = sinh(0.5 * x);\n\tscale *= 4.0 * Pi * scale / OmegaKpos;\n\t*abserr *= scale;\n\n\t//Final scaling of results\n\tresult *= Pi * nrm / (OmegaKpos * OmegaKpos);\n\n\treturn result;\n}\n\n\ndouble Dc0Inv_Cosmic(UniverseLCDM *uni, double Dc0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble zCur, zLast, f, fp, fppoverfp, foverfp, delta, ainv, dummy;\n\tdouble c3, c2, c1;\n\tdouble epsrelDc0 = 0.0625 * epsrel;\n\tdouble epsabsDc0 = epsrelDc0 * Dc0;\n\tunsigned int iter;\n\tbool converged = false;\n\n\tif (isnan(Dc0) || isnan(epsrel)) {\n\t\treturn NAN;\n\t} else if (Dc0 < uni->Dc0InvD0max) {\n\t\t//do nothing\n\t}\n\telse if (!isnan(uni->Dc0LastTurn) && Dc0 == uni->Dc0LastTurn) {\n\t\treturn uni->zLastTurn;\n\t}\n\telse if (Dc0 == uni->Dc0Max) {\n\t\treturn INFINITY;\n\t}\n\telse {\n\t\tfprintf(stderr, \"Dc0Inv_Cosmic: Dc0 outside the invertable region.\\n\");\n\t\treturn NAN;\n\t}\n\n\t//Approximation for Dc0 = z / (1 + OmegaM * z )\n\tzCur = Dc0 / (1.0 - uni->OmegaMatter * Dc0);\n\tc3 = -2.0 * uni->OmegaRelativistic;\n\tc2 = -1.5 * uni->OmegaMatter;\n\tc1 = -uni->OmegaCurvature;\n\n\t//Iterate using modified Halley's method\n\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\tzLast = zCur;\n\t\tf = (Dc0_Cosmic(uni, zCur, true, epsabsDc0, epsrelDc0, MaxGSLlevel, &dummy) \\\n\t\t\t- Dc0);\n\t\tainv = 1.0 + zCur;\n\t\tfp = Einv(uni, ainv);\n\n\t\tfppoverfp = FMA_m(FMA_m(c3, ainv, c2), ainv, c1) * ainv * fp * fp;\n\t\tfoverfp = f / fp;\n\n\t\tdelta = -foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4);\n\t\tzCur += delta;\n\n\t\t//Prevent the current estimate from becoming invalid\n\t\tif (zCur <= -1.0) {\n\t\t\tif (zCur < -1.0) {\n\t\t\t\tzCur = fabs(zCur + 1.0) - 1.0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tzCur = -0.5;\n\t\t\t}\n\t\t\tdelta = zCur - zLast;\n\t\t}\n\n\t\tif (fabs(delta) <= epsrel * fabs(zCur)) {\n\t\t\tconverged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!converged) {\n\t\tzCur = NAN;\n\t}\n\n\treturn zCur;\n}\n\ndouble DcInv_Cosmic(UniverseLCDM *uni, double Dc,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble Dc0 = Dc / uni->DH;\n\n\treturn Dc0Inv_Cosmic(uni, Dc0, branchNum, epsrel, maxiter);\n}\n\n\ndouble DcT0Inv_Cosmic(UniverseLCDM *uni, double DcT0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\treturn (*(uni->F_DcT0Inv))(uni, DcT0, branchNum, epsrel, maxiter);\n}\n\nstatic double DcT0InvFlat(struct UniverseLCDM *uni, double DcT0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter){\n\treturn Dc0Inv_Cosmic(uni, DcT0, branchNum, epsrel, maxiter);\n}\n\nstatic double DcT0InvNegK(struct UniverseLCDM *uni, double DcT0, unsigned int branchNum,\n\tdouble epsrel, unsigned int maxiter){\n\tdouble x, nrm, Dc0;\n\tdouble OmegaKpos = -uni->OmegaCurvature;\n\n\tnrm = sqrt(OmegaKpos);\n\tx = asin(DcT0 * nrm);\n\n\tif (branchNum == 0) {\n\t\t//common case, do nothing\n\t}\n\n\telse if ((branchNum & 1) == 0) { //branchNum even\n\t\tx += copysign(2.0 * Pi * (double) branchNum, x);\n\t}\n\n\telse { //branchNum odd\n\t\t//Reflect across Pi/2\n\t\tx += 2.0 * copysign( 0.5 * Pi - fabs(x), x);\n\n\t\t//Add the remaining branch shifts\n\t\tx += copysign(2.0 * Pi * (double) (branchNum - 1), x);\n\t}\n\n\tDc0 = x * nrm / OmegaKpos;\n\n\treturn Dc0Inv_Cosmic(uni, Dc0, 0, epsrel, maxiter);\n}\n\nstatic double DcT0InvPosK(struct UniverseLCDM *uni, double DcT0, unsigned int branchNum,\n\tdouble epsrel, unsigned int maxiter){\n\tdouble x, nrm, Dc0;\n\tdouble OmegaKpos = uni->OmegaCurvature;\n\n\tnrm = sqrt(OmegaKpos);\n\tx = asinh(DcT0 * nrm);\n\n\tDc0 = x * nrm / OmegaKpos;\n\n\treturn Dc0Inv_Cosmic(uni, Dc0, 0, epsrel, maxiter);\n}\n\ndouble DcTInv_Cosmic(UniverseLCDM *uni, double DcT,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\n\treturn DcT0Inv_Cosmic(uni, DcT / uni->DH, branchNum, epsrel, maxiter);\n}\n\n\ndouble Da0Inv_Cosmic(UniverseLCDM *uni, double Da0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\n\treturn (*(uni->F_Da0Inv))(uni, Da0, branchNum, epsrel, maxiter);\n}\n\ndouble Da0InvFlat(struct UniverseLCDM *uni, double Da0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble zCur, zLast, f, ainv, a, Einv_, dummy;\n\tdouble fp, fppoverfp, foverfp, delta;\n\tdouble Dc0;\n\tdouble zMin, zMax;\n\tdouble c1, c2, c3;\n\tdouble epsrelDa0 = 0.0625 * epsrel;\n\tdouble epsabsDa0 = Da0 * epsrelDa0;\n\tunsigned int iter;\n\tbool converged = false;\n\n\tif (isnan(Da0) || isnan(epsrel)) {\n\t\treturn NAN;\n\t}\n\telse if (Da0 < uni->Da0Max) {\n\t\tif (branchNum == 0) {\n\t\t\tzMin = -1.0;\n\t\t\tzMax = uni->z_DaMax;\n\t\t}\n\t\telse {\n\t\t\tdouble z = uni->zLastTurn;\n\t\t\tdouble dummy;\n\t\t\tdouble Da0LastTurn = (DcT0Flat(uni, z, true, 1e-6, epsrel, 128, &dummy) \\\n\t\t\t\t/ (1.0 + z));\n\n\t\t\tif (Da0 < Da0LastTurn) {\n\t\t\t\treturn NAN;\n\t\t\t}\n\t\t\telse if (Da0 == Da0LastTurn) {\n\t\t\t\treturn uni->zLastTurn;\n\t\t\t}\n\n\t\t\tzMin = uni->z_DaMax;\n\t\t\tzMax = uni->zLastTurn;\n\t\t}\n\t}\n\telse if (Da0 == uni->Da0Max) {\n\t\treturn uni->z_DaMax;\n\t}\n\telse {\n\t\tfprintf(stderr, \"Da0InvFlat: Da0 outside the invertable region.\\n\");\n\t\tprintf(\"%.16e\\n\", uni->Da0Max);\n\t\treturn NAN;\n\t}\n\n\tif (branchNum == 0) {\n\t\tzCur = 0.5 * (zMin + zMax);\n\t}\n\telse {\n\t\tzCur = 2.0 * zMin;\n\t}\n\tf = Da0;\n\n\tc3 = -2.0 * uni->OmegaRelativistic;\n\tc2 = -1.5 * uni->OmegaMatter;\n\tc1 = -uni->OmegaCurvature;\n\n\t//Because Da often has a maximum, we proceed using Halley's iteration instead of Newtons.\n\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\tzLast = zCur;\n\n\t\tainv = 1.0 + zCur;\n\t\ta = 1.0 / ainv;\n\t\tDc0 = Dc0_Cosmic(uni, zCur, true, epsabsDa0, epsrelDa0, 128, &dummy);\n\t\tEinv_ = Einv(uni, ainv);\n\n\t\tf = FMA_m(Dc0, a, - Da0);\n\t\tfp = FMA_m(-Dc0, a, Einv_) * a;\n\t\tfoverfp = f / fp;\n\n\t\tfppoverfp = FMA_m(FMA_m(c3, ainv, c2), ainv, c1) * ainv / fp;\n\t\tfppoverfp = FMA_m(fppoverfp, Einv_ * Einv_ * Einv_, -2.0) * a;\n\n\t\tdelta = - foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4);\n\t\tzCur += delta;\n\n\t\t//Prevent the current estimate from becoming invalid\n\t\tif (zCur <= zMin){\n\t\t\tif (zCur < zMin) {\n\t\t\t\tzCur = fabs(zCur - zMin) + zMin;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tzCur = zMin + MIN(0.5, 0.125 * (zMax - zMin));\n\t\t\t}\n\t\t\tdelta = zCur - zLast;\n\t\t}\n\n\t\telse if (zCur >= zMax) {\n\t\t\tif (zCur > zMax) {\n\t\t\t\tzCur = zMax - fabs(zMax - zCur);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tzCur = zMax - MIN(0.5, 0.125 * (zMax - zMin));\n\t\t\t}\n\t\t\tdelta = zCur - zLast;\n\t\t}\n\n\t\tif (fabs(delta) <= epsrel * fabs(zCur)) {\n\t\t\tconverged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!converged) {\n\t\tzCur = NAN;\n\t}\n\n\treturn zCur;\n}\n\ndouble Da0InvNegK(struct UniverseLCDM *uni, double Da0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble zCur, zLast, f, ainv, a, Einv_, dummy;\n\tdouble fp, fppoverfp, foverfp, delta;\n\tdouble tanReduced, sinReduced, cosReduced, Dc0;\n\tdouble Wkpos = -uni->OmegaCurvature;\n\tdouble rootWk = sqrt(Wkpos);\n\tdouble zMin, zMax;\n\tdouble c1, c2, c3;\n\tdouble epsrelDa0 = 0.0625 * epsrel;\n\tdouble epsabsDa0 = Da0 * epsrelDa0;\n\tunsigned int iter;\n\tbool converged = false;\n\n\tif (isnan(Da0) || isnan(epsrel)) {\n\t\treturn NAN;\n\t}\n\telse if (Da0 < uni->Da0Max) {\n\t\tif (branchNum == 0) {\n\t\t\tzMin = -1.0;\n\t\t\tzMax = uni->z_DaMax;\n\t\t}\n\t\telse {\n\t\t\tdouble z = uni->zLastTurn;\n\t\t\tdouble dummy;\n\t\t\tdouble Da0LastTurn = (DcT0Flat(uni, z, true, 1e-6, epsrel, 128, &dummy) \\\n\t\t\t\t/ (1.0 + z));\n\n\t\t\tif (Da0 < Da0LastTurn) {\n\t\t\t\treturn NAN;\n\t\t\t}\n\t\t\telse if (Da0 == Da0LastTurn) {\n\t\t\t\treturn uni->zLastTurn;\n\t\t\t}\n\n\t\t\tzMin = uni->z_DaMax;\n\t\t\tzMax = uni->zLastTurn;\n\t\t}\n\t}\n\telse if (Da0 == uni->Da0Max) {\n\t\treturn uni->z_DaMax;\n\t}\n\telse {\n\t\tfprintf(stderr, \"Da0Inv_Cosmic: Da0 outside the invertable region.\\n\");\n\t\treturn NAN;\n\t}\n\n\tif (branchNum == 0) {\n\t\tzCur = 0.5 * (zMin + zMax);\n\t}\n\telse {\n\t\tzCur = 2.0 * zMin;\n\t}\n\n\tc3 = -2.0 * uni->OmegaRelativistic;\n\tc2 = -1.5 * uni->OmegaMatter;\n\tc1 = -uni->OmegaCurvature;\n\n\t//Because Da often has a maximum, we proceed using Halley's iteration instead of Newtons.\n\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\tzLast = zCur;\n\n\t\tainv = 1.0 + zCur;\n\t\ta = 1.0 / ainv;\n\t\tDc0 = Dc0_Cosmic(uni, zCur, true, epsabsDa0, epsrelDa0, 128, &dummy);\n\t\tEinv_ = Einv(uni, ainv);\n\t\tsinReduced = sin(Dc0 * rootWk)/rootWk;\n\t\tcosReduced = cos(Dc0 * rootWk);\n\t\ttanReduced = sinReduced / cosReduced;\n\n\t\tf = FMA_m(sinReduced, a, -Da0);\n\t\tfp = FMA_m(-sinReduced, a, cosReduced * Einv_) * a;\n\t\tfoverfp = f / fp;\n\n\t\tfppoverfp = FMA_m(FMA_m(c3, ainv, c2), ainv, c1) / fp;\n\t\tfppoverfp = FMA_m(fppoverfp, Einv_ * Einv_ * Einv_,\n\t\t\tFMA_m(Einv_ * Einv_, -Wkpos, 2.0 * a) * tanReduced);\n\n\t\tdelta = - foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4);\n\t\tzCur += delta;\n\n\t\t//Prevent the current estimate from becoming invalid\n\t\tif (zCur <= zMin){\n\t\t\tif (zCur < zMin) {\n\t\t\t\tzCur = fabs(zCur - zMin) + zMin;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tzCur = zMin + MIN(0.5, 0.125 * (zMax - zMin));\n\t\t\t}\n\t\t\tdelta = zCur - zLast;\n\t\t}\n\n\t\telse if (zCur >= zMax) {\n\t\t\tif (zCur > zMax) {\n\t\t\t\tzCur = zMax - fabs(zMax - zCur);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tzCur = zMax - MIN(0.5, 0.125 * (zMax - zMin));\n\t\t\t}\n\t\t\tdelta = zCur - zLast;\n\t\t}\n\n\t\tif (fabs(delta) <= epsrel * fabs(zCur)) {\n\t\t\tconverged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!converged) {\n\t\tzCur = NAN;\n\t}\n\n\treturn zCur;\n}\n\ndouble Da0InvPosK(struct UniverseLCDM *uni, double Da0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble zCur, zLast, f, ainv, a, Einv_, dummy;\n\tdouble fp, fppoverfp, foverfp, delta;\n\tdouble tanhReduced, sinhReduced, coshReduced, Dc0;\n\tdouble Wkpos = uni->OmegaCurvature;\n\tdouble rootWk = sqrt(Wkpos);\n\tdouble zMin, zMax;\n\tdouble c1, c2, c3;\n\tdouble epsrelDa0 = 0.0625 * epsrel;\n\tdouble epsabsDa0 = Da0 * epsrelDa0;\n\tunsigned int iter;\n\tbool converged = false;\n\n\tif (isnan(Da0) || isnan(epsrel)) {\n\t\treturn NAN;\n\t}\n\telse if (Da0 < uni->Da0Max) {\n\t\tif (branchNum == 0) {\n\t\t\tzMin = -1.0;\n\t\t\tzMax = uni->z_DaMax;\n\t\t}\n\t\telse {\n\t\t\tdouble z = uni->zLastTurn;\n\t\t\tdouble dummy;\n\t\t\tdouble Da0LastTurn = (DcT0Flat(uni, z, true, 1e-6, epsrel, 128, &dummy) \\\n\t\t\t\t/ (1.0 + z));\n\n\t\t\tif (Da0 < Da0LastTurn) {\n\t\t\t\treturn NAN;\n\t\t\t}\n\t\t\telse if (Da0 == Da0LastTurn) {\n\t\t\t\treturn uni->zLastTurn;\n\t\t\t}\n\n\t\t\tzMin = uni->z_DaMax;\n\t\t\tzMax = uni->zLastTurn;\n\t\t}\n\t}\n\telse if (Da0 == uni->Da0Max) {\n\t\treturn uni->z_DaMax;\n\t}\n\telse {\n\t\tfprintf(stderr, \"Da0Inv_Cosmic: Da0 outside the invertable region.\\n\");\n\t\treturn NAN;\n\t}\n\n\tif (branchNum == 0) {\n\t\tzCur = 0.5 * (zMin + zMax);\n\t}\n\telse {\n\t\tzCur = 2.0 * zMin;\n\t}\n\n\tc3 = -2.0 * uni->OmegaRelativistic;\n\tc2 = -1.5 * uni->OmegaMatter;\n\tc1 = -uni->OmegaCurvature;\n\n\t//Because Da often has a maximum, we proceed using Halley's iteration instead of Newtons.\n\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\tzLast = zCur;\n\n\t\tainv = 1.0 + zCur;\n\t\ta = 1.0 / ainv;\n\t\tDc0 = Dc0_Cosmic(uni, zCur, true, epsabsDa0, epsrelDa0, 128, &dummy);\n\t\tEinv_ = Einv(uni, ainv);\n\t\tsinhReduced = sinh(Dc0 * rootWk)/rootWk;\n\t\tcoshReduced = cosh(Dc0 * rootWk);\n\t\ttanhReduced = tanh(Dc0 * rootWk)/rootWk;\n\n\t\tf = FMA_m(sinhReduced, a, -Da0);\n\t\tfp = FMA_m(-sinhReduced, a, coshReduced * Einv_) * a;\n\t\tfoverfp = f / fp;\n\n\t\tfppoverfp = FMA_m(FMA_m(c3, ainv, c2), ainv, c1) / fp;\n\t\tfppoverfp = FMA_m(fppoverfp, Einv_ * Einv_ * Einv_,\n\t\t\tFMA_m(Einv_ * Einv_, Wkpos, 2.0 * a) * tanhReduced);\n\n\t\tdelta = - foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4);\n\t\tzCur += delta;\n\n\t\t//Prevent the current estimate from becoming invalid\n\t\tif (zCur <= zMin){\n\t\t\tif (zCur < zMin) {\n\t\t\t\tzCur = fabs(zCur - zMin) + zMin;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tzCur = zMin + MIN(0.5, 0.125 * (zMax - zMin));\n\t\t\t}\n\t\t\tdelta = zCur - zLast;\n\t\t}\n\n\t\telse if (zCur >= zMax) {\n\t\t\tif (zCur > zMax) {\n\t\t\t\tzCur = zMax - fabs(zMax - zCur);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tzCur = zMax - MIN(0.5, 0.125 * (zMax - zMin));\n\t\t\t}\n\t\t\tdelta = zCur - zLast;\n\t\t}\n\n\t\tif (fabs(delta) <= epsrel * fabs(zCur)) {\n\t\t\tconverged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!converged) {\n\t\tzCur = NAN;\n\t}\n\n\treturn zCur;\n}\n\ndouble DaInv_Cosmic(UniverseLCDM *uni, double Da, unsigned int branchNum,\n\tdouble epsrel, unsigned int maxiter) {\n\treturn Da0Inv_Cosmic(uni, Da / uni->DH, branchNum, epsrel, maxiter);\n}\n\n\ndouble Dl0Inv_Cosmic(UniverseLCDM *uni, double Dl0, unsigned int branchNum,\n\tdouble epsrel, unsigned int maxiter) {\n\treturn (*(uni->F_Dl0Inv))(uni, Dl0, branchNum, epsrel, maxiter);\n}\n\ndouble Dl0InvFlat(struct UniverseLCDM *uni, double Dl0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble zCur, zLast, branchsign, f, ainv, Einv_, dummy;\n\tdouble fp, fppoverfp, foverfp, delta;\n\tdouble Dc0;\n\tdouble zMin, zMax;\n\tdouble c1, c2, c3;\n\tdouble epsrelDl0 = 0.0625 * epsrel;\n\tdouble epsabsDl0 = Dl0 * epsrelDl0;\n\tunsigned int iter;\n\tbool converged = false;\n\n\tif (isnan(Dl0) || isnan(epsrel)) {\n\t\treturn NAN;\n\t}\n\telse if (isinf(Dl0)) {\n\t\treturn INFINITY;\n\t}\n\telse if ((!isnan(uni->Dc0LastTurn) && \\\n\t\tDl0 < uni->Dc0LastTurn * (1.0 + uni->zLastTurn)) || \\\n\t\tisnan(uni->Dc0LastTurn)) {\n\t\t//do nothing\n\t}\n\telse {\n\t\tfprintf(stderr, \"Dl0InvFlat: Unhandled case.\\n\");\n\t\treturn NAN;\n\t}\n\n\t//Approximation for Dc0 = z * (1+z) / ( 1 + OmegaM * z )\n\tzCur = 0.5 * (1.0 - Dc0 * uni->OmegaMatter);\n\tzCur = sqrt(FMA_m(zCur, zCur, Dc0)) - zCur;\n\tc3 = -2.0 * uni->OmegaRelativistic;\n\tc2 = -1.5 * uni->OmegaMatter;\n\tc1 = -uni->OmegaCurvature;\n\n\t//Iterate using modified Halley's method\n\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\tzLast = zCur;\n\n\t\tainv = 1.0 + zCur;\n\t\tDc0 = Dc0_Cosmic(uni, zCur, true, epsabsDl0, epsrelDl0, 128, &dummy);\n\t\tEinv_ = Einv(uni, ainv);\n\n\t\tf = FMA_m(Dc0, ainv, -Dl0);\n\t\tfp = FMA_m(Einv_, ainv, Dc0);\n\t\tfoverfp = f / fp;\n\n\t\tfppoverfp = FMA_m(FMA_m(FMA_m(c3, ainv, c2), ainv, c1),\n\t\t\tainv * ainv * Einv_ * Einv_, 2.0) * Einv_;\n\t\tfppoverfp /= fp;\n\n\t\tdelta = -foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4);\n\t\tzCur += delta;\n\n\t\t//Prevent the current estimate from becoming invalid\n\t\tif (zCur <= -1.0) {\n\t\t\tif (zCur < -1.0) {\n\t\t\t\tzCur = fabs(zCur + 1.0) - 1.0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tzCur = -0.5;\n\t\t\t}\n\t\t\tdelta = zCur - zLast;\n\t\t}\n\n\t\tif (fabs(delta) < epsrel * fabs(zCur)) {\n\t\t\tconverged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!converged) {\n\t\tzCur = NAN;\n\t}\n\n\treturn zCur;\n}\n\ndouble Dl0InvNegK(struct UniverseLCDM *uni, double Dl0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble zCur, zLast, branchsign, f, ainv, Einv_, dummy;\n\tdouble fp, fppoverfp, foverfp, delta;\n\tdouble tanReduced, sinReduced, cosReduced, Dc0;\n\tdouble Wkpos = -uni->OmegaCurvature;\n\tdouble rootWk = sqrt(Wkpos);\n\tdouble zMin, zMax;\n\tdouble c1, c2, c3;\n\tdouble epsrelDl0 = 0.0625 * epsrel;\n\tdouble epsabsDl0 = Dl0 * epsrelDl0;\n\tunsigned int iter;\n\tbool converged = false;\n\n\tif (isnan(Dl0) || isnan(epsrel)) {\n\t\treturn NAN;\n\t}\n\telse if (isinf(Dl0)) {\n\t\treturn INFINITY;\n\t}\n\telse if ((!isnan(uni->Dc0LastTurn) && \\\n\t\tDl0 < uni->Dc0LastTurn * (1.0 + uni->zLastTurn)) || \\\n\t\tisnan(uni->Dc0LastTurn)) {\n\t\t//do nothing\n\t}\n\telse {\n\t\tfprintf(stderr, \"Dl0InvNegK: Unhandled case.\\n\");\n\t\treturn NAN;\n\t}\n\n\t//Approximation for Dc0 = z * (1+z) / ( 1 + OmegaM * z )\n\tzCur = 0.5 * (1.0 - Dc0 * uni->OmegaMatter);\n\tzCur = sqrt(FMA_m(zCur, zCur, Dc0)) - zCur;\n\tc3 = -2.0 * uni->OmegaRelativistic;\n\tc2 = -1.5 * uni->OmegaMatter;\n\tc1 = -uni->OmegaCurvature;\n\n\t//Iterate using modified Halley's method\n\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\tzLast = zCur;\n\n\t\tainv = 1.0 + zCur;\n\t\tDc0 = Dc0_Cosmic(uni, zCur, true, epsabsDl0, epsrelDl0, 128, &dummy);\n\t\tEinv_ = Einv(uni, ainv);\n\t\tsinReduced = sin(Dc0 * rootWk)/rootWk;\n\t\tcosReduced = cos(Dc0 * rootWk);\n\t\ttanReduced = tan(Dc0 * rootWk)/rootWk;\n\n\t\tf = FMA_m(sinReduced, ainv, -Dl0);\n\t\tfp = FMA_m(Einv_ * cosReduced, ainv, sinReduced);\n\t\tfoverfp = f / fp;\n\n\t\tfppoverfp = (FMA_m(FMA_m(c3, ainv, c2), ainv, c1) * \\\n\t\t\tainv * Einv_ * Einv_);\n\t\tfppoverfp /= FMA_m(Einv_, ainv, tanReduced);\n\t\tfppoverfp += FMA_m(tanReduced, ainv * Einv_ / -Wkpos, 2.0);\n\t\tfppoverfp *= Einv_;\n\n\t\tdelta = -foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4);\n\t\tzCur += delta;\n\n\t\t//Prevent the current estimate from becoming invalid\n\t\tif (zCur <= -1.0) {\n\t\t\tif (zCur < -1.0) {\n\t\t\t\tzCur = fabs(zCur + 1.0) - 1.0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tzCur = -0.5;\n\t\t\t}\n\t\t\tdelta = zCur - zLast;\n\t\t}\n\n\t\tif (fabs(delta) < epsrel * fabs(zCur)) {\n\t\t\tconverged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!converged) {\n\t\tzCur = NAN;\n\t}\n\n\treturn zCur;\n}\n\ndouble Dl0InvPosK(struct UniverseLCDM *uni, double Dl0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble zCur, zLast, branchsign, f, ainv, Einv_, dummy;\n\tdouble fp, fppoverfp, foverfp, delta;\n\tdouble tanhReduced, sinhReduced, coshReduced, Dc0;\n\tdouble Wkpos = uni->OmegaCurvature;\n\tdouble rootWk = sqrt(Wkpos);\n\tdouble zMin, zMax;\n\tdouble c1, c2, c3;\n\tdouble epsrelDl0 = 0.0625 * epsrel;\n\tdouble epsabsDl0 = Dl0 * epsrelDl0;\n\tunsigned int iter;\n\tbool converged = false;\n\n\tif (isnan(Dl0) || isnan(epsrel)) {\n\t\treturn NAN;\n\t}\n\telse if (isinf(Dl0)) {\n\t\treturn INFINITY;\n\t}\n\telse if ((!isnan(uni->Dc0LastTurn) && \\\n\t\tDl0 < uni->Dc0LastTurn * (1.0 + uni->zLastTurn)) || \\\n\t\tisnan(uni->Dc0LastTurn)) {\n\t\t//do nothing\n\t}\n\telse {\n\t\tfprintf(stderr, \"Dl0InvPosK: Unhandled case.\\n\");\n\t\treturn NAN;\n\t}\n\n\t//Approximation for Dc0 = z * (1+z) / ( 1 + OmegaM * z )\n\tzCur = 0.5 * (1.0 - Dc0 * uni->OmegaMatter);\n\tzCur = sqrt(FMA_m(zCur, zCur, Dc0)) - zCur;\n\tc3 = -2.0 * uni->OmegaRelativistic;\n\tc2 = -1.5 * uni->OmegaMatter;\n\tc1 = -uni->OmegaCurvature;\n\n\t//Iterate using modified Halley's method\n\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\tzLast = zCur;\n\n\t\tainv = 1.0 + zCur;\n\t\tDc0 = Dc0_Cosmic(uni, zCur, true, epsabsDl0, epsrelDl0, 128, &dummy);\n\t\tEinv_ = Einv(uni, ainv);\n\t\tsinhReduced = sinh(Dc0 * rootWk)/rootWk;\n\t\tcoshReduced = cosh(Dc0 * rootWk);\n\t\ttanhReduced = tanh(Dc0 * rootWk)/rootWk;\n\n\t\tf = FMA_m(sinhReduced, ainv, -Dl0);\n\t\tfp = FMA_m(Einv_ * coshReduced, ainv, sinhReduced);\n\t\tfoverfp = f / fp;\n\n\t\tfppoverfp = (FMA_m(FMA_m(c3, ainv, c2), ainv, c1) * \\\n\t\t\tainv * Einv_ * Einv_);\n\t\tfppoverfp /= FMA_m(Einv_, ainv, tanhReduced);\n\t\tfppoverfp += FMA_m(tanhReduced, ainv * Einv_ / Wkpos, 2.0);\n\t\tfppoverfp *= Einv_;\n\n\t\tdelta = -foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4);\n\t\tzCur += delta;\n\n\t\t//Prevent the current estimate from becoming invalid\n\t\tif (zCur <= -1.0) {\n\t\t\tif (zCur < -1.0) {\n\t\t\t\tzCur = fabs(zCur + 1.0) - 1.0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tzCur = -0.5;\n\t\t\t}\n\t\t\tdelta = zCur - zLast;\n\t\t}\n\n\t\tif (fabs(delta) < epsrel * fabs(zCur)) {\n\t\t\tconverged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!converged) {\n\t\tzCur = NAN;\n\t}\n\n\treturn zCur;\n}\n\ndouble DlInv_Cosmic(UniverseLCDM *uni, double Dl, unsigned int branchNum,\n\tdouble epsrel, unsigned int maxiter) {\n\treturn Dl0Inv_Cosmic(uni, Dl / uni->DH, branchNum, epsrel, maxiter);\n}\n\n\ndouble Vc0Inv_Cosmic(UniverseLCDM *uni, double Vc0, unsigned int branchNum,\n\tdouble epsrel, unsigned int maxiter) {\n\n\treturn (*(uni->F_Vc0Inv))(uni, Vc0, branchNum, epsrel, maxiter);\n}\n\ndouble VcInv_Cosmic(UniverseLCDM *uni, double Vc,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble Vc0 = Vc / uni->VH;\n\n\treturn Vc0Inv_Cosmic(uni, Vc0, branchNum, epsrel, maxiter);\n}\n\nstatic double Vc0InvFlat(struct UniverseLCDM *uni, double Vc0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\n\treturn Dc0Inv_Cosmic(uni, pow(Vc0 * 3.0 / (4.0 * Pi), 1.0/3.0),\n\t\tbranchNum, epsrel, maxiter);\n}\n\nstatic double Vc0InvNegK(struct UniverseLCDM *uni, double Vc0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble OmegaKpos = -uni->OmegaCurvature;\n\tdouble nrm = sqrt(OmegaKpos);\n\tdouble x, f, fp, delta;\n\tunsigned int iter;\n\tbool converged = false;\n\tdouble xCur, xLast, y, sx;\n\tdouble y0, dy;\n\tdouble epsrelx = epsrel * 0.25;\n\n\ty = -OmegaKpos * nrm * Vc0 / Pi; //This is sin(x) - x\n\ty0 = -2.0 * Pi * round(y / (2*Pi));\n\tdy = y - y0;\n\n\txCur = -y0 - copysign(pow(6.0 * fabs(dy), 1.0/3.0), dy) ;\n\n\t//Iterate using Newton's method\n\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\txLast = xCur;\n\t\tsx = sin(xCur);\n\t\tf = sx - xCur - y;\n\t\tfp = sin(0.5*xCur);\n\t\tfp *= -2.0 * fp;\n\n\t\tdelta = -f/fp;\n\n\t\txCur += delta;\n\n\t\tif (fabs(delta) <= epsrelx * fabs(xCur)) {\n\t\t\tconverged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (converged) {\n\t\treturn Dc0Inv_Cosmic(uni, xCur * 0.5 * nrm / OmegaKpos, branchNum, epsrel, maxiter);\n\t}\n\treturn NAN;\n}\n\nstatic double Vc0InvPosK(struct UniverseLCDM *uni, double Vc0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble OmegaKpos = uni->OmegaCurvature;\n\tdouble nrm = sqrt(OmegaKpos);\n\tdouble x, f, fp, delta;\n\tunsigned int iter;\n\tbool converged = false;\n\tdouble xCur, xLast, y, ypos, sx;\n\tdouble epsrelx = epsrel * 0.25;\n\n\ty = OmegaKpos * nrm * Vc0 / Pi; //This is sinh(x) - x\n\typos = fabs(y);\n\n\tif (ypos < 4.5) {\n\t\txCur = copysign(pow(6.0 * ypos, 1.0/3.0), y);\n\t} else {\n\t\txCur = copysign(y, log(0.5*ypos));\n\t}\n\n\t//Iterate using Newton's method\n\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\txLast = xCur;\n\t\tsx = sinh(xCur);\n\t\tf = sx - xCur - y;\n\t\tfp = sinh(0.5*xCur);\n\t\tfp *= 2.0 * fp;\n\n\t\tdelta = -f/fp;\n\t\txCur += delta;\n\n\t\tif (fabs(delta) <= epsrelx * fabs(xCur)) {\n\t\t\tconverged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (converged) {\n\t\treturn Dc0Inv_Cosmic(uni, xCur * 0.5 * nrm / OmegaKpos, branchNum, epsrel, maxiter);\n\t}\n\treturn NAN;\n}\n\n\ndouble tL0Inv_Cosmic(UniverseLCDM *uni, double tL0,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble zCur, zLast, f, fp, dummy;\n\tdouble ainv, foverfp, fppoverfp, delta, c4, c3, c2, c0;\n\tdouble epsreltL0 = 0.0625 * epsrel;\n\tdouble epsabstL0 = tL0 * epsreltL0;\n\tunsigned int iter;\n\tbool converged = false;\n\n\tif (isnan(tL0) || isnan(epsrel)) {\n\t\treturn NAN;\n\t}\n\telse if (tL0 < uni->age0) {\n\t\t//do nothing\n\t}\n\telse if (!isnan(uni->tL0LastTurn) && tL0 == uni->tL0LastTurn) {\n\t\treturn uni->zLastTurn;\n\t}\n\telse if (tL0 == uni->age0) {\n\t\treturn INFINITY;\n\t}\n\telse if (isnan(tL0) || isnan(epsrel)) {\n\t\treturn NAN;\n\t}\n\telse {\n\t\tfprintf(stderr, \"tL0Inv_Cosmic: tL0 outside the invertable region.\\n\");\n\t\treturn NAN;\n\t}\n\n\tc4 = -3.0 * uni->OmegaRelativistic;\n\tc3 = -2.5 * uni->OmegaMatter;\n\tc2 = -2.0 * uni->OmegaCurvature;\n\tc0 = -uni->OmegaLambda;\n\n\t//Approximation for tL= tAge * ( 1 - 1/pow(1+z, 1.5) )\n\tzCur = pow(1.0 - tL0 / uni->age0, -2.0/3.0);\n\n\t//Iterate using Halley's method\n\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\tzLast = zCur;\n\t\tf = (tL0_Cosmic(uni, zCur, true, epsabstL0, epsreltL0, MaxGSLlevel, &dummy)\n\t\t\t- tL0);\n\t\tainv = 1.0 + zCur;\n\t\tfp = Einv(uni, ainv) / ainv;\n\n\t\tfppoverfp = FMA_m(FMA_m(FMA_m(c4, ainv, c3), ainv, c2), ainv * ainv, c0) * ainv;\n\t\tfppoverfp *= fp * fp;\n\t\tfoverfp = f / fp;\n\t\tdelta = -foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-1);\n\n\t\tzCur += delta;\n\n\t\t//Prevent the current estimate from becoming invalid\n\t\tif (zCur <= -1.0){\n\t\t\tif (zCur < -1.0) {\n\t\t\t\tzCur = fabs(zCur + 1.0) - 1.0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tzCur = -0.5;\n\t\t\t}\n\t\t\tdelta = zCur - zLast;\n\t\t}\n\n\t\tif (fabs(delta) <= epsrel * fabs(zCur)) {\n\t\t\tconverged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!converged) {\n\t\tzCur = NAN;\n\t}\n\n\treturn zCur;\n}\n\ndouble tLInv_Cosmic(UniverseLCDM *uni, double tL,\n\tunsigned int branchNum, double epsrel, unsigned int maxiter) {\n\tdouble tL0 = tL / uni->tH;\n\n\treturn tL0Inv_Cosmic(uni, tL0, branchNum, epsrel, maxiter);\n}\n\n\n//Function to find the redshift at which Da has a maximum\nstatic double FindDa0Max(UniverseLCDM *uni, double epsrel, unsigned int maxiter) {\n\tdouble Einv_, ainv, a, zCur, zLast, dummy;\n\tdouble epsrelDa0 = 0.0625 * epsrel;\n\tunsigned int iter;\n\tbool converged = false;\n\n\tif (uni->flat || fabs(uni->OmegaCurvature) <= NumericallyFlat) {\n\t\t//Iterate using Newton's method\n\t\tdouble f, fp, delta, Dc0, dummy;\n\t\tdouble c3, c2, c1;\n\n\t\tzCur = 0.0;\n\t\tf = (DcT0Flat(uni, 1.0, true, epsrelDa0, epsrel, 128, &dummy) \\\n\t\t\t\t/ ainv);\n\n\t\tc3 = -2.0 * uni->OmegaRelativistic;\n\t\tc2 = -1.5 * uni->OmegaMatter;\n\t\tc1 = -uni->OmegaCurvature;\n\t\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\t\tzLast = zCur;\n\n\t\t\tainv = 1.0 + zCur;\n\t\t\ta = 1.0 / ainv;\n\t\t\tDc0 = DcT0Flat(uni, zCur, \\\n\t\t\t\ttrue, f * epsrelDa0, epsrel, 128, &dummy);\n\t\t\tEinv_ = Einv(uni, ainv);\n\t\t\tf = FMA_m(-Dc0, a, Einv_);\n\t\t\tfp = FMA_m(FMA_m(c3, ainv, c2), ainv, c1);\n\t\t\tfp = FMA_m(fp, ainv * Einv_ * Einv_ * Einv_, \\\n\t\t\t\tFMA_m(Dc0, a, -Einv_) * a * 2.0);\n\n\t\t\tdelta = -f / fp;\n\t\t\tzCur += delta;\n\n\t\t\t//Prevent the current estimate from becoming invalid\n\t\t\tif (zCur <= -1.0){\n\t\t\t\tif (zCur < -1.0) {\n\t\t\t\t\tzCur = fabs(zCur + 1.0) - 1.0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tzCur = -0.5;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (fabs(delta) <= epsrel * fabs(zCur) || isinf(zCur)) {\n\t\t\t\tconverged = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\telse if (uni->OmegaCurvature < 0.0) {\n\t\t//Iterate using Newton's method\n\t\tdouble f, fp, delta, Dc0, dummy;\n\t\tdouble c3, c2, c1;\n\t\tdouble tanReduced, Einv_, ainv, a;\n\t\tdouble Wkpos = -uni->OmegaCurvature;\n\t\tdouble rootWk = sqrt(Wkpos);\n\n\t\tzCur = 0.0;\n\t\tDc0 = (Dc0_Cosmic(uni, 1.0, true, epsrelDa0, epsrel, 128, &dummy) \\\n\t\t\t\t/ ainv);\n\n\t\tc3 = -2.0 * uni->OmegaRelativistic;\n\t\tc2 = -1.5 * uni->OmegaMatter;\n\t\tc1 = -uni->OmegaCurvature;\n\t\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\t\tzLast = zCur;\n\n\t\t\tainv = 1.0 + zCur;\n\t\t\ta = 1.0 / ainv;\n\t\t\tDc0 = Dc0_Cosmic(uni, zCur, true,\n\t\t\t\tepsrelDa0 * Dc0, epsrelDa0, 128, &dummy);\n\t\t\ttanReduced = tan(Dc0 * rootWk) / rootWk;\n\t\t\tEinv_ = Einv(uni, ainv);\n\n\t\t\tf = FMA_m(-tanReduced, a, Einv_);\n\t\t\tfp = FMA_m(2.0*tanReduced, a, -2.0 * Einv_);\n\t\t\tfp = FMA_m(fp, a, Einv_*Einv_ * \\\n\t\t\t\tFMA_m(FMA_m(FMA_m(c3, ainv, c2), ainv, c1), \\\n\t\t\t\t\tainv * Einv_, Wkpos * tanReduced));\n\n\t\t\tdelta = -f / fp;\n\t\t\tzCur += delta;\n\n\t\t\t//Prevent the current estimate from becoming invalid\n\t\t\tif (zCur <= -1.0){\n\t\t\t\tif (zCur < -1.0) {\n\t\t\t\t\tzCur = fabs(zCur + 1.0) - 1.0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tzCur = -0.5;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (fabs(delta) <= epsrel * fabs(zCur) || isinf(zCur)) {\n\t\t\t\tconverged = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\telse { //uni->OmegaCurvature > 0.0\n\t\t//Iterate using Newton's method\n\t\tdouble f, fp, delta, Dc0, dummy;\n\t\tdouble c3, c2, c1;\n\t\tdouble tanhReduced, Einv_, ainv, a;\n\t\tdouble Wkpos = uni->OmegaCurvature;\n\t\tdouble rootWk = sqrt(Wkpos);\n\n\t\tzCur = 0.0;\n\t\tDc0 = (Dc0_Cosmic(uni, 1.0, true, epsrelDa0, epsrel, 128, &dummy) \\\n\t\t\t\t/ ainv);\n\n\t\tc3 = -2.0 * uni->OmegaRelativistic;\n\t\tc2 = -1.5 * uni->OmegaMatter;\n\t\tc1 = -uni->OmegaCurvature;\n\t\tfor (iter = 0; iter < maxiter; ++iter) {\n\t\t\tzLast = zCur;\n\n\t\t\tainv = 1.0 + zCur;\n\t\t\ta = 1.0 / ainv;\n\t\t\tDc0 = Dc0_Cosmic(uni, zCur, true,\n\t\t\t\tepsrelDa0 * Dc0, epsrelDa0, 128, &dummy);\n\t\t\ttanhReduced = tanh(Dc0 * rootWk) / rootWk;\n\t\t\tEinv_ = Einv(uni, ainv);\n\n\t\t\tf = FMA_m(-tanhReduced, a, Einv_);\n\t\t\tfp = FMA_m(2.0*tanhReduced, a, -2.0 * Einv_);\n\t\t\tfp = FMA_m(fp, a, Einv_*Einv_ * \\\n\t\t\t\tFMA_m(FMA_m(FMA_m(c3, ainv, c2), ainv, c1), \\\n\t\t\t\t\tainv * Einv_, Wkpos * tanhReduced));\n\n\t\t\tdelta = -f / fp;\n\t\t\tzCur += delta;\n\n\t\t\t//Prevent the current estimate from becoming invalid\n\t\t\tif (zCur <= -1.0){\n\t\t\t\tif (zCur < -1.0) {\n\t\t\t\t\tzCur = fabs(zCur + 1.0) - 1.0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tzCur = -0.5;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (fabs(delta) <= epsrel * fabs(zCur) || isinf(zCur)) {\n\t\t\t\tconverged = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!converged) {\n\t\tzCur = NAN;\n\t}\n\n\treturn zCur;\n}", "meta": {"hexsha": "4e41f6463e6f3767561b97439557d94485f4f3e9", "size": 68967, "ext": "c", "lang": "C", "max_stars_repo_path": "CosmoCalcs/CosmoCalcs.c", "max_stars_repo_name": "odysseus9672/SELPythonLibs", "max_stars_repo_head_hexsha": "95f4f1b4d87e54e3e469598b70d09c70c657d59e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-15T18:06:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T11:44:08.000Z", "max_issues_repo_path": "CosmoCalcs/CosmoCalcs.c", "max_issues_repo_name": "odysseus9672/SELPythonLibs", "max_issues_repo_head_hexsha": "95f4f1b4d87e54e3e469598b70d09c70c657d59e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-22T05:27:08.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-25T04:44:56.000Z", "max_forks_repo_path": "CosmoCalcs/CosmoCalcs.c", "max_forks_repo_name": "odysseus9672/SELPythonLibs", "max_forks_repo_head_hexsha": "95f4f1b4d87e54e3e469598b70d09c70c657d59e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-08-22T05:19:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-27T09:04:25.000Z", "avg_line_length": 26.9718420023, "max_line_length": 102, "alphanum_fraction": 0.6330563893, "num_tokens": 26903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4249827149506779}} {"text": "/*\n * Copyright (C) 2018-2020\n * HERE Europe B.V.\n * Utrecht University (The Netherlands).\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n * License-Filename: LICENSE\n */\n\n//\n// Created by Wouter Jongeling (wouter.jongeling@gmail.com)\n// Modified by Mitra, Aniket on 2019-06-18.\n//\n\n/*!\n * @file BrownianBridge.h\n * @brief\n * @authors Aniket Mitra (aniket.mitra@here.com)\n * Wouter Jongeling (wouter.jongeling@gmail.com)\n */\n\n\n#ifndef MOVETK_BROWNIANBRIDGE__H\n#define MOVETK_BROWNIANBRIDGE__H\n\n#include \n#include \n#include \"movetk/utils/Requirements.h\"\n#include \"movetk/utils/Iterators.h\"\n#include \"movetk/geom/trajectory_to_interface.h\"\n#include \"movetk/utils/Iterators.h\"\n#include \n#include \n#include \"gsl/gsl_min.h\"\n\n/*!\n * @file AlgorithmTraits.h\n * @brief The Brownian Bridge Movement Model (BBMM)\n * @authors Aniket Mitra (aniket.mitra@here.com)\n */\n\n/*!\n * @brief a collection of algorithms in movetk\n */\nnamespace movetk_algorithms {\n\n // based on\n // https://www.semanticscholar.org/paper/Computational-Movement-Analysis-Using-Brownian-Sijben/c6104979e609e12e1514b8b605a7d14fa6b5d81a\n\n /*!\n * @brief a collection of classes for BBMM\n */\n namespace brownian_bridge {\n\n /*!\n * @struct ParameterTraits\n * @brief This traits class serves as a collection of types\n * for parameterization of BBMM\n * @tparam _GeometryTraits - This class is a collection of movetk\n * geometry types. For example @refitem movetk_core::MovetkGeometryKernel\n * @tparam TrajectoryIterator - An iterator type.\n * For example @refitem TabularTrajectory::TrajectoryIterator\n */\n template\n struct ParameterTraits {\n typedef _GeometryTraits GeometryTraits;\n /*!*\n * @typedef ::NT\n * @brief typedef of the number type defined in GeometryTraits.\n * For example @refitem movetk_core::MovetkGeometryKernel::NT\n * */\n typedef typename GeometryTraits::NT NT;\n /*!*\n * @typedef ::Point\n * @brief typedef of the point type defined in GeometryTraits.\n * For example @refitem movetk_core::MovetkGeometryKernel::MovetkPoint\n * */\n typedef typename GeometryTraits::MovetkPoint Point;\n /*!* @typedef ::Vector\n * @brief typedef of the vector type defined in GeometryTraits.\n * For example @refitem movetk_core::MovetkGeometryKernel::MovetkVector\n * */\n typedef typename GeometryTraits::MovetkVector Vector;\n /*!* @typedef ::Parameters\n */\n typedef std::tuple Parameters;\n /*!\n * @enum ParameterColumns\n *\n */\n enum ParameterColumns {\n POINT, /*!< global enum value 1 */\n MU, /*!< global enum value 1 */\n SIGMA_SQUARED, /*!< global enum value 1 */\n BEGIN, /*!< global enum value 1 */\n END /*!< global enum value 1 */\n };\n\n };\n\n\n\n\n /*!\n * @class template MLE\n * @brief The Maximum Likelihood Estimator\n * @tparam GeometryTraits - This class is a collection of movetk\n * geometry types. For example @refitem movetk_core::MovetkGeometryKernel\n * @tparam ParameterTraits - This traits class serves as a collection of types\n * for parameterization of BBMM\n * @tparam Norm - The type that models Euclidean distance\n * For example @refitem movetk_support::FiniteNorm\n * @tparam InputIterator - A random access iterator type over a collection of\n * tuples where each tuple is a model of type ParameterTraits::Parameters\n * @tparam MaxIter - A positive integer that bounds the number of iterations in the MLE\n * algorithm\n */\n template,\n typename = movetk_core::requires_tuple<\n typename InputIterator::value_type>,\n typename = movetk_core::requires_tuple_element_as_movetk_point,\n typename = movetk_core::requires_tuple_element_as_movetk_point,\n typename = movetk_core::requires_tuple_element_as_NT>\n class MLE {\n private:\n typedef typename GeometryTraits::NT NT;\n const gsl_min_fminimizer_type *T = gsl_min_fminimizer_goldensection;\n gsl_min_fminimizer *s = gsl_min_fminimizer_alloc(T);\n gsl_function F;\n NT estimated_parameter;\n std::size_t iter = 0, status;\n\n struct fn_params {\n InputIterator first;\n InputIterator beyond;\n };\n\n static double fn(double sigma_squared, void *p) {\n Norm norm;\n struct fn_params *params = (fn_params *) p;\n InputIterator it = params->first;\n NT log_likelihood = 0;\n while (it != params->beyond) {\n typename GeometryTraits::MovetkVector v = std::get(*it)\n - std::get(*it);\n NT operand1 = -LOG_TWO_PI - log(static_cast(sigma_squared));\n NT operand2 = -norm(v) / (2 * sigma_squared);\n log_likelihood += operand1 + operand2;\n it++;\n }\n return -1 * log_likelihood;\n }\n\n void operator()(InputIterator first, InputIterator beyond,\n NT result, NT x_lower, NT x_upper, NT eps) {\n struct fn_params params;\n params.first = first;\n params.beyond = beyond;\n F.function = &MLE::fn;\n F.params = ¶ms;\n status = gsl_min_fminimizer_set(s, &F, result, x_lower, x_upper);\n do {\n iter++;\n status = gsl_min_fminimizer_iterate(s);\n result = gsl_min_fminimizer_x_minimum(s);\n x_lower = gsl_min_fminimizer_x_lower(s);\n x_upper = gsl_min_fminimizer_x_upper(s);\n\n status = gsl_min_test_interval(x_lower, x_upper, eps, 0.0);\n\n if (status == GSL_SUCCESS) {\n estimated_parameter = result;\n break;\n }\n } while (status == GSL_CONTINUE && iter < MaxIter);\n\n if (iter >= MaxIter)\n estimated_parameter = result;\n }\n\n public:\n /*!\n *\n * @param first\n * @param beyond\n * @param result\n * @param x_lower\n * @param x_upper\n * @param eps\n */\n MLE(InputIterator first, InputIterator beyond,\n NT result, NT x_lower, NT x_upper, NT eps) {\n Norm norm;\n std::size_t num_elements = std::distance(first, beyond);\n if (num_elements == 1) {\n typename GeometryTraits::MovetkVector v = std::get(*first)\n - std::get(*first);\n NT l = norm(v);\n if (l < MOVETK_EPS) {\n estimated_parameter = MOVETK_EPS;\n return;\n }\n }\n (*this)(first, beyond, result, x_lower, x_upper, eps);\n }\n\n /*!\n *\n * @param first\n * @param beyond\n */\n MLE(InputIterator first, InputIterator beyond) {\n Norm norm;\n InputIterator it = first;\n NT upper_bound = 0, squared_length = 0;\n std::size_t num_elements = std::distance(first, beyond);\n if (num_elements == 1) {\n typename GeometryTraits::MovetkVector v = std::get(*first)\n - std::get(*first);\n NT l = norm(v);\n if (l < MOVETK_EPS) {\n estimated_parameter = MOVETK_EPS;\n return;\n }\n }\n while (it != beyond) {\n typename GeometryTraits::MovetkVector v = std::get(*it)\n - std::get(*it);\n NT l = norm(v);\n squared_length += l;\n if (l > upper_bound)\n upper_bound = l;\n it++;\n }\n NT initial_estimate = squared_length / (2 * num_elements);\n (*this)(first, beyond, initial_estimate, MOVETK_EPS, upper_bound, MOVETK_EPS);\n }\n\n /*!\n *\n * @return\n */\n NT operator()() {\n return estimated_parameter;\n }\n\n /*!\n *\n */\n ~MLE() {\n gsl_min_fminimizer_free(s);\n }\n };\n\n\n /*!\n *\n * @tparam GeometryTraits\n * @tparam ProbeTraits\n * @tparam ParameterTraits\n * @tparam Norm\n * @tparam GeoProjection\n */\n template\n class Model {\n private:\n\n typedef typename GeometryTraits::NT NT;\n typedef typename GeometryTraits::MovetkPoint Point;\n typedef typename GeometryTraits::MovetkVector Vector;\n movetk_core::MakePoint make_point;\n\n NT joint_log_likelihood = 0;\n\n Point mean(Point &p1, Point &p2, NT alpha) {\n Vector v = p2 - p1;\n v *= alpha;\n return (p1 + v);\n }\n\n public:\n /*!\n *\n * @tparam TrajectoryIterator\n * @tparam OutputIterator\n * @param first\n * @param beyond\n * @param result\n */\n template,\n typename = movetk_core::requires_tuple<\n typename TrajectoryIterator::value_type>,\n typename = movetk_core::requires_tuple_element_as_arithmetic<\n ProbeTraits::ProbeColumns::LAT, typename TrajectoryIterator::value_type>,\n typename = movetk_core::requires_tuple_element_as_arithmetic<\n ProbeTraits::ProbeColumns::LON, typename TrajectoryIterator::value_type>,\n typename = movetk_core::requires_tuple_element_as_size_t<\n ProbeTraits::ProbeColumns::SAMPLE_DATE, typename TrajectoryIterator::value_type>,\n typename = movetk_core::requires_output_iterator,\n typename = movetk_core::requires_tuple<\n typename OutputIterator::value_type>,\n typename = movetk_core::requires_tuple_element_as_movetk_point,\n typename = movetk_core::requires_tuple_element_as_movetk_point,\n typename = movetk_core::requires_tuple_element_as_NT>\n Model(TrajectoryIterator first, TrajectoryIterator beyond, OutputIterator result) {\n\n\n auto reflat = std::get(*first);\n auto reflon = std::get(*first);\n GeoProjection ref(reflat, reflon);\n\n TrajectoryIterator tit = first;\n std::size_t NumPoints = std::distance(first, beyond);\n\n if (NumPoints == 1) {\n auto lat = std::get(*first);\n auto lon = std::get(*first);\n auto projected_point = ref.project(lat, lon);\n Point p1 = make_point(std::cbegin(projected_point), std::cend(projected_point));\n *result = std::make_tuple(p1, p1, 0, first, first);\n return;\n }\n\n std::size_t multiple = (NumPoints - 1) / 2;\n std::size_t remainder = (NumPoints - 1) % 2;\n TrajectoryIterator last = first + 2 * multiple;\n\n\n while (tit != last) {\n auto lat = std::get(*tit);\n auto lon = std::get(*tit);\n auto projected_point = ref.project(lat, lon);\n Point p1 = make_point(std::cbegin(projected_point), std::cend(projected_point));\n\n lat = std::get(*(tit + 1));\n lon = std::get(*(tit + 1));\n projected_point = ref.project(lat, lon);\n Point p2 = make_point(std::cbegin(projected_point), std::cend(projected_point));\n\n lat = std::get(*(tit + 2));\n lon = std::get(*(tit + 2));\n projected_point = ref.project(lat, lon);\n Point p3 = make_point(std::cbegin(projected_point), std::cend(projected_point));\n\n auto ts1 = std::get(*tit);\n auto ts2 = std::get(*(tit + 1));\n auto ts3 = std::get(*(tit + 2));\n NT alpha = static_cast( ts3 - ts2 ) / static_cast( ts3 - ts1 );\n\n Point mu = mean(p1, p3, alpha);\n *result = std::make_tuple(p2, mu, 0, tit, tit + 2);\n tit += 2;\n }\n\n if (remainder == 1) {\n auto lat = std::get(*last);\n auto lon = std::get(*last);\n auto projected_point = ref.project(lat, lon);\n Point p1 = make_point(std::cbegin(projected_point), std::cend(projected_point));\n\n lat = std::get(*(last + 1));\n lon = std::get(*(last + 1));\n projected_point = ref.project(lat, lon);\n Point p2 = make_point(std::cbegin(projected_point), std::cend(projected_point));\n Point mu = mean(p1, p2, 0.5);\n *result = std::make_tuple(mu, mu, 0, last, last + 1);\n }\n\n }\n\n\n };\n\n\n /*!\n *\n * @tparam GeometryTraits\n * @tparam ParameterTraits\n */\n template\n class ParameterSelector {\n std::size_t SIZE;\n public:\n /*!\n *\n * @param size\n */\n ParameterSelector(std::size_t size) : SIZE(size) {}\n\n /*!\n *\n * @tparam InputIterator\n * @tparam OutputIterator\n * @param first\n * @param beyond\n * @param result\n */\n template,\n typename = movetk_core::requires_output_iterator,\n typename = movetk_core::requires_tuple,\n typename = movetk_core::requires_tuple_element_as_NT,\n typename = movetk_core::requires_NT>\n void operator()(InputIterator first, InputIterator beyond, OutputIterator result) {\n assert(std::distance(first, beyond) >= SIZE);\n std::vector coeffs;\n std::transform(first, beyond, std::back_inserter(coeffs), [](auto a) {\n return std::get(a);\n });\n std::sort(std::begin(coeffs), std::end(coeffs));\n std::size_t coeff_interval = std::distance(first, beyond) / SIZE;\n for (std::size_t i = 0; i < SIZE; i++) {\n std::size_t index = coeff_interval / 2 + coeff_interval * i;\n *result = coeffs[index];\n }\n }\n };\n\n\n template\n class LogLikelihood {\n typedef typename GeometryTraits::NT NT;\n typedef typename ParameterTraits::Parameters Parameters;\n public:\n LogLikelihood() = default;\n\n template,\n typename = movetk_core::requires_output_iterator,\n typename = movetk_core::requires_NT,\n typename = movetk_core::requires_NT>\n void operator()(const Parameters ¶ms, InputIterator first,\n InputIterator beyond, OutputIterator result) {\n Norm norm;\n typename GeometryTraits::MovetkVector v = std::get(params)\n - std::get(params);\n InputIterator pit = first;\n NT squared_length = norm(v);\n while (pit != beyond) {\n NT operand1 = -LOG_TWO_PI - log(*pit);\n NT operand2 = -squared_length / (2 * (*pit));\n NT log_likelihood = operand1 + operand2;\n *result = log_likelihood;\n pit++;\n }\n }\n\n NT operator()(const Parameters ¶ms, NT sigma_squared) {\n Norm norm;\n typename GeometryTraits::MovetkVector v = std::get(params)\n - std::get(params);\n NT squared_length = norm(v);\n NT operand1 = -LOG_TWO_PI - log(sigma_squared);\n NT operand2 = -squared_length / (2 * sigma_squared);\n return (operand1 + operand2);\n }\n };\n\n\n }\n\n\n}\n\n#endif //MOVETK_BROWNIANBRIDGE__H\n", "meta": {"hexsha": "6a855a1514a42dfff0c0ab49589cfc48f620483e", "size": 21678, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/movetk/algo/BrownianBridge.h", "max_stars_repo_name": "hiteshbedre/movetk", "max_stars_repo_head_hexsha": "8d261f19538e28ff36cac98a89ef067f8c26f978", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2020-09-09T19:52:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T10:04:24.000Z", "max_issues_repo_path": "src/include/movetk/algo/BrownianBridge.h", "max_issues_repo_name": "bacusters/movetk", "max_issues_repo_head_hexsha": "acbc9c5acb69dd3eb23aa7d2156ede02ed468eae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2020-09-11T17:40:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T23:56:19.000Z", "max_forks_repo_path": "src/include/movetk/algo/BrownianBridge.h", "max_forks_repo_name": "aniketmitra001/movetk", "max_forks_repo_head_hexsha": "cdf0c98121da6df4cadbd715fba02b05be724218", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-02-05T21:40:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-11T02:27:00.000Z", "avg_line_length": 43.356, "max_line_length": 139, "alphanum_fraction": 0.5398099456, "num_tokens": 4397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4249111580202288}} {"text": "/*****************************************************************************/\n#define this_is \"FDBinary v.3 beta (test version of 21 Feb 2010)\"\n/*****************************************************************************/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"mxfuns.h\"\n#include \"fd3sep.h\"\n#include \"triorb.h\"\n\n/*****************************************************************************/\n\n/* function and macro to kill the program with a short message */\n#define FDBErrorString \"\\nError in FDBianry\"\n#define DIE(s) {fprintf(stderr,\"%s: %s\\n\",FDBErrorString,s);fdbfailure();};\nvoid fdbfailure(void) { exit ( EXIT_FAILURE ); }\n\n/*****************************************************************************/\n\n/* macros for reading values from keyboard */\n#define GETDBL(x) {if(1!=scanf(\"%lg\",x)) DIE(\"failed reading double\");}\n#define GETINT(x) {if(1!=scanf(\"%d\", x)) DIE(\"failed reading int\");}\n#define GETLNG(x) {if(1!=scanf(\"%ld\",x)) DIE(\"failed reading long\");}\n#define GETSTR(x) {if(1!=scanf(\"%s\", x)) DIE(\"failed reading string\");}\n\n/*****************************************************************************/\n\n#define SPEEDOFLIGHT 2.998E5 /* speed of light in km/s */\n\nstatic char *triorb_strings[] = {\n /* 0 */ \"period of AB--C\", \"day\", \"%.9lg\",\n /* 1 */ \"time of periast pass in AB--C\", \"day\", \"%.9lg\",\n /* 2 */ \"eccentricity of AB--C\", \"1\", \"%.9lg\",\n /* 3 */ \"periast long of AB in AB--C\", \"deg\", \"%.9lg\",\n /* 4 */ \"a sin(incl) of AB in AB--C\", \"light-day\", \"%.9lg\",\n /* 5 */ \"a sin(incl) of C in AB--C\", \"light-day\", \"%.9lg\",\n /* 6 */ \"period A--B\", \"day\", \"%.9lg\",\n /* 7 */ \"time of periast pass in A--B\", \"day\", \"%.9lg\",\n /* 8 */ \"eccentricity of A--B\", \"1\", \"%.9lg\",\n /* 9 */ \"periast long of A in A--B\", \"deg\", \"%.9lg\",\n /* 10 */ \"rv semiamp of A in A--B\", \"km/s\", \"%.9lg\",\n /* 11 */ \"rv semiamp of B in A--B\", \"km/s\", \"%.9lg\",\n /* 12 */ \"periast long adv per cycle in A--B\", \"deg\", \"%.9lg\"\n};\n\nstatic char *triorb_pname (long j) { return triorb_strings[3*j]; }\nstatic char *triorb_punit (long j) { return triorb_strings[3*j+1]; }\nstatic char *triorb_pformat (long j) { return triorb_strings[3*j+2]; }\n\n/*****************************************************************************/\n\nstatic long K, M, N, Ndft, ksw[3], nfp, opsw[TRIORB_NP];\nstatic double **dftobs, **dftmod, **dftres;\nstatic double rvstep, *otimes, *rvcorr, *sig, **lfm, **rvm;\nstatic double op0[TRIORB_NP], dop0[TRIORB_NP];\nstatic double meritfngsl ( const gsl_vector *v, void *params );\nstatic double meritfn ( double *op );\n\n#define MX_FDBINARY_FORMAT \"%15.8E \"\nstatic char *mxfd3fmts=MX_FDBINARY_FORMAT;\n\n/* FDBinary */\n\nint main ( void ) {\n\n long i, i0, i1, j, k, vc, vlen, nruns, niter;\n double **masterobs, **mod, **res, **obs, z0, z1, stoprat;\n char obsfn[1024], resfn[1024], modfn[1024], rvsfn[1024], logfn[1024];\n char *starcode[] = {\"A\",\"B\",\"C\"};\n FILE *logfp;\n\n setbuf ( stdout, NULL );\n MxError( FDBErrorString, stdout, fdbfailure );\n MxFormat( mxfd3fmts );\n\n printf ( \"\\n %s\\n\", this_is );\n\n printf ( \"\\n SECTION 1: LOADING OBSERVED SPECTRA\\n\\n\" );\n printf ( \" observed spectra master file = \" );\n GETSTR ( obsfn ); printf ( \"%s\\n\", obsfn );\n vc=0; vlen=0; masterobs = MxLoad ( obsfn, &vc, &vlen ); M = vc - 1;\n printf ( \" loaded %ld spectra with %ld data pts per spectrum\\n\", M, vlen );\n z0 = **masterobs; z1 = *(*masterobs+vlen-1);\n rvstep = SPEEDOFLIGHT * ( - 1 + exp ((z1-z0)/(vlen-1)) );\n printf ( \" lnlambda range from %lf to %lf\\n\", z0, z1 );\n printf ( \" rv step %lg km/s per data point\\n\", rvstep );\n printf ( \" use data from lnlambda = \" );\n GETDBL ( &z0 ); printf ( \"%lg\\n\", z0 );\n printf ( \" to lnlambda = \" );\n GETDBL ( &z1 ); printf ( \"%lg\\n\", z1 );\n i0 = 0; while ( *(*masterobs+i0) < z0 ) i0++;\n i1 = vlen-1; while ( z1 < *(*masterobs+i1) ) i1--;\n N = i1 - i0 + 1;\n printf ( \" selected %ld data points per spectrum\\n\", N );\n obs = MxAlloc ( M+1, N );\n for ( i = 0 ; i < N ; i++ ) for ( j = 0 ; j <= M ; j++ )\n *(*(obs+j)+i) = *(*(masterobs+j)+i0+i);\n MxFree ( masterobs, vc, vlen );\n printf ( \" write selected data to file = \" );\n GETSTR ( obsfn ); printf ( \"%s\\n\", obsfn ); MxWrite ( obs, M+1, N, obsfn );\n\n printf ( \"\\n SECTION 2: COMPONENT SPECTRA MODELING SWITCHES (0/1)\\n\\n\" );\n for ( K = i = 0 ; i < 3 ; i++ ) {\n int sw;\n GETINT(&sw);\n sw = sw ? 1 : 0;\n printf ( \" %s = %d\\n\", starcode[i], sw );\n if ( sw ) ksw[K++] = i;\n }\n printf ( \"\\n number of components to be resolved is %ld\\n\", K );\n\n /* allocating memory */\n Ndft = 2*(N/2 + 1);\n dftobs = MxAlloc ( M, Ndft ); dft_fwd ( M, N, obs+1, dftobs );\n otimes = *MxAlloc ( 1, M );\n rvcorr = *MxAlloc ( 1, M );\n sig = *MxAlloc ( 1, M );\n res = MxAlloc ( M+1, N ); dftres = MxAlloc ( M, Ndft );\n mod = MxAlloc ( K+1, N ); dftmod = MxAlloc ( K, Ndft );\n rvm = MxAlloc ( K, M );\n lfm = MxAlloc ( K, M );\n for ( i = 0 ; i < N ; i++ ) { *(*res+i) = *(*obs+i); *(*mod+i) = *(*obs+i); } \n\n printf ( \"\\n SECTION 3: DESCRIPTORS TO OBSERVED SPECTRA\\n\" );\n printf ( \" AND LIGHT-FACTORS ASSIGNED TO COMPONENTS\\n\\n\" );\n printf ( \" %14s%12s%12s\", \"t_obs\", \"rv_corr\", \"noise_rms\" );\n for ( k = 0 ; k < K ; k++ ) printf ( \" lf_%s\", starcode[ksw[k]] );\n printf ( \"\\n\" );\n printf ( \" %14s%12s%12s\", \"[day]\", \"[km/s]\", \"[1]\" );\n for ( k = 0 ; k < K ; k++ ) printf ( \" [1]\" );\n printf ( \"\\n\\n\" );\n for ( j = 0 ; j < M ; j++ )\n {\n GETDBL(otimes+j); printf ( \" %14.5lf\", *(otimes+j) );\n GETDBL(rvcorr+j); printf ( \"%12.4lf\", *(rvcorr+j) );\n GETDBL(sig+j); printf ( \"%12.4lf\", *(sig+j) );\n for ( k = 0; k < K ; k++ )\n { GETDBL(*(lfm+k)+j); printf ( \"%10.4lf\", *(*(lfm+k)+j) ); }\n putchar ( '\\n' );\n }\n\n printf ( \"\\n SECTION 4: PARAMETERS OF ORBITS\\n\" );\n for ( nfp = i = 0 ; i < TRIORB_NP ; i++ ) {\n if ( 0 == i ) printf ( \"\\n wide (AB--C) orbit\\n\\n\" );\n if ( 6 == i ) printf ( \"\\n tight (A--B) orbit\\n\\n\" );\n printf ( \" %s [%s] = \", triorb_pname(i), triorb_punit(i) );\n GETDBL(op0+i); printf ( triorb_pformat(i), *(op0+i) );\n printf ( \" +/- \" );\n GETDBL(dop0+i); printf ( triorb_pformat(i), *(dop0+i) );\n if ( *(dop0+i) ) { opsw[nfp++] = i; printf ( \" *** free ***\" ); }\n if ( 2 == i || 8 == i ) *(op0+i) = *(op0+i) / (1-*(op0+i)); /* ecc */\n printf ( \"\\n\" );\n }\n printf ( \"\\n number of free orbital parameters is %ld\\n\", nfp );\n\n printf ( \"\\n SECTION 5: OPTIMISATION DETAILS\\n\\n\" );\n if ( 0 == nfp ) {\n printf ( \" WARNING: *** no free orbital parameters *** \\n\" );\n printf ( \" optimisation of orb. parameters will not be performed\\n\" );\n printf ( \" all input in this section is ignored\\n\\n\" );\n }\n GETLNG( &nruns );\n printf ( \" number of independent optimisation runs = %ld\\n\", nruns );\n GETLNG( &niter );\n printf ( \" number of allowed iterations per run = %ld\\n\", niter );\n GETDBL( &stoprat );\n printf ( \" stop when simplex shrinked by factor = %lg\\n\", stoprat );\n\n printf ( \"\\n SECTION 6: OUTPUT FILES\\n\\n\" );\n\n printf ( \" write model spectra to file = \" );\n GETSTR ( modfn ); printf ( \"%s\\n\", modfn );\n printf ( \" write residuals to file = \" );\n GETSTR ( resfn ); printf ( \"%s\\n\", resfn );\n printf ( \" write radial velocities to file = \" );\n GETSTR ( rvsfn ); printf ( \"%s\\n\", rvsfn );\n printf ( \" write optimisation log to file = \" );\n scanf ( \"%s\", logfn );\n if ( strlen ( logfn ) ) {\n printf ( \"%s\\n\", logfn );\n if ( NULL == ( logfp = fopen ( logfn, \"w\" ) ) )\n DIE ( \"could not open log file\" );\n setbuf ( logfp, NULL );\n } else {\n printf ( \"[no log file will be written]\\n\" );\n }\n\n printf ( \"\\n SECTION 7: OPTIMISATION\\n\\n\" );\n\n if ( 0 == nfp ) { /* separation */\n\n double chi2;\n\n printf ( \" WARNING: *** no free orbital parameters *** \\n\" );\n chi2 = meritfn ( op0 );\n printf ( \" separation at the starting point: chi2=%lg gof=%.2lf\\n\",\n chi2, gsl_sf_gamma_inc_Q ( N*(M-K)/2.0, chi2/2.0 ) );\n dft_bck ( K, N, dftmod, mod+1 ); MxWrite ( mod, K+1, N, modfn );\n dft_bck ( M, N, dftres, res+1 ); MxWrite ( res, M+1, N, resfn );\n MxWrite( rvm, K, M, rvsfn );\n\n } else { /* disentangling */\n\n const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;\n gsl_multimin_fminimizer *s = NULL; gsl_multimin_function minex_func;\n gsl_vector *ss, *x;\n size_t iter = 0, irun = 0, i; int status;\n double size0 = 1.0, size, chi2;\n const gsl_rng_type * R; gsl_rng * r;\n\n gsl_rng_env_setup (); R = gsl_rng_default; r = gsl_rng_alloc (R);\n\n minex_func.f = &meritfngsl;\n minex_func.n = nfp;\n minex_func.params = (void *) NULL;\n\n s = gsl_multimin_fminimizer_alloc (T, nfp);\n x = gsl_vector_alloc (nfp); /* starting point */\n ss = gsl_vector_alloc (nfp); /* initial vertex size vector */\n\n for ( i = 0 ; i < nfp ; i++ ) {\n gsl_vector_set ( x, i, op0[opsw[i]] );\n gsl_vector_set ( ss, i, dop0[opsw[i]] );\n size0 *= dop0[opsw[i]];\n }\n\n chi2 = meritfngsl ( x, NULL );\n printf ( \" separation at the starting point: chi2=%lg gof=%.2lf\\n\",\n chi2, gsl_sf_gamma_inc_Q ( N*(M-K)/2.0, chi2/2.0 ) );\n dft_bck ( K, N, dftmod, mod+1 ); MxWrite ( mod, K+1, N, modfn );\n dft_bck ( M, N, dftres, res+1 ); MxWrite ( res, M+1, N, resfn );\n MxWrite( rvm, K, M, rvsfn );\n\n printf\n ( \" converged disentangling runs reported only if chi2 decreases\\n\" );\n\n for ( irun = 0 ; irun < nruns ; irun++ ) {\n\n for ( i = 0 ; i < nfp ; i++ ) {\n double tmp = 2.0 * ( gsl_rng_uniform (r) - 0.5 );\n gsl_vector_set ( x, i, op0[opsw[i]] + tmp * dop0[opsw[i]] );\n gsl_vector_set ( ss, i, dop0[opsw[i]] );\n }\n\n gsl_multimin_fminimizer_set ( s, &minex_func, x, ss );\n status = GSL_FAILURE; size = size0;\n\n for ( iter = 0 ; iter < niter ; iter++ ) {\n if ( gsl_multimin_fminimizer_iterate (s) ) break;\n size = gsl_multimin_fminimizer_size (s);\n status = gsl_multimin_test_size (size, stoprat*size0);\n if ( GSL_SUCCESS == status ) break;\n }\n\n if ( (GSL_SUCCESS == status) && (s->fval < chi2) ) {\n printf ( \"\\n irun=%d iter=%d sxshrnkf=%.2lg chi2=%lg \",\n irun+1, iter, size/size0, chi2 = s->fval );\n printf ( \"gof=%.2lf\\n\",\n gsl_sf_gamma_inc_Q ( (N*(M-K)-nfp)/2.0, chi2/2.0 ) );\n for ( i = 0 ; i < nfp ; i++ ) {\n double xi = gsl_vector_get (s->x, i);\n if ( 2 == opsw[i] || 8 == opsw[i] ) xi = fabs ( xi / (1 + xi) );\n printf ( \" %40s = \", triorb_pname(opsw[i]) );\n printf ( triorb_pformat(opsw[i]), xi );\n if ( strcmp ( triorb_punit(opsw[i]), \"1\" ) )\n printf ( \" %s\", triorb_punit(opsw[i]) );\n printf ( \"\\n\" );\n }\n dft_bck ( K, N, dftmod, mod+1 ); MxWrite ( mod, K+1, N, modfn );\n dft_bck ( M, N, dftres, res+1 ); MxWrite ( res, M+1, N, resfn );\n MxWrite( rvm, K, M, rvsfn );\n }\n\n if ( (GSL_SUCCESS == status) && strlen ( logfn ) ) {\n fprintf ( logfp, \"%d %d %.2lg %lg \",\n irun+1, iter, size/size0, s->fval );\n fprintf ( logfp, \"%.2lf \",\n gsl_sf_gamma_inc_Q ( (N*(M-K)-nfp)/2.0, (s->fval)/2.0 ) );\n for ( i = 0 ; i < nfp ; i++ ) {\n double xi = gsl_vector_get (s->x, i);\n if ( 2 == opsw[i] || 8 == opsw[i] ) xi = fabs ( xi / (1 + xi) );\n fprintf ( logfp, \" \" );\n fprintf ( logfp, triorb_pformat(i), xi );\n }\n fprintf ( logfp, \"\\n\" );\n }\n\n }\n\n gsl_multimin_fminimizer_free (s);\n gsl_vector_free(x);\n gsl_vector_free(ss);\n\n printf ( \"\\n completed %ld optimisation runs\\n\\n\", nruns );\n\n }\n\n printf ( \" EXITING REGULARLY\\n\\n\" );\n\n return EXIT_SUCCESS;\n\n}\n\n/*****************************************************************************/\n\ndouble meritfngsl ( const gsl_vector *v, void *params ) \n{\n\n long i, j;\n double op[TRIORB_NP];\n\n for ( i = j = 0 ; i < TRIORB_NP ; i++ )\n op[i] = dop0[i] ? gsl_vector_get ( v, j++ ) : op0[i];\n\n return meritfn ( op );\n}\n\n/*****************************************************************************/\n\ndouble meritfn ( double *opin ) \n{\n\n long j, k;\n double op[TRIORB_NP], rv[3];\n\n op[ 0] = opin[ 0];\n op[ 1] = opin[ 1];\n op[ 2] = fabs ( opin[2] / (1 + opin[2]) );\n op[ 3] = opin[ 3] * (M_PI/180);\n op[ 4] = opin[ 4];\n op[ 5] = opin[ 5];\n op[ 6] = opin[ 6];\n op[ 7] = opin[ 7];\n op[ 8] = fabs ( opin[8] / (1 + opin[8]) );\n op[ 9] = opin[ 9] * (M_PI/180);\n op[10] = opin[10] / rvstep;\n op[11] = opin[11] / rvstep;\n op[12] = opin[12] * (M_PI/180);\n\n for ( j = 0 ; j < M ; j++ ) {\n triorb_rv ( op, otimes[j], rv );\n for ( k = 0 ; k < K ; k++ )\n *(*(rvm+k)+j) = rv[ksw[k]] + *(rvcorr+j) / rvstep;\n }\n\n return fd3sep ( K, M, N, dftobs, sig, rvm, lfm, dftmod, dftres );\n}\n\n/*****************************************************************************/\n\n", "meta": {"hexsha": "3d4e91d4b1c11430119a6f9454f787ab6de15a1b", "size": 13269, "ext": "c", "lang": "C", "max_stars_repo_path": "fdbinary.c", "max_stars_repo_name": "mrawls/FDBinary-tools", "max_stars_repo_head_hexsha": "26b78a12df53d9a1a477fcf247cbf2dad8c39836", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-25T09:45:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-28T14:43:53.000Z", "max_issues_repo_path": "fdbinary.c", "max_issues_repo_name": "mrawls/FDBinary-tools", "max_issues_repo_head_hexsha": "26b78a12df53d9a1a477fcf247cbf2dad8c39836", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fdbinary.c", "max_forks_repo_name": "mrawls/FDBinary-tools", "max_forks_repo_head_hexsha": "26b78a12df53d9a1a477fcf247cbf2dad8c39836", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9610027855, "max_line_length": 80, "alphanum_fraction": 0.4986057729, "num_tokens": 4577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4247473726664117}} {"text": "#define _USE_MATH_DEFINES\n#include \n#include \n#include \n#include \n#include \n#include \n//#include \n\nusing Eigen::Matrix;\nusing Eigen::VectorXd;\n\nvoid li(size_t k, double x, Matrix &ans);\n\ntemplate\nclass Distribution {\nprivate:\n T loc;\n T scale;\n Matrix param;\n size_t k;\n //\n Matrix C;\n Matrix C_inf;\n Matrix Gamma;\n Matrix C_li;\n Matrix Col;\n Matrix Col_arg;\n Matrix Alpha;\n Matrix M;\n Matrix C_y;\n std::vector y_abs_pow;\n Matrix X_pow;\n Matrix Li;\n Matrix I;\n Matrix I_u;\n Matrix I_t;\npublic:\n Distribution(T loc_, T scale_, Matrix param_)\n : loc(loc_), scale(scale_), param(std::move(param_)), k(param.size()),\n C_y(Matrix::Ones(2 * k - 2)), y_abs_pow(2 * k - 1), X_pow(Matrix(2 * k - 2)),\n Li(Matrix(2 * k - 2)), I_u(Matrix(2 * k - 1)) {\n // Vector of i * Gamma(i) * (1 - 2^{1 - i}) * zeta(i)\n C = Matrix(2 * k - 2);\n C[0] = M_LN2;\n\n {\n double curr = 0.5;\n for (size_t i = 2; i <= 2 * k - 2; i++) {\n C[i - 1] = i * gsl_sf_fact(i - 1) * (1 - curr) * gsl_sf_zeta_int(i);\n curr /= 2;\n }\n }\n\n C_inf = Matrix::Ones(2 * k - 2);\n for (size_t i = 0; i < 2 * k - 2; i += 2) {\n C_inf[i] = -1;\n }\n\n // Vector of i * Gamma(i)\n Gamma = Matrix(2 * k - 2);\n\n C_li = Matrix::Zero(2 * k - 2, 2 * k - 2);\n for (size_t i = 0; i < 2 * k - 2; i++) {\n Gamma[i] = gsl_sf_fact(i + 1);\n if (i != 0) {\n C_li(i, 0) = 1 / Gamma[i - 1];\n } else {\n C_li(i, 0) = 1;\n }\n }\n\n // Matrix of collocation coefficients\n Col = Matrix::Zero(2 * k - 1, 2 * k - 1);\n for (size_t i = 0; i < 2 * k - 1; i++) {\n for (size_t j = 0; j <= i; j++) {\n Col(i, j) = gsl_sf_choose(i, j);\n }\n }\n\n M = Matrix(2 * k - 1);\n M[0] = 1;\n for (size_t i = 1; i < 2 * k - 1; i++) {\n M[i] = i % 2 == 1 ? 0 : 2 * C[i - 1];\n }\n\n precalc();\n }\n\n void precalc() {\n // Matrix of collocation coefficients\n std::vector locs(2 * k - 1), scales(2 * k - 1);\n locs[0] = 1;\n scales[0] = 1;\n for (size_t i = 1; i < 2 * k - 1; i++) {\n locs[i] = locs[i - 1] * loc;\n scales[i] = scales[i - 1] * scale;\n }\n\n Col_arg = Col;\n for (size_t i = 0; i < 2 * k - 1; i++) {\n for (size_t j = 0; j <= i; j++) {\n Col_arg(i, j) *= locs[i - j] * scales[j];\n }\n }\n\n // Matrix of shifted alpha parameter vector\n Alpha = Matrix::Zero(k, 2 * k - 1);\n for (size_t i = 0; i < k; i++) {\n for (size_t j = i; j < i + k; j++) {\n Alpha(i, j) = param[j - i];\n }\n }\n Alpha = param.transpose() * Alpha;\n }\n\n void reset_param(T loc_, T scale_, Eigen::Matrix ¶m_) {\n loc = loc_;\n scale = scale_;\n param = param_;\n precalc();\n }\n\n double cdf(T x) {\n// std::cout << \"x = \" << x << std::endl;\n T y = (x - loc) / scale;\n T y_abs = abs(y);\n\n if (y < 0) {\n for (size_t i = 1; i < 2 * k - 2; i += 2) {\n C_y[i] = -1;\n }\n } else {\n for (size_t i = 1; i < 2 * k - 2; i += 2) {\n C_y[i] = 1;\n }\n }\n\n // Vector of pow(arg, i)\n y_abs_pow[0] = 1;\n for (size_t i = 1; i < 2 * k - 1; i++) {\n y_abs_pow[i] = y_abs_pow[i - 1] * y_abs;\n }\n\n for (size_t i = 0; i < 2 * k - 2; i++) {\n X_pow[i] = y_abs_pow[i + 1]; // (y_abs, i + 1);\n }\n X_pow = (0.5 * tanh(y_abs / 2) - 0.5) * X_pow;\n\n // Polylogarithms vector\n\n// for (size_t i = 0; i < 2 * k - 2; i++) {\n// if (y_abs >= 690) Li[i] = 0;\n// else Li[i] = -gsl_sf_fermi_dirac_int(i, -y_abs);\n// }\n double z = -std::exp(-y_abs);\n li(2 * k - 2, z, Li);\n// std::cout << \"li = \" << Li.transpose() << std::endl;\n\n // Polylogarithm coefficients\n Matrix C_li_arg = C_li;\n for (size_t i = 0; i < 2 * k - 2; i++) {\n C_li_arg(i, 0) *= y_abs_pow[i]; // pow(y_abs, i);\n for (size_t j = 1; j <= i; j++) {\n C_li_arg(i, j) = C_li_arg(i - 1, j - 1);\n }\n }\n\n C_li_arg = C_li_arg * Li;\n C_li_arg = Gamma.array() * C_li_arg.array();\n\n I = (C_inf + C_y).array() * C.array() + C_y.array() * X_pow.array() + C_y.array() * C_li_arg.array();\n\n // from -infty to 0 + 0.5 * tanh\n T C_y0 = y >= 0 ? 1 : -1;\n I_u << 0.5 + C_y0 * 0.5 * tanh(y_abs / 2), I;\n\n // Vector I^t\n I_t = Col_arg * I_u;\n T fx = (Alpha * I_t)(0);\n T C_1 = 1 / (Alpha * Col_arg * M).sum();\n// std::cout << \"fx = \" << C_1 * fx << std::endl;\n return C_1 * fx;\n }\n};\n", "meta": {"hexsha": "889fa09c299f79c9713da38dd26ae3e81b5e1eff", "size": 5468, "ext": "h", "lang": "C", "max_stars_repo_path": "nychka/distribution/approx_class.h", "max_stars_repo_name": "ainmukh/project", "max_stars_repo_head_hexsha": "c5a7481414bd2baa2b38b8c64c593348846b6660", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nychka/distribution/approx_class.h", "max_issues_repo_name": "ainmukh/project", "max_issues_repo_head_hexsha": "c5a7481414bd2baa2b38b8c64c593348846b6660", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nychka/distribution/approx_class.h", "max_forks_repo_name": "ainmukh/project", "max_forks_repo_head_hexsha": "c5a7481414bd2baa2b38b8c64c593348846b6660", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3978494624, "max_line_length": 111, "alphanum_fraction": 0.407644477, "num_tokens": 1985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.42458247295606644}} {"text": "#ifndef __MATH_GSL_VECTOR__\n#define __MATH_GSL_VECTOR__\n\n#include \n\n#include \n#include \n\n#include \n#include \"math/vectorops.h\"\n\nclass GslVectorItem {\n public:\n GslVectorItem(gsl_vector* ptr, size_t index) :\n ptr_(ptr),\n index_(index) { }\n\n operator const double() {\n return gsl_vector_get(ptr_, index_);\n }\n\n double operator =(const double v) {\n gsl_vector_set(ptr_, index_, v);\n return v;\n }\n\n double operator +=(const double v) {\n double oldv = gsl_vector_get(ptr_, index_);\n gsl_vector_set(ptr_, index_, oldv + v);\n return oldv + v;\n }\n\n double operator -=(const double v) {\n double oldv = gsl_vector_get(ptr_, index_);\n gsl_vector_set(ptr_, index_, oldv - v);\n return oldv - v;\n }\n private:\n gsl_vector* ptr_;\n size_t index_;\n};\n\nclass GslVectorBase {\n public:\n /*\n double operator[](const size_t index) const {\n assert(ptr_ != NULL);\n return gsl_vector_get(ptr_, index);\n }\n */\n\n GslVectorItem operator[](const size_t index) const {\n assert(ptr_ != NULL);\n return GslVectorItem(ptr_, index);\n }\n\n GslVectorBase& operator+=(const gsl_vector* x) {\n assert(ptr_ != NULL);\n gsl_vector_add(ptr_, x);\n return *this;\n }\n\n GslVectorBase& operator-=(const gsl_vector* x) {\n assert(ptr_ != NULL);\n gsl_vector_sub(ptr_, x);\n return *this;\n }\n\n GslVectorBase& operator+=(const GslVectorBase& x) {\n assert(ptr_ != NULL);\n gsl_vector_add(ptr_, x.ptr());\n return *this;\n }\n\n GslVectorBase& operator-=(const GslVectorBase& x) {\n assert(ptr_ != NULL);\n gsl_vector_sub(ptr_, x.ptr());\n return *this;\n }\n\n GslVectorBase& operator*=(const gsl_vector* x) {\n assert(ptr_ != NULL);\n gsl_vector_mul(ptr_, x);\n return *this;\n }\n\n GslVectorBase& operator*=(const GslVectorBase& x) {\n assert(ptr_ != NULL);\n gsl_vector_mul(ptr_, x.ptr());\n return *this;\n }\n\n GslVectorBase& operator/=(const GslVectorBase& x) {\n assert(ptr_ != NULL);\n gsl_vector_div(ptr_, x.ptr());\n return *this;\n }\n\n double Sum() const {\n return gsl_blas_dsum(ptr_);\n }\n\n double L2Norm() const {\n return gsl_blas_dnrm2(ptr_);\n }\n\n void Normalize() const {\n assert(ptr_ != NULL);\n double s = Sum();\n gsl_vector_scale(ptr_, 1. / s);\n }\n\n size_t size() const {\n return ptr_->size;\n }\n\n GslVectorBase& operator*=(double v) {\n assert(ptr_ != NULL);\n gsl_vector_scale(ptr_, v);\n return *this;\n }\n\n GslVectorBase& operator/=(double v) {\n assert(ptr_ != NULL);\n gsl_vector_scale(ptr_, 1. / v);\n return *this;\n }\n\n // Note that the standalone product is a dot product!\n const double operator*(const gsl_vector* x) const {\n double result;\n assert(ptr_ != NULL);\n gsl_blas_ddot(ptr_, x, &result);\n return result;\n }\n\n const double operator*(const GslVectorBase& x) const {\n double result;\n assert(ptr_ != NULL);\n gsl_blas_ddot(ptr_, x.ptr(), &result);\n return result;\n }\n\n GslVectorBase& operator+=(const double x) {\n for (size_t ii = 0; ii < ptr_->size; ++ii) {\n gsl_vector_set(ptr_, ii, gsl_vector_get(ptr_, ii) + x);\n }\n return *this;\n }\n\n GslVectorBase& operator-=(const double x) {\n for (size_t ii = 0; ii < ptr_->size; ++ii) {\n gsl_vector_set(ptr_, ii, gsl_vector_get(ptr_, ii) - x);\n }\n return *this;\n }\n\n GslVectorBase& operator=(const gsl_vector* x) {\n assert(ptr_ != NULL);\n gsl_vector_memcpy(ptr_, x);\n\n return *this;\n }\n\n GslVectorBase& operator=(const GslVectorBase& x) {\n assert(ptr_ != NULL);\n return *this = x.ptr();\n }\n\n GslVectorBase& operator=(const double v) {\n if (v == 0.0) {\n SetZero();\n } else {\n SetAll(v);\n }\n return *this;\n }\n\n void SetZero() {\n assert(ptr_ != NULL);\n gsl_vector_set_zero(ptr_);\n }\n\n void SetAll(const double v) {\n assert(ptr_ != NULL);\n gsl_vector_set_all(ptr_, v);\n }\n\n int Fprintf(FILE* stream, const char* format) const {\n assert(ptr_ != NULL);\n return gsl_vector_fprintf(stream, ptr_, format);\n }\n\n int Fscanf(FILE* stream) {\n assert(ptr_ != NULL);\n return gsl_vector_fscanf(stream, ptr_);\n }\n\n const gsl_vector* ptr() const { return ptr_; }\n gsl_vector* mutable_ptr() { return ptr_; }\n\n protected:\n GslVectorBase() : ptr_(NULL) { }\n gsl_vector* ptr_;\n\n private:\n GslVectorBase(const GslVectorBase&) { }\n};\n\nclass GslVector : public GslVectorBase {\n public:\n GslVector(const size_t size) : GslVectorBase() {\n Allocate(size);\n }\n\n GslVector() : GslVectorBase() {\n }\n\n ~GslVector() {\n if (ptr_ != NULL) {\n gsl_vector_free(ptr_);\n }\n }\n\n void Reset(gsl_vector* val) {\n if (ptr_ != NULL) {\n gsl_vector_free(ptr_);\n }\n ptr_ = val;\n }\n\n void Allocate(const size_t size) {\n assert(ptr_ == NULL);\n ptr_ = gsl_vector_alloc(size);\n }\n\n GslVectorBase& operator=(const gsl_vector* x) {\n GslVectorBase::operator=(x);\n return *this;\n }\n\n GslVectorBase& operator=(const GslVectorBase& x) {\n GslVectorBase::operator=(x);\n return *this;\n }\n\n GslVectorBase& operator=(const double v) {\n GslVectorBase::operator=(v);\n return *this;\n }\n private:\n GslVector(const GslVector&) { }\n};\n\nclass GslMatrixRow : public GslVectorBase {\n public:\n GslMatrixRow(GslMatrix& matrix, const size_t row) :\n view_(gsl_matrix_row(matrix.mutable_ptr(), row)) { \n ptr_ = &view_.vector;\n }\n\n GslMatrixRow(gsl_matrix* matrix, const size_t row) :\n view_(gsl_matrix_row(matrix, row)) { \n ptr_ = &view_.vector;\n }\n\n GslVectorBase& operator=(const gsl_vector* x) {\n GslVectorBase::operator=(x);\n return *this;\n }\n\n GslVectorBase& operator=(const GslVectorBase& x) {\n GslVectorBase::operator=(x);\n return *this;\n }\n\n GslVectorBase& operator=(const double v) {\n GslVectorBase::operator=(v);\n return *this;\n }\n private:\n gsl_vector_view view_;\n GslMatrixRow(const GslMatrixRow&) { }\n};\n\nclass GslMatrixColumn : public GslVectorBase {\n public:\n GslMatrixColumn(GslMatrix& matrix, const size_t col) :\n view_(gsl_matrix_column(matrix.mutable_ptr(), col)) { \n ptr_ = &view_.vector;\n }\n\n GslMatrixColumn(gsl_matrix* matrix, const size_t col) :\n view_(gsl_matrix_column(matrix, col)) { \n ptr_ = &view_.vector;\n }\n\n GslVectorBase& operator=(const gsl_vector* x) {\n GslVectorBase::operator=(x);\n return *this;\n }\n\n GslVectorBase& operator=(const GslVectorBase& x) {\n GslVectorBase::operator=(x);\n return *this;\n }\n\n GslVectorBase& operator=(const double v) {\n GslVectorBase::operator=(v);\n return *this;\n }\n private:\n gsl_vector_view view_;\n GslMatrixColumn(const GslMatrixColumn&) { }\n};\n\nclass GslMatrixDiagonal : public GslVectorBase {\n public:\n GslMatrixDiagonal(GslMatrix& matrix) :\n view_(gsl_matrix_diagonal(matrix.mutable_ptr())) { \n ptr_ = &view_.vector;\n }\n\n GslMatrixDiagonal(gsl_matrix* matrix) :\n view_(gsl_matrix_diagonal(matrix)) { \n ptr_ = &view_.vector;\n }\n\n GslVectorBase& operator=(const gsl_vector* x) {\n GslVectorBase::operator=(x);\n return *this;\n }\n\n GslVectorBase& operator=(const GslVectorBase& x) {\n GslVectorBase::operator=(x);\n return *this;\n }\n\n GslVectorBase& operator=(const double v) {\n GslVectorBase::operator=(v);\n return *this;\n }\n private:\n gsl_vector_view view_;\n GslMatrixDiagonal(const GslMatrixDiagonal&) { }\n};\n\nclass GslSubvector : public GslVectorBase {\n public:\n GslSubvector(GslVectorBase& vector, size_t i, size_t n) :\n view_(gsl_vector_subvector(vector.mutable_ptr(), i, n)) { \n ptr_ = &view_.vector;\n }\n\n GslVectorBase& operator=(const gsl_vector* x) {\n GslVectorBase::operator=(x);\n return *this;\n }\n\n GslVectorBase& operator=(const GslVectorBase& x) {\n GslVectorBase::operator=(x);\n return *this;\n }\n\n GslVectorBase& operator=(const double v) {\n GslVectorBase::operator=(v);\n return *this;\n }\n private:\n gsl_vector_view view_;\n GslSubvector(const GslSubvector&) { }\n};\n\n#endif // __MATH_GSL_VECTOR__\n\n", "meta": {"hexsha": "402343cde49f770c6e440778eea1b317bca4a4d7", "size": 8018, "ext": "h", "lang": "C", "max_stars_repo_path": "DTM/dtm-master/lib/math/gsl_vector.h", "max_stars_repo_name": "boomsbloom/dtm-fmri", "max_stars_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z", "max_issues_repo_path": "DTM/dtm-master/lib/math/gsl_vector.h", "max_issues_repo_name": "boomsbloom/dtm-fmri", "max_issues_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DTM/dtm-master/lib/math/gsl_vector.h", "max_forks_repo_name": "boomsbloom/dtm-fmri", "max_forks_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z", "avg_line_length": 21.3244680851, "max_line_length": 63, "alphanum_fraction": 0.6440508855, "num_tokens": 2338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4243954657834915}} {"text": "#include \n#include \n#include \n#include \"parmt_utils.h\"\n#ifdef PARMT_USE_INTEL\n#include \n#else\n#include \n#endif\n#include \"iscl/memory/memory.h\"\n\n/*!\n * @brief Converts the NED based fundamental faults to Green's functions which\n * scale the NED based moment tensor terms s.t. \\f$ u = G m \\f$.\n * where \\f$ m = \\{ m_{xx}, m_{yy}, m_{zz}, m_{xy}, m_{xz}, m_{yz} \\} \\f$\n * are the NED moment tensor terms and \\f$ u \\f$ is the estimate for\n * the icomp'th component with source receiver azimuth, az, and given\n * channel orientation encapsulated by cmpaz and cmpinc.\n *\n * @param[in] npgrns number of points in greens functions\n * @param[in] ldg leading dimension of G (>= 6)\n * @param[in] icomp =1 for vertical Green's functions.\n * =2 for north (channel 2) Green's functions.\n * =3 for east (channel 3) Green's functions.\n * @param[in] azin source to receiver azimuth (degrees)\n * @param[in] bazin receiver to source azimuth (degrees). if you \n * do not know then set this to:\n * fmod(az + 180.0, 360.0)\n * @param[in] cmpaz component azimuth (0 north, +90 east)\n * @param[in] cmpinc component inclinantion (-90 up, 0 east/north, +90 down)\n * @param[in] ZDS vertical greens fn for 90 degree dip slip [npgrns]\n * @param[in] ZSS vertical greens fn for vertical strike slip [npgrns]\n * @param[in] ZDD vertical greens fn for 45 degree dip slip [npgrns]\n * @param[in] ZEX vertical greens fn for an explosion [npgrns]\n * @param[in] RDS radial greens fn for 90 degree dip slip [npgrns]\n * @param[in] RSS radial greens fn for vertical strike slip [npgrns]\n * @param[in] RDD radial greens fn for 45 degree dip slip [npgrns]\n * @param[in] REX radial greens fn for an explosion [npgrns]\n * @param[in] TDS transverse greens fn for 90 degree dip slip [npgrns]\n * @param[in] TSS transverse greens fn for vertical strike slip [npgrns]\n *\n * @param[out] G row major Green's functions matrix [npgrns x ldg].\n * the columns are ordered: \n * \\f$ \\{ G_{xx}, G_{yy}, G_{zz},\n * G_{xy}, G_{xz}, G_{yz} \\} \\f$\n *\n * @result 0 indicates success\n *\n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n */\nint parmt_utils_ff2mtGreensMatrix64f(const int npgrns, const int ldg,\n const int icomp,\n const double azin, const double bazin,\n const double cmpaz, const double cmpinc,\n const double *__restrict__ ZDS,\n const double *__restrict__ ZSS,\n const double *__restrict__ ZDD,\n const double *__restrict__ ZEX,\n const double *__restrict__ RDS,\n const double *__restrict__ RSS,\n const double *__restrict__ RDD,\n const double *__restrict__ REX,\n const double *__restrict__ TDS,\n const double *__restrict__ TSS,\n double *__restrict__ G)\n{\n double *Gxx, *Gyy, *Gzz, *Gxy, *Gxz, *Gyz;\n int ierr;\n ierr = 0;\n if (npgrns < 1 || ldg < 6 || G == NULL)\n {\n if (npgrns < 1)\n {\n fprintf(stderr, \"%s: No points in greens fns\\n\", __func__);\n }\n if (ldg < 6){fprintf(stderr, \"%s: ldg must be >= 6\\n\", __func__);}\n if (G == NULL){fprintf(stderr, \"%s: Error G is NULL\\n\", __func__);}\n return -1;\n }\n Gxx = memory_calloc64f(npgrns);\n Gyy = memory_calloc64f(npgrns);\n Gzz = memory_calloc64f(npgrns);\n Gxy = memory_calloc64f(npgrns);\n Gxz = memory_calloc64f(npgrns);\n Gyz = memory_calloc64f(npgrns);\n ierr = parmt_utils_ff2mtGreens64f(npgrns, icomp, azin, bazin,\n cmpaz, cmpinc,\n ZDS, ZSS, ZDD, ZEX,\n RDS, RSS, RDD, REX,\n TDS, TSS,\n Gxx, Gyy, Gzz,\n Gxy, Gxz, Gyz);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Failed to compute greens functions columns\\n\",\n __func__);\n } \n else\n {\n cblas_dcopy(npgrns, Gxx, 1, &G[0], ldg);\n cblas_dcopy(npgrns, Gyy, 1, &G[1], ldg);\n cblas_dcopy(npgrns, Gzz, 1, &G[2], ldg);\n cblas_dcopy(npgrns, Gxy, 1, &G[3], ldg);\n cblas_dcopy(npgrns, Gxz, 1, &G[4], ldg);\n cblas_dcopy(npgrns, Gyz, 1, &G[5], ldg);\n }\n memory_free64f(&Gxx);\n memory_free64f(&Gyy);\n memory_free64f(&Gzz);\n memory_free64f(&Gxy);\n memory_free64f(&Gxz);\n memory_free64f(&Gyz);\n return ierr;\n}\n//============================================================================//\n/*!\n * @brief Converts the NED based fundamental faults to Green's functions which\n * scale the NED based moment tensor terms s.t. \\f$ u = G m \\f$.\n * where \\f$ m = \\{ m_{xx}, m_{yy}, m_{zz}, m_{xy}, m_{xz}, m_{yz} \\} \\f$\n * are the NED moment tensor terms and \\f$ u \\f$ is the estimate for\n * the icomp'th component with source receiver azimuth, az, and given\n * channel orientation encapsulated by cmpaz and cmpinc. \n *\n * @param[in] npgrns number of points in greens functions\n * @param[in] icomp =1 for vertical Green's functions.\n * =2 for north (channel 2) Green's functions.\n * =3 for east (channel 3) Green's functions.\n * @param[in] azin source to receiver azimuth (degrees)\n * @param[in] bazin receiver to source azimuth (degrees). if you \n * do not know then set this to:\n * fmod(az + 180.0, 360.0)\n * @param[in] cmpaz component azimuth (0 north, +90 east)\n * @param[in] cmpinc component inclinantion (-90 up, 0 east/north, +90 down)\n * @param[in] ZDS vertical greens fn for 90 degree dip slip [npgrns]\n * @param[in] ZSS vertical greens fn for vertical strike slip [npgrns]\n * @param[in] ZDD vertical greens fn for 45 degree dip slip [npgrns]\n * @param[in] ZEX vertical greens fn for an explosion [npgrns]\n * @param[in] RDS radial greens fn for 90 degree dip slip [npgrns]\n * @param[in] RSS radial greens fn for vertical strike slip [npgrns]\n * @param[in] RDD radial greens fn for 45 degree dip slip [npgrns]\n * @param[in] REX radial greens fn for an explosion [npgrns]\n * @param[in] TDS transverse greens fn for 90 degree dip slip [npgrns]\n * @param[in] TSS transverse greens fn for vertical strike slip [npgrns]\n *\n * @param[out] Gxx greens function scaling mxx moment tensor term [npgrns]\n * @param[out] Gyy greens function scaling myy moment tensor term [npgrns]\n * @param[out] Gzz greens function scaling mzz moment tensor term [npgrns]\n * @param[out] Gxy greens function scaling mxy moment tensor term [npgrns]\n * @param[out] Gxz greens function scaling mxz moment tensor term [npgrns]\n * @param[out] Gyz greens function scaling myz moment tensor term [npgrns]\n *\n * @result 0 indicates success\n *\n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n */\nint parmt_utils_ff2mtGreens64f(const int npgrns, const int icomp,\n const double azin, const double bazin,\n const double cmpaz, const double cmpinc,\n const double *__restrict__ ZDS,\n const double *__restrict__ ZSS,\n const double *__restrict__ ZDD,\n const double *__restrict__ ZEX,\n const double *__restrict__ RDS,\n const double *__restrict__ RSS,\n const double *__restrict__ RDD,\n const double *__restrict__ REX,\n const double *__restrict__ TDS,\n const double *__restrict__ TSS,\n double *__restrict__ Gxx,\n double *__restrict__ Gyy,\n double *__restrict__ Gzz,\n double *__restrict__ Gxy,\n double *__restrict__ Gxz,\n double *__restrict__ Gyz)\n{\n double az, baz, c2a, ca, caz, cos_caz, cost,\n gxx_e, gxy_e, gxz_e, gyy_e, gyz_e, gzz_e,\n gxx_n, gxy_n, gxz_n, gyy_n, gyz_n, gzz_n,\n gxx_r, gxy_r, gxz_r, gyy_r, gyz_r, gzz_r,\n gxx_t, gxy_t, gxz_t, gyy_t, gyz_t, gzz_t,\n gxx_z, gxy_z, gxz_z, gyy_z, gyz_z, gzz_z,\n rex, rdd, rds, rss, s2a, sa, sin_caz, sint,\n tds, tss, xscal,\n zex, zdd, zds, zss;\n int i;\n const double pi180 = M_PI/180.0;\n const double half = 0.5; \n const double sixth = 1.0/6.0;\n const double third = 1.0/3.0;\n //------------------------------------------------------------------------//\n if (icomp < 1 || icomp > 3)\n {\n fprintf(stderr, \"%s: Invalid component: %d\\n\", __func__, icomp);\n return -1;\n }\n if (icomp == 1)\n {\n if (ZDS == NULL || ZSS == NULL || ZDD == NULL || ZEX == NULL)\n {\n if (ZDS == NULL){fprintf(stderr, \"%s: zds is NULL\\n\", __func__);}\n if (ZSS == NULL){fprintf(stderr, \"%s: zss is NULL\\n\", __func__);}\n if (ZDD == NULL){fprintf(stderr, \"%s: zdd is NULL\\n\", __func__);}\n if (ZEX == NULL){fprintf(stderr, \"%s: zex is NULL\\n\", __func__);}\n return -1;\n }\n }\n else\n {\n if (RDS == NULL || RSS == NULL || RDD == NULL || REX == NULL ||\n TDS == NULL || TSS == NULL)\n {\n if (RDS == NULL){fprintf(stderr, \"%s: rds is NULL\\n\", __func__);}\n if (RSS == NULL){fprintf(stderr, \"%s: rss is NULL\\n\", __func__);}\n if (RDD == NULL){fprintf(stderr, \"%s: rdd is NULL\\n\", __func__);}\n if (REX == NULL){fprintf(stderr, \"%s: rex is NULL\\n\", __func__);}\n if (TDS == NULL){fprintf(stderr, \"%s: tds is NULL\\n\", __func__);}\n if (TSS == NULL){fprintf(stderr, \"%s: tss is NULL\\n\", __func__);}\n return -1;\n }\n } \n // Get the backazimuth\n az = azin;\n baz = bazin; //fmod(az + 180.0, 360.0);\n // Convert to radians\n az = az*pi180;\n baz = baz*pi180;\n caz = cmpaz*pi180;\n // Compute the geometric factors\n sa = sin(az);\n ca = cos(az);\n s2a = sin(2.*az);\n c2a = cos(2.*az);\n sint = sin(baz);\n cost = cos(baz);\n cos_caz = cos(caz);\n sin_caz = sin(caz);\n // the cmpaz will come from the metadata so fix that\n if (icomp == 3)\n {\n cos_caz = cos(caz - M_PI/2.0);\n sin_caz = sin(caz - M_PI/2.0);\n }\n // Set the columns (Minson et. al. 2008)\n xscal = 1.0;\n if (fabs(cmpinc - 90.0) < 1.e-4){xscal =-1.0;}\n if (icomp == 1)\n {\n #pragma omp simd\n for (i=0; i (n, e)\n // n = cos(baz-180)*r - sin(baz-180)*t\n // =-cos(baz)*r + sin(baz)*t\n // e = sin(baz-180)*r + cos(baz-180)*t\n // =-sin(baz)*r - cos(baz)*t\n gxx_n =-cost*gxx_r + sint*gxx_t;\n gxx_e =-sint*gxx_r - cost*gxx_t;\n gyy_n =-cost*gyy_r + sint*gyy_t;\n gyy_e =-sint*gyy_r - cost*gyy_t;\n gzz_n =-cost*gzz_r + sint*gzz_t;\n gzz_e =-sint*gzz_r - cost*gzz_t;\n gxy_n =-cost*gxy_r + sint*gxy_t;\n gxy_e =-sint*gxy_r - cost*gxy_t;\n gxz_n =-cost*gxz_r + sint*gxz_t;\n gxz_e =-sint*gxz_r - cost*gxz_t;\n gyz_n =-cost*gyz_r + sint*gyz_t;\n gyz_e =-sint*gyz_r - cost*gyz_t;\n // Rotate from (n, e) -> (1, 2) around az\n // 1 = cos(comp_az)*n + sin(comp_az)*e\n Gxx[i] = cos_caz*gxx_n + sin_caz*gxx_e;\n Gyy[i] = cos_caz*gyy_n + sin_caz*gyy_e;\n Gzz[i] = cos_caz*gzz_n + sin_caz*gzz_e;\n Gxy[i] = cos_caz*gxy_n + sin_caz*gxy_e;\n Gxz[i] = cos_caz*gxz_n + sin_caz*gxz_e;\n Gyz[i] = cos_caz*gyz_n + sin_caz*gyz_e;\n\n } // Loop on points\n }\n // East or 3 component\n else\n {\n // Loop on rows (data points) \n #pragma omp simd\n for (i=0; i (n, e)\n // n = cos(baz-180)*r - sin(baz-180)*t\n // =-cos(baz)*r + sin(baz)*t\n // e = sin(baz-180)*r + cos(baz-180)*t\n // =-sin(baz)*r - cos(baz)*t\n gxx_n =-cost*gxx_r + sint*gxx_t;\n gxx_e =-sint*gxx_r - cost*gxx_t;\n gyy_n =-cost*gyy_r + sint*gyy_t;\n gyy_e =-sint*gyy_r - cost*gyy_t;\n gzz_n =-cost*gzz_r + sint*gzz_t;\n gzz_e =-sint*gzz_r - cost*gzz_t;\n gxy_n =-cost*gxy_r + sint*gxy_t;\n gxy_e =-sint*gxy_r - cost*gxy_t;\n gxz_n =-cost*gxz_r + sint*gxz_t;\n gxz_e =-sint*gxz_r - cost*gxz_t;\n gyz_n =-cost*gyz_r + sint*gyz_t;\n gyz_e =-sint*gyz_r - cost*gyz_t;\n // Rotate from (n, e) -> (1, 2) around az\n // 2 =-sin(comp_az)*n + cos(comp_az)*e\n Gxx[i] =-sin_caz*gxx_n + cos_caz*gxx_e;\n Gyy[i] =-sin_caz*gyy_n + cos_caz*gyy_e;\n Gzz[i] =-sin_caz*gzz_n + cos_caz*gzz_e;\n Gxy[i] =-sin_caz*gxy_n + cos_caz*gxy_e;\n Gxz[i] =-sin_caz*gxz_n + cos_caz*gxz_e;\n Gyz[i] =-sin_caz*gyz_n + cos_caz*gyz_e;\n } // Loop on points\n } // End check on 1 or 2 component\n } // End check on component\n return 0;\n}\n", "meta": {"hexsha": "e7943f724e6e5dcc1a84d6e9b6a5fd37ef8dd60f", "size": 16682, "ext": "c", "lang": "C", "max_stars_repo_path": "utils/ff2mtGreens.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/ff2mtGreens.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/ff2mtGreens.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4478371501, "max_line_length": 80, "alphanum_fraction": 0.4882508093, "num_tokens": 4838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924953, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4242684587916098}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n// Code to calculate the covariance matrix for fitting the peculiar velocities of the 2MTF simulations.\r\n// Generates a grid covering -120= -1.0) && (costheta <= 1.0)) {\r\n\t\t\t\ttheta = acos(costheta);\r\n\t\t\t\tdx = ri*rj/(ri+rj)*(xi/ri + xj/rj);\r\n\t dy = ri*rj/(ri+rj)*(yi/ri + yj/rj);\r\n\t dz = ri*rj/(ri+rj)*(zi/ri + zj/rj);\r\n\t dl = sqrt(dx*dx+dy*dy+dz*dz);\r\n\t\t\t\tphi_arg = (dx*(xi-xj) + dy*(yi-yj) + dz*(zi-zj))/(dl*s);\r\n\t\t\t\tif ((phi_arg >=-1.0) && (phi_arg <= 1.0)) {\r\n\t\t\t\t\tphi = acos(phi_arg);\r\n\t\t\t\t}\r\n\t\t\t\telse if (phi_arg > 1.0) {\r\n\t\t\t\t\tphi = 0.0;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tphi = M_PI;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if (costheta > 1.0) {\r\n\t\t\t\ttheta = 0.0;\r\n\t\t\t\tdx = ri*rj/(ri+rj)*(xi/ri + xj/rj);\r\n\t dy = ri*rj/(ri+rj)*(yi/ri + yj/rj);\r\n\t dz = ri*rj/(ri+rj)*(zi/ri + zj/rj);\r\n\t dl = sqrt(dx*dx+dy*dy+dz*dz);\r\n\t\t\t\tphi_arg = (dx*(xi-xj) + dy*(yi-yj) + dz*(zi-zj))/(dl*s);\r\n\t\t\t\tif ((phi_arg >=-1.0) && (phi_arg <= 1.0)) {\r\n\t\t\t\t\tphi = acos(phi_arg);\r\n\t\t\t\t}\r\n\t\t\t\telse if (phi_arg > 1.0) {\r\n\t\t\t\t\tphi = 0.0;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tphi = M_PI;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\ttheta = M_PI;\r\n\t\t\t\tdx = ri*rj/(ri+rj)*(xi/ri + xj/rj);\r\n\t dy = ri*rj/(ri+rj)*(yi/ri + yj/rj);\r\n\t dz = ri*rj/(ri+rj)*(zi/ri + zj/rj);\r\n\t dl = sqrt(dx*dx+dy*dy+dz*dz);\r\n\t\t\t\tphi_arg = (dx*(xi-xj) + dy*(yi-yj) + dz*(zi-zj))/(dl*s);\r\n\t\t\t\tif ((phi_arg >=-1.0) && (phi_arg <= 1.0)) {\r\n\t\t\t\t\tphi = acos(phi_arg);\r\n\t\t\t\t}\r\n\t\t\t\telse if (phi_arg > 1.0) {\r\n\t\t\t\t\tphi = 0.0;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tphi = M_PI;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n /*double theta = acos((xi*xj + yi*yj + zi*zj)/(ri*rj));\r\n double phi;\r\n if (indi + indj == nelements-1) {\r\n \tphi = M_PI/2.0;\r\n } else {\r\n\t double dx = ri*rj/(ri+rj)*(xi/ri + xj/rj);\r\n\t double dy = ri*rj/(ri+rj)*(yi/ri + yj/rj);\r\n\t double dz = ri*rj/(ri+rj)*(zi/ri + zj/rj);\r\n\t double dl = sqrt(dx*dx+dy*dy+dz*dz);\r\n\t\t\t \tdouble phi = acos((dx*(xi-xj) + dy*(yi-yj) + dz*(zi-zj))/(dl*s));\r\n\t\t\t}*/\r\n\t\t\tdouble 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;\r\n\t\t\tfor (ell=16; ell>=0; ell-=2) {\r\n\t\t\t\tcov_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);\r\n\t\t\t\t\r\n\t\t\t\tif (ell < 15) {\r\n\t\t\t\t\tcov_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));\r\n\t\t\t\t\t}\r\n\t\t\t\tif (ell < 13) {\r\n\t\t\t\t\tcov_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);\r\n\t\t\t\t\t}\r\n\t\t\t\tif (ell < 11) {\r\n\t\t\t\t\tcov_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);\r\n\t\t\t\t\t}\r\n\t\t\t\tif (ell < 9) {\r\n\t\t\t\t\tcov_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);\r\n\t\t\t\t\t}\r\n\t\t\t\tif (ell < 7) {\r\n\t\t\t\t\tcov_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));\r\n\t\t\t\t\t}\r\n\t\t\t\tif (ell < 5) {\r\n\t\t\t\t\tcov_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);\r\n\t\t\t\t\t}\r\n\t\t\t}\r\n conv_pk_gal_0_12[indi][indj] = cov_0_12/(2.0*M_PI*M_PI)/2304.0;\r\n conv_pk_gal_0_10[indi][indj] = -cov_0_10/(2.0*M_PI*M_PI)/384.0;\r\n conv_pk_gal_0_8[indi][indj] = cov_0_8/(2.0*M_PI*M_PI)/16.0;\r\n conv_pk_gal_0_6[indi][indj] = -cov_0_6/(2.0*M_PI*M_PI)/8.0;\r\n conv_pk_gal_0_4[indi][indj] = cov_0_4/(2.0*M_PI*M_PI)/4.0;\r\n conv_pk_gal_0_2[indi][indj] = -cov_0_2/(2.0*M_PI*M_PI)/2.0;\r\n conv_pk_gal_0_0[indi][indj] = cov_0_0/(2.0*M_PI*M_PI);\r\n conv_pk_gal_0_12[indj][indi] = cov_0_12/(2.0*M_PI*M_PI)/2304.0;\r\n conv_pk_gal_0_10[indj][indi] = -cov_0_10/(2.0*M_PI*M_PI)/384.0;\r\n conv_pk_gal_0_8[indj][indi] = cov_0_8/(2.0*M_PI*M_PI)/16.0;\r\n conv_pk_gal_0_6[indj][indi] = -cov_0_6/(2.0*M_PI*M_PI)/8.0;\r\n conv_pk_gal_0_4[indj][indi] = cov_0_4/(2.0*M_PI*M_PI)/4.0;\r\n conv_pk_gal_0_2[indj][indi] = -cov_0_2/(2.0*M_PI*M_PI)/2.0;\r\n conv_pk_gal_0_0[indj][indi] = cov_0_0/(2.0*M_PI*M_PI);\r\n //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]);\r\n }\r\n }\r\n\r\n\tsprintf(covfile, \"%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_0.dat\", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize);\r\n write_cov(covfile, nelements, conv_pk_gal_0_0, 8);\r\n\tsprintf(covfile, \"%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_2.dat\", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize);\r\n write_cov(covfile, nelements, conv_pk_gal_0_2, 10);\r\n\tsprintf(covfile, \"%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_4.dat\", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize);\r\n write_cov(covfile, nelements, conv_pk_gal_0_4, 12);\r\n\tsprintf(covfile, \"%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_6.dat\", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize);\r\n write_cov(covfile, nelements, conv_pk_gal_0_6, 14);\r\n \tsprintf(covfile, \"%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_8.dat\", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize);\r\n write_cov(covfile, nelements, conv_pk_gal_0_8, 16);\r\n \tsprintf(covfile, \"%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_10.dat\", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize);\r\n write_cov(covfile, nelements, conv_pk_gal_0_10, 18);\r\n \tsprintf(covfile, \"%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_12.dat\", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize);\r\n write_cov(covfile, nelements, conv_pk_gal_0_12, 20);\r\n\tsprintf(covfile, \"%s_k0p%03d_0p%03d_gridcorr%02d_dd_1_0.dat\", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize);\r\n\r\n\tprintf(\"Done dd covariance\\n\");\r\n\r\n for (i=0; i\n#include \n#include \n\n/* This is an implementation of the algorithm used in Knuths's\n subtractive generator, with the Numerical Recipe's ran3 paramters.\n It is a subtractive lagged fibonnaci generator. */\n\nstatic inline unsigned long int ran3_get (void *vstate);\nstatic double ran3_get_double (void *vstate);\nstatic void ran3_set (void *state, unsigned long int s);\n\n#define M_BIG 1000000000\n#define M_SEED 161803398\n\ntypedef struct\n {\n unsigned int x;\n unsigned int y;\n unsigned long int buffer[56];\n }\nran3_state_t;\n\nstatic inline unsigned long int\nran3_get (void *vstate)\n{\n ran3_state_t *state = (ran3_state_t *) vstate;\n long int j;\n\n state->x++;\n\n if (state->x == 56)\n state->x = 1;\n\n state->y++;\n\n if (state->y == 56)\n state->y = 1;\n\n j = state->buffer[state->x] - state->buffer[state->y];\n\n if (j < 0)\n j += M_BIG;\n\n state->buffer[state->x] = j;\n\n return j;\n}\n\nstatic double\nran3_get_double (void *vstate)\n{\n return ran3_get (vstate) / (double) M_BIG ;\n}\n\nstatic void\nran3_set (void *vstate, unsigned long int s)\n{\n ran3_state_t *state = (ran3_state_t *) vstate;\n int i, i1;\n long int j, k;\n\n if (s == 0)\n s = 1; /* default seed is 1 */\n\n j = (M_SEED - s) % M_BIG;\n\n /* Avoid potential problem with negative values */\n if (j < 0) j += M_BIG;\n\n /* the zeroth element is never used, but we initialize it for\n consistency between states */\n\n state->buffer[0] = 0; \n\n state->buffer[55] = j;\n\n k = 1;\n for (i = 1; i < 55; i++)\n {\n int n = (21 * i) % 55;\n state->buffer[n] = k;\n k = j - k;\n if (k < 0)\n k += M_BIG;\n j = state->buffer[n];\n\n }\n\n for (i1 = 0; i1 < 4; i1++)\n {\n for (i = 1; i < 56; i++)\n {\n long int t = state->buffer[i] - state->buffer[1 + (i + 30) % 55];\n if (t < 0)\n t += M_BIG;\n state->buffer[i] = t;\n }\n }\n\n state->x = 0;\n state->y = 31;\n\n return;\n}\n\nstatic const gsl_rng_type ran3_type =\n{\"ran3\", /* name */\n M_BIG, /* RAND_MAX */\n 0, /* RAND_MIN */\n sizeof (ran3_state_t),\n &ran3_set,\n &ran3_get,\n &ran3_get_double};\n\nconst gsl_rng_type *gsl_rng_ran3 = &ran3_type;\n", "meta": {"hexsha": "d855d2547ac4a9c659fb8ffeb56dc7b4631aaca5", "size": 3102, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/rng/ran3.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/ran3.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/ran3.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 22.8088235294, "max_line_length": 84, "alphanum_fraction": 0.6112185687, "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.42400790710654584}} {"text": "/******************************************\\\n* OpenMP/SSE/BLAS Optimized Matrix Library *\n* *\n* by *\n* Elliott Forney *\n* 3.9.2010 *\n\\******************************************/\n\n/*\n * Libraries\n */\n\n#include \n#include \n#include \n#include \n\n// cblas\n#include \n\n// OpenMP\n#include \n\n// SSE 4.1 intrinsics\n#include \n\n// SSE 2 intrinsics\n// #include \n\n//\n#include \"errcheck.h\"\n#include \"matrix.h\"\n\n/*\n * Macros\n */\n\n//** Debugging level\n#define DEBUG 0\n\n//** Initialization\n\n// max number of chars per line in input table\n#define line_buff_size 1024\n\n//** Access\n\n// row major indexing\n// expects stride and data to be set\n#define data_at(r,c) data[r*stride+c]\n\n//** Addition/Subtraction\n\n// when number of values in matrix is\n// larger than add_lim use big kernel\n#define add_lim 10000\n\n//** Transpose\n\n#define trans_lim 22500\n\n//#define trans_tile 64\n\n/*\n * Global variables\n */\n\nunsigned rand_state = 8;\n\n/*\n * Function prototypes\n */\n\n//\nvoid build_drc(matrix *m);\n\n// sigmoid function\nfloat phi(const float v);\n\n// derivative of sigmoid function given phi(v)\nfloat phi_prime(const float z);\n\n// addition kernel for small matrices\nvoid add_small(float *a, float *b, float *c, const unsigned n);\n\n// addition kernel for big matrices\nvoid add_big(float *m, float *b, float *c, const unsigned n);\n\n// subtraction kernel for small matrices\nvoid sub_small(float *a, float *b, float *c, const unsigned n);\n\n// subtraction kernel for big matrices\nvoid sub_big(float *a, float *b, float *c, const unsigned n);\n\n// pointwise square kernel for small matrices\nvoid sqr_small(float *a, float *b, const unsigned n);\n\n// pointwise square kernel for big matrices\nvoid sqr_big(float *a, float *b, const unsigned n);\n\n// scalar multiply kernel for small matrices\nvoid scl_small(float *a, float b, float *c, const unsigned n);\n\n// scalar multiply kernel for big matrices\nvoid scl_big(float *a, float b, float *c, const unsigned n);\n\n// scalar multiplication & pointwise addition kernel for small matrices\nvoid scl_add_small(float *a, float b, float *c, float *d, const unsigned n);\n\n// scalar multiplication & pointwise addition kernel for big matrices\nvoid scl_add_big(float *a, float b, float *c, float *d, const unsigned n);\n\n// pointwise multiplication for small matrices\nvoid pmult_small(float *a, float *b, float *c, const unsigned n);\n\n// pointwise multiplication for big matrices\nvoid pmult_big(float *a, float *b, float *c, const unsigned n);\n\n/*\n * Function bodies\n */\n\n// build row-col indices for double index\nvoid build_drc(matrix *m)\n{\n // not done/needed yet\n}\n\n// sigmoid function\nfloat phi(const float v)\n{\n // recommended by Lecun, find citation!!\n const float scl = 2.0f/3.0f;\n return 1.7159f * tanh( scl * v );\n}\n\n// derivative of sigmoid function given phi(v)\nfloat phi_prime(const float z)\n{\n const float scl = 2.0f/3.0f;\n return scl * (1.7159f - z*z);\n}\n\n// addition kernel for small matrices\nvoid add_small(float *a, float *b, float *c, const unsigned n)\n{\n // pointer to last destination\n const float *a_end = a+n;\n\n // loop through each value in destination\n while (a < a_end)\n {\n // four values from b and c into sse registers\n __m128 mm_v1 = _mm_load_ps(b);\n __m128 mm_v2 = _mm_load_ps(c);\n\n // add our sse vectors\n mm_v1 = _mm_add_ps(mm_v1, mm_v2);\n\n // store result into a\n _mm_store_ps(a, mm_v1);\n\n // increment pointers by 4\n a += 4; b += 4; c += 4;\n }\n}\n\n// addition kernel for big matrices\nvoid add_big(float *a, float *b, float *c, const unsigned n)\n{\n unsigned i;\n\n // loop through a, b and c by 4 in parallel\n #pragma omp parallel for\n for (i = 0; i < n; i += 4)\n {\n // load four values into sse registers\n __m128 mm_v1 = _mm_load_ps(b+i); // what if they have different strides!!! :(\n __m128 mm_v2 = _mm_load_ps(c+i);\n\n // add our sse vectors\n mm_v1 = _mm_add_ps(mm_v1, mm_v2);\n\n // store result into a\n _mm_store_ps(a+i, mm_v1);\n }\n}\n\n// subtraction kernel for small matrices\nvoid sub_small(float *a, float *b, float *c, const unsigned n)\n{\n const float *a_end = a+n;\n\n while (a < a_end)\n {\n __m128 mm_v1 = _mm_load_ps(b);\n __m128 mm_v2 = _mm_load_ps(c);\n\n mm_v1 = _mm_sub_ps(mm_v1, mm_v2);\n\n _mm_store_ps(a, mm_v1);\n\n a += 4; b += 4; c += 4;\n }\n}\n\n// subtraction kernel for big matrices\nvoid sub_big(float *a, float *b, float *c, const unsigned n)\n{\n unsigned i;\n\n #pragma omp parallel for\n for (i = 0; i < n; i += 4)\n {\n __m128 mm_v1 = _mm_load_ps(b+i);\n __m128 mm_v2 = _mm_load_ps(c+i);\n\n mm_v1 = _mm_sub_ps(mm_v1, mm_v2);\n\n _mm_store_ps(a+i, mm_v1);\n }\n}\n\n// pointwise square kernel for small matrices\nvoid sqr_small(float *a, float *b, const unsigned n)\n{\n const float *a_end = a+n;\n\n while (a < a_end)\n {\n __m128 mm_v = _mm_load_ps(b);\n\n mm_v = _mm_mul_ps(mm_v, mm_v);\n\n _mm_store_ps(a, mm_v);\n\n a += 4; b += 4;\n }\n}\n\n// pointwise square kernel for big matrices\nvoid sqr_big(float *a, float *b, const unsigned n)\n{\n unsigned i;\n\n #pragma omp parallel for\n for (i = 0; i < n; i += 4)\n {\n __m128 mm_v = _mm_load_ps(b+i);\n\n mm_v = _mm_mul_ps(mm_v, mm_v);\n\n _mm_store_ps(a+i, mm_v);\n }\n}\n\n// scalar multiplication kernel for small matrices\nvoid scl_small(float *a, float b, float *c, const unsigned n)\n{\n const float *a_end = a+n;\n\n __m128 mm_s = _mm_set1_ps(b);\n\n while (a < a_end)\n {\n __m128 mm_v = _mm_load_ps(c);\n\n mm_v = _mm_mul_ps(mm_s, mm_v);\n\n _mm_store_ps(a, mm_v);\n\n a += 4; c += 4;\n }\n}\n\n// scalar multiplication kernel for big matrices\nvoid scl_big(float *a, float b, float *c, const unsigned n)\n{\n unsigned i;\n\n const __m128 mm_s = _mm_set1_ps(b);\n\n #pragma omp parallel for\n for (i = 0; i < n; i += 4)\n {\n __m128 mm_v = _mm_load_ps(c+i);\n\n mm_v = _mm_mul_ps(mm_s, mm_v);\n\n _mm_store_ps(a+i, mm_v);\n }\n}\n\n// scalar multiplication & pointwise addition kernel for small matrices\nvoid scl_add_small(float *a, float b, float *c, float *d, unsigned n)\n{\n const float *a_end = a+n;\n\n __m128 mm_s = _mm_set1_ps(b);\n\n while (a < a_end)\n {\n __m128 mm_v1 = _mm_load_ps(c);\n __m128 mm_v2 = _mm_load_ps(d);\n\n mm_v1 = _mm_mul_ps(mm_s, mm_v1);\n mm_v1 = _mm_add_ps(mm_v1, mm_v2);\n\n _mm_store_ps(a, mm_v1);\n\n a += 4; c += 4; d += 4;\n }\n}\n\n// scalar multiplication & pointwise addition kernel for big matrices\nvoid scl_add_big(float *a, float b, float *c, float *d, unsigned n)\n{\n unsigned i;\n\n const __m128 mm_s = _mm_set1_ps(b);\n\n #pragma omp parallel for\n for (i = 0; i < n; i += 4)\n {\n __m128 mm_v1 = _mm_load_ps(c+i);\n __m128 mm_v2 = _mm_load_ps(d+i);\n\n mm_v1 = _mm_mul_ps(mm_s, mm_v1);\n mm_v1 = _mm_add_ps(mm_v1, mm_v2);\n\n _mm_store_ps(a+i, mm_v1);\n }\n}\n\n\n// pointwise multiplication kernel for small matrices\nvoid pmult_small(float *a, float *b, float *c, const unsigned n)\n{\n // pointer to last destination\n const float *a_end = a+n;\n\n // loop through each value in destination\n while (a < a_end)\n {\n // four values from b and c into sse registers\n __m128 mm_v1 = _mm_load_ps(b);\n __m128 mm_v2 = _mm_load_ps(c);\n\n // mult our sse vectors\n mm_v1 = _mm_mul_ps(mm_v1, mm_v2);\n\n // store result into a\n _mm_store_ps(a, mm_v1);\n\n // increment pointers by 4\n a += 4; b += 4; c += 4;\n }\n}\n\n// pointwise multiplication kernel for big matrices\nvoid pmult_big(float *a, float *b, float *c, const unsigned n)\n{\n unsigned i;\n\n // loop through a, b and c by 4 in parallel\n #pragma omp parallel for\n for (i = 0; i < n; i += 4)\n {\n // load four values into sse registers\n __m128 mm_v1 = _mm_load_ps(b+i);\n __m128 mm_v2 = _mm_load_ps(c+i);\n\n // mult our sse vectors\n mm_v1 = _mm_mul_ps(mm_v1, mm_v2);\n\n // store result into a\n _mm_store_ps(a+i, mm_v1);\n }\n}\n\n/*\n * External function bodies\n */\n\n//** Initialization & Destruction\n\n// initialize matrix m of size r by c\nvoid matrix_init(matrix *m, const unsigned r, const unsigned c)\n{\n // set matrix dimensions\n m->r = r;\n m->c = c;\n\n // zero pad to nearest mult of 64, lcm 4 for sse, 64 for trans\n // leave one extra row/col to append bias terms\n// m->rstride = r + (64 - (r % 64)); // lcm(trans_tile, 4)\n// m->cstride = c + (64 - (c % 64));\n\n // 64 tiles speeds up transpose but hurts everything else\n m->rstride = r + (4 - (r % 4));\n m->cstride = c + (4 - (c % 4));\n\n // allocate space for matrix, 16 byte aligned\n m->cpu_data = (float*)_mm_malloc((m->rstride)*(m->cstride)*\n sizeof(float), 16);\n if (m->cpu_data == NULL)\n errcheck_cpu();\n\n // allocate space for last column holder\n m->cv = (float*)malloc((m->r)*sizeof(float));\n if (m->cv == NULL)\n errcheck_cpu();\n\n // zero out data for padding\n memset(m->cpu_data, '\\0', (m->rstride)*(m->cstride)*sizeof(float));\n memset(m->cv, '\\0', (m->r)*sizeof(float));\n\n // build row-col indices\n build_drc(m);\n}\n\n// initialize matrix m from ascii table\nvoid matrix_init_file(matrix *m, char *file_name)\n{\n // will need to do this dynamically if\n // we ever want to handle big tables!!!\n float table_data[line_buff_size][line_buff_size];\n unsigned r = 0, c = 0;\n\n // open file & setup input buffer\n FILE *table = fopen(file_name, \"r\");\n char line_buffer[line_buff_size];\n\n // check if we were even able to open table file\n if (file_name == NULL)\n errcheck_cpu();\n\n // buckle-up, don't drink and code\n memset(table_data, '\\0', line_buff_size*line_buff_size*sizeof(float));\n\n // for each line in table (row)\n while (fgets(line_buffer, line_buff_size, table))\n {\n if (DEBUG > 5)\n printf(\"line buffer: %s\\n\", line_buffer);\n\n // set up string tokenizer on input buffer\n char *cur_val = strtok(line_buffer, \" \"); // Note reentrant or thread safe!!\n\n // don't increment num rows on blank line\n if (cur_val != NULL)\n {\n c = 0; // new row, reset col counter\n\n // for each token (col)\n while (cur_val != NULL)\n {\n // convert from char to float\n table_data[r][c] = atof(cur_val);\n\n if (DEBUG > 5)\n printf(\"converting %d %d %f\\n\", r, c, table_data[r][c]);\n\n // get next token\n cur_val = strtok(NULL, \" \");\n ++c; // increment num cols\n }\n ++r; // increment num rows\n }\n }\n\n // close file descriptor\n fclose(table);\n\n // initialize m\n matrix_init(m, r, c);\n\n // setup for data_at\n unsigned mr, mc;\n float *data = m->cpu_data;\n const unsigned stride = m->cstride;\n\n // loop through collected data and put into m\n for (mr = 0; mr < r; ++mr)\n for (mc = 0; mc < c; ++mc)\n data_at(mr,mc) = table_data[mr][mc];\n}\n\n// load zeros into matrix m\nvoid matrix_load_zero(matrix m)\n{\n float *data = m.cpu_data;\n const float *data_end = data + (m.rstride*m.cstride);\n\n // loop through all values and set to zero\n // memset?\n while (data < data_end)\n *(data++) = 0.0f;\n}\n\n// load values from an array\nvoid matrix_load_array(matrix m, float *v)\n{\n unsigned r, c, i = 0;\n\n // set data and stride for data_at\n float *data = m.cpu_data;\n const unsigned stride = m.cstride;\n\n for (r = 0; r < m.r; ++r)\n for (c = 0; c < m.c; ++c)\n data_at(r,c) = v[i++];\n}\n\n// load values from the random uniform distribution\nvoid matrix_load_runif(matrix m, float min, float max)\n{\n unsigned r, c;\n\n // set data and stride for data_at\n float *data = m.cpu_data;\n const unsigned stride = m.cstride;\n\n const float range = max - min;\n\n // needs work to be multithreaded!\n\n // set each non-padding value from random uniform\n for (r = 0; r < m.r; ++r)\n for (c = 0; c < m.c; ++c)\n data_at(r,c) = rand_r(&rand_state) * range / RAND_MAX + min;\n}\n\nvoid matrix_load_testa(matrix m, unsigned n)\n{\n unsigned r, c;\n\n // set data and stride for data_at\n float *data = m.cpu_data;\n const unsigned stride = m.cstride;\n\n #pragma omp parallel for private(c)\n for (r = 0; r < m.r; ++r)\n for (c = 0; c < m.c; ++c)\n //data_at(r,c) = (float)n * (float)r*c;\n data_at(r,c) = (float)n;\n}\n\nvoid matrix_load_testb(matrix m)\n{\n unsigned r, c;\n\n // set data and stride for data_at\n float *data = m.cpu_data;\n const unsigned stride = m.cstride;\n\n #pragma omp parallel for private(c)\n for (r = 0; r < m.r; ++r)\n for (c = 0; c < m.c; ++c)\n //data_at(r,c) = (float)r;\n data_at(r,c) = 1.0f;\n}\n\nvoid matrix_load_testc(matrix m)\n{\n unsigned r, c;\n\n // set data and stride for data_at\n float *data = m.cpu_data;\n const unsigned stride = m.cstride;\n\n #pragma omp parallel for private(c)\n for (r = 0; r < m.r; ++r)\n for (c = 0; c < m.c; ++c)\n //data_at(r,c) = (float)c;\n data_at(r,c) = 1.0f;\n}\n\n// copy values to an array\nvoid matrix_unload_array(matrix m, float *v)\n{\n unsigned r, c, i = 0;\n\n float *data = m.cpu_data;\n const unsigned stride = m.cstride;\n\n for (r = 0; r < m.r; ++r)\n for (c = 0; c < m.c; ++c)\n v[i++] = data_at(r,c);\n}\n\n// write values to a file\nvoid matrix_unload_file(matrix m, char *file_name)\n{\n unsigned r, c;\n \n float *data = m.cpu_data;\n const unsigned stride = m.cstride;\n \n // open file for writing\n FILE *table = fopen(file_name, \"w\");\n\n // check if we were even able to open table file\n if (file_name == NULL)\n errcheck_cpu();\n\n for (r = 0; r < m.r; ++r)\n {\n for (c = 0; c < m.c-1; ++c)\n fprintf(table, \"%.16f \", data_at(r,c));\n fprintf(table, \"%.16f\\n\", data_at(r,c));\n }\n\n fclose(table);\n}\n\n// destroy matrix m\nvoid matrix_dest(matrix *m)\n{\n // free matrix data\n free(m->cpu_data);\n free(m->cv);\n\n // free row/col indices\n //free(m->drc);\n\n // set everything to zero for safety\n m->r = 0;\n m->c = 0;\n m->rstride = 0;\n m->cstride = 0;\n m->cpu_data = NULL;\n}\n\n//** Synchronization\n\n// wait for asynchronous calls to finish\nvoid matrix_wait()\n{\n // nada\n}\n\n//** Addition/Subtraction\n\n// a = b + c\nvoid matrix_add(matrix a, matrix b, matrix c)\n{\n #ifndef NO_ERRCHECK\n if ( (a.r != b.r) || (b.r != c.r) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Rows don't match for addition!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n\n if ( (a.c != b.c) || (b.c != c.c) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Cols don't match for addition!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n #endif\n\n const unsigned n = a.r * a.cstride;\n\n/* naive\n unsigned i;\n float *aval = a.cpu_data;\n float *bval = b.cpu_data;\n float *cval = c.cpu_data;\n for (i = 0; i < n; ++i)\n aval[i] = bval[i] + cval[i]; */\n\n if (n < add_lim)\n add_small(a.cpu_data, b.cpu_data, c.cpu_data, n);\n else\n add_big(a.cpu_data, b.cpu_data, c.cpu_data, n);\n}\n\n// a = b - c\nvoid matrix_sub(matrix a, matrix b, matrix c)\n{\n #ifndef NO_ERRCHECK\n if ( (a.r != b.r) || (b.r != c.r) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Rows don't match for subtraction!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n\n if ( (a.c != b.c) || (b.c != c.c) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Cols don't match for subtraction!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n #endif\n\n const unsigned n = a.r * a.cstride;\n\n if (n < add_lim)\n sub_small(a.cpu_data, b.cpu_data, c.cpu_data, n);\n else\n sub_big(a.cpu_data, b.cpu_data, c.cpu_data, n);\n}\n\n//** Multiplication\n\n// a = b * c\nvoid matrix_mult(matrix a, matrix b, matrix c)\n{\n #ifndef NO_ERRCHECK\n if ( (b.c != c.r) || (a.r != b.r) || (a.c != c.c) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Dimensions don't match for multiplication!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n #endif\n\n // use cblas for multiplication, not going to beat this.. for now ;)\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n b.r, c.c, b.c, 1.0f,\n b.cpu_data, b.cstride, c.cpu_data, c.cstride,\n 0.0f, a.cpu_data, a.cstride);\n}\n\n// a = phi(b * c)\nvoid matrix_mult_phi(matrix a, matrix b, matrix c)\n{\n #ifndef NO_ERRCHECK\n if ( (b.c != c.r) || (a.r != b.r) || (a.c != c.c) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Dimensions don't match for mult_phi!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n #endif\n\n // use cblas for multiplication, not going to beat this.. for now ;)\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n b.r, c.c, b.c, 1.0f,\n b.cpu_data, b.cstride, c.cpu_data, c.cstride,\n 0.0f, a.cpu_data, a.cstride);\n\n // apply phi\n\n unsigned row, col;\n\n float *adata = a.cpu_data;\n const unsigned astride = a.cstride;\n\n // need to optimize small kern and put into functions\n if ((a.r*a.cstride) < add_lim)\n {\n const __m128 mm_s1 = _mm_set1_ps(1.7159f);\n const __m128 mm_s2 = _mm_set1_ps(2.0f/3.0f);\n for (row = 0; row < a.r; ++row)\n for (col = 0; col < a.c; col += 4)\n {\n unsigned i;\n const unsigned base = row*astride+col;\n\n // inside scalar mult\n __m128 mm_v = _mm_load_ps(adata+base);\n mm_v = _mm_mul_ps(mm_v, mm_s2);\n _mm_store_ps(adata+base, mm_v);\n\n // apply tanh\n for (i = base; i < base+4; ++i)\n adata[i] = tanh(adata[i]);\n\n // outside scalar mult\n mm_v = _mm_load_ps(adata+base);\n mm_v = _mm_mul_ps(mm_v, mm_s1);\n _mm_store_ps(adata+base, mm_v);\n }\n }\n else\n {\n const __m128 mm_s1 = _mm_set1_ps(1.7159f);\n const __m128 mm_s2 = _mm_set1_ps(2.0f/3.0f);\n #pragma omp parallel for private(col)\n for (row = 0; row < a.r; ++row)\n for (col = 0; col < a.c; col += 4)\n {\n unsigned i;\n const unsigned base = row*astride+col;\n\n // inside scalar mult\n __m128 mm_v = _mm_load_ps(adata+base);\n mm_v = _mm_mul_ps(mm_v, mm_s2);\n _mm_store_ps(adata+base, mm_v);\n\n // apply tanh\n for (i = base; i < base+4; ++i)\n adata[i] = tanh(adata[i]);\n\n // outside scalar mult\n mm_v = _mm_load_ps(adata+base);\n mm_v = _mm_mul_ps(mm_v, mm_s1);\n _mm_store_ps(adata+base, mm_v);\n }\n }\n\n/*\n unsigned i;\n #pragma omp parallel for\n for (i = 0; i < a.r*a.cstride; ++i)\n adata[i] = phi(adata[i]);\n*/\n}\n\n//** Transpose\n\n// a = b^T\nvoid matrix_trans(matrix a, matrix b)\n{\n #ifndef NO_ERRCHECK\n if ( (a.r != b.c) || (a.c != b.r) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Source and destination dimensions don't match for transpose!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n #endif\n\n unsigned r, c;\n\n float *adata = a.cpu_data;\n float *bdata = b.cpu_data;\n\n const unsigned astride = a.cstride;\n const unsigned bstride = b.cstride;\n\n // need to seperate into smaller functions\n if ((a.r*a.c) < trans_lim)\n {\n for (r = 0; r < a.r; r += 4)\n for (c = 0; c < a.c; c += 4)\n {\n // load 4x4 tile\n float *base = bdata + c*bstride+r;\n __m128 mm_v1 = _mm_load_ps(base );\n __m128 mm_v2 = _mm_load_ps(base + bstride);\n __m128 mm_v3 = _mm_load_ps(base + 2*bstride);\n __m128 mm_v4 = _mm_load_ps(base + 3*bstride);\n\n // transpose 4x4 tile\n _MM_TRANSPOSE4_PS(mm_v1, mm_v2, mm_v3, mm_v4);\n\n // store 4x4 tile back into a\n base = adata + r*astride+c;\n _mm_store_ps(base, mm_v1);\n _mm_store_ps(base + astride, mm_v2);\n _mm_store_ps(base + 2*astride, mm_v3);\n _mm_store_ps(base + 3*astride, mm_v4);\n }\n }\n else\n {\n #pragma omp parallel for private(c)\n for (r = 0; r < a.r; r += 4)\n for (c = 0; c < a.c; c += 4)\n {\n // load 4x4 tile\n float *base = bdata + c*bstride+r;\n __m128 mm_v1 = _mm_load_ps(base );\n __m128 mm_v2 = _mm_load_ps(base + bstride);\n __m128 mm_v3 = _mm_load_ps(base + 2*bstride);\n __m128 mm_v4 = _mm_load_ps(base + 3*bstride);\n\n // transpose 4x4 tile\n _MM_TRANSPOSE4_PS(mm_v1, mm_v2, mm_v3, mm_v4);\n\n // store 4x4 tile back into a\n base = adata + r*astride+c;\n _mm_store_ps(base, mm_v1);\n _mm_store_ps(base + astride, mm_v2);\n _mm_store_ps(base + 2*astride, mm_v3);\n _mm_store_ps(base + 3*astride, mm_v4);\n }\n }\n\n /* tiled version, fast but big tiles hurt everything else\n #pragma omp parallel for private(tc,r,c)\n for (tr = 0; tr < a.r; tr += trans_tile)\n for (tc = 0; tc < a.c; tc += trans_tile)\n for (r = tr; r < tr+trans_tile; r += 4)\n for (c = tc; c < tc+trans_tile; c += 4)\n {\n // load 4x4 tile\n float *base = bdata + c*bstride+r;\n __m128 mm_v1 = _mm_load_ps(base );\n __m128 mm_v2 = _mm_load_ps(base + bstride);\n __m128 mm_v3 = _mm_load_ps(base + 2*bstride);\n __m128 mm_v4 = _mm_load_ps(base + 3*bstride);\n\n // transpose 4x4 tile\n _MM_TRANSPOSE4_PS(mm_v1, mm_v2, mm_v3, mm_v4);\n\n // store 4x4 tile back into a\n base = adata + r*astride+c;\n _mm_store_ps(base, mm_v1);\n _mm_store_ps(base + astride, mm_v2);\n _mm_store_ps(base + 2*astride, mm_v3);\n _mm_store_ps(base + 3*astride, mm_v4);\n } */\n}\n\n//** Pointwise miscellaneous\n\n// a = b^2\nvoid matrix_sqr(matrix a, matrix b)\n{\n #ifndef NO_ERRCHECK\n if ( (a.r != b.r) || (a.c != b.c) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Source and destination dimensions don't match for square!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n #endif\n\n const unsigned n = a.r * a.cstride;\n\n if (n < add_lim)\n sqr_small(a.cpu_data, b.cpu_data, n);\n else\n sqr_big(a.cpu_data, b.cpu_data, n);\n}\n\n// scalar multiplication a = b*c\nvoid matrix_scl(matrix a, float b, matrix c)\n{\n #ifndef NO_ERRCHECK\n if ( (a.r != c.r) || (a.c != c.c) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Source and destination dimensions don't match for scale!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n #endif\n\n const unsigned n = a.r * a.cstride;\n\n if (n < add_lim)\n scl_small(a.cpu_data, b, c.cpu_data, n);\n else\n scl_big(a.cpu_data, b, c.cpu_data, n);\n}\n\n// scalar multiplication & pointwise addition a = b.*c+d\nvoid matrix_scl_add(matrix a, float b, matrix c, matrix d)\n{\n #ifndef NO_ERRCHECK\n if ( (a.r != c.r) || (a.c != c.c) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Source and destination dimensions don't match for scl_add!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n if ( (a.r != d.r) || (a.c != d.c) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Source and destination dimensions don't match for scl_add!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n #endif\n\n const unsigned n = a.r * a.cstride;\n\n if (n < add_lim)\n scl_add_small(a.cpu_data, b, c.cpu_data, d.cpu_data, n);\n else\n scl_add_big(a.cpu_data, b, c.cpu_data, d.cpu_data, n);\n}\n\n// pointwise multiplication a = b.*c\nvoid matrix_pmult(matrix a, matrix b, matrix c)\n{\n #ifndef NO_ERRCHECK\n if ( (a.r != b.r) || (b.r != c.r) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Rows don't match for pmult!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n\n if ( (a.c != b.c) || (b.c != c.c) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Cols don't match for pmult!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n #endif\n\n const unsigned n = a.r * a.cstride;\n\n if (n < add_lim)\n pmult_small(a.cpu_data, b.cpu_data, c.cpu_data, n);\n else\n pmult_big(a.cpu_data, b.cpu_data, c.cpu_data, n);\n}\n\n// \nvoid matrix_phi_prime(matrix a, matrix b)\n{\n unsigned r, c;\n\n const unsigned astride = a.cstride;\n const unsigned bstride = b.cstride;\n\n float *adata = a.cpu_data;\n float *bdata = b.cpu_data;\n\n const __m128 mm_s1 = _mm_set1_ps(2.0f/3.0f);\n const __m128 mm_s2 = _mm_set1_ps(1.7159f);\n\n // need to optimize small kern and put into functions\n if ((a.r*a.cstride) < add_lim)\n {\n for (r = 0; r < a.r; ++r)\n for (c = 0; c < a.c; c += 4)\n {\n __m128 mm_v1 = _mm_load_ps(bdata + r*bstride+c);\n\n mm_v1 = _mm_mul_ps(mm_v1, mm_v1);\n\n mm_v1 = _mm_sub_ps(mm_s2, mm_v1);\n\n mm_v1 = _mm_mul_ps(mm_s1, mm_v1);\n\n _mm_store_ps(adata + r*astride+c, mm_v1);\n }\n }\n else\n {\n #pragma omp parallel for private(c)\n for (r = 0; r < a.r; ++r)\n for (c = 0; c < a.c; c += 4)\n {\n __m128 mm_v1 = _mm_load_ps(bdata + r*bstride+c);\n\n mm_v1 = _mm_mul_ps(mm_v1, mm_v1);\n\n mm_v1 = _mm_sub_ps(mm_s2, mm_v1);\n\n mm_v1 = _mm_mul_ps(mm_s1, mm_v1);\n\n _mm_store_ps(adata + r*astride+c, mm_v1);\n }\n }\n\n// const float scl = 2.0f/3.0f;\n// return scl * (1.7159f - z*z);\n\n/*\n #pragma omp parallel for private(c)\n for (r = 0; r < a.r; ++r)\n for (c = 0; c < a.c; ++c)\n adata[r*astride + c] =\n phi_prime(bdata[r*bstride + c]);\n*/\n}\n\n// a = b .* phi_prime(c)\nvoid matrix_pmult_phi_prime(matrix a, matrix b, matrix c)\n{\n unsigned i;\n\n float *adata = a.cpu_data;\n float *bdata = b.cpu_data;\n float *cdata = c.cpu_data;\n\n const __m128 mm_s1 = _mm_set1_ps(2.0f/3.0f);\n const __m128 mm_s2 = _mm_set1_ps(1.7159f);\n\n #pragma omp parallel for\n for (i = 0; i < a.r*a.cstride; i += 4)\n {\n __m128 mm_v1 = _mm_load_ps(bdata+i);\n __m128 mm_v2 = _mm_load_ps(cdata+i);\n\n mm_v2 = _mm_mul_ps(mm_v2, mm_v2);\n\n mm_v2 = _mm_sub_ps(mm_s2, mm_v2);\n\n mm_v2 = _mm_mul_ps(mm_s1, mm_v2);\n\n mm_v2 = _mm_mul_ps(mm_v1, mm_v2);\n\n _mm_store_ps(adata + i, mm_v2);\n }\n}\n\n//\nvoid matrix_delta(matrix delta, matrix y, matrix g)\n{\n unsigned r, c;\n\n #ifndef NO_ERRCHECK\n if ( (delta.r != y.r) || (y.r != g.r) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Rows don't match for delta!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n\n if ( (delta.c != y.c) || (y.c != g.c) ) {\n fprintf(stderr, __FILE__ \" %d: \"\n \"Cols don't match for delta!\\n\", __LINE__);\n exit(CPU_ERROR);\n }\n #endif\n\n const unsigned dstride = delta.cstride;\n const unsigned gstride = g.cstride;\n const unsigned ystride = y.cstride;\n\n float *ddata = delta.cpu_data;\n float *gdata = g.cpu_data;\n float *ydata = y.cpu_data;\n\n // need to optimize small kern and put into functions\n if ((delta.r*delta.cstride) < add_lim)\n {\n const __m128 mm_s = _mm_set1_ps(2.0f/(g.r*g.c));\n for (r = 0; r < delta.r; ++r)\n for (c = 0; c < delta.c; c += 4)\n {\n __m128 mm_v1 = _mm_load_ps(gdata + r*gstride+c);\n __m128 mm_v2 = _mm_load_ps(ydata + r*ystride+c);\n\n mm_v1 = _mm_sub_ps(mm_v2, mm_v1);\n mm_v1 = _mm_mul_ps(mm_v1, mm_s);\n\n _mm_store_ps(ddata + r*dstride+c, mm_v1);\n }\n }\n else\n {\n const __m128 mm_s = _mm_set1_ps(2.0f/(g.r*g.c));\n #pragma omp parallel for private (c)\n for (r = 0; r < delta.r; ++r)\n for (c = 0; c < delta.c; c += 4)\n {\n __m128 mm_v1 = _mm_load_ps(gdata + r*gstride+c);\n __m128 mm_v2 = _mm_load_ps(ydata + r*ystride+c);\n\n mm_v1 = _mm_sub_ps(mm_v2, mm_v1);\n mm_v1 = _mm_mul_ps(mm_v1, mm_s);\n\n _mm_store_ps(ddata + r*dstride+c, mm_v1);\n }\n }\n\n/*\n const float denom = 2.0f / (g.r*g.c);\n\n #pragma omp parallel for private(c)\n for (r = 0; r < delta.r; ++r)\n for (c = 0; c < delta.c; ++c)\n {\n const float gval = gdata[r*gstride + c];\n const float yval = ydata[r*ystride + c];\n\n // wow, sse could be used all over here!\n ddata[r*dstride + c] = \n (yval - gval) * denom;\n }\n*/\n}\n\n//** Combination/Separation\n\n// remove last row of m\nvoid matrix_r0(matrix *m)\n{\n --(m->r);\n\n float *data = (m->cpu_data)+((m->r)*(m->cstride));\n const float *data_end = data + m->c;\n\n while (data < data_end)\n *(data++) = 0.0f;\n}\n\n// append a row of 1's to m\nvoid matrix_r1(matrix *m)\n{\n float *data = (m->cpu_data)+((m->r)*(m->cstride));\n const float *data_end = data + m->c;\n\n while (data < data_end)\n *(data++) = 1.0f;\n\n ++(m->r);\n}\n\n//** Error measurement\n\n// rmse between values of actual and approx\nfloat matrix_rmse(matrix actual, matrix approx)\n{\n // if dims don't match throw error!\n \n unsigned r, c;\n const unsigned stride = actual.cstride;\n const unsigned len = actual.r*actual.c;\n float *d1 = actual.cpu_data;\n float *d2 = approx.cpu_data;\n float err = 0.0f;\n\n // need to use omp, maybe reduction? \n for (r = 0; r < actual.r; ++r)\n for (c = 0; c < actual.c; ++c)\n {\n const unsigned i = r*stride+c;\n err += (d1[i] - d2[i])*(d1[i] - d2[i]);\n }\n\n return sqrt(err/len);\n}\n\n// remove and save last col of m\nvoid matrix_c0v(matrix *m)\n{\n unsigned r;\n const unsigned stride = m->cstride;\n const unsigned c = --(m->c);\n float *data = m->cpu_data;\n\n for (r = 0; r < m->r; ++r)\n {\n float *cur = data + r*stride+c;\n m->cv[r] = *cur;\n *cur = 0.0f;\n }\n}\n\n// restore last col of m\nvoid matrix_cv(matrix *m)\n{\n unsigned r;\n\n const unsigned stride = m->cstride;\n const unsigned c = (m->c)++;\n float *data = m->cpu_data;\n\n for (r = 0; r < m->r; ++r)\n data[r*stride+c] = m->cv[r];\n}\n\n//** Output\n\n// print m to standard out\nvoid matrix_print(matrix m)\n{\n unsigned r, c;\n const unsigned stride = m.cstride;\n float *data = m.cpu_data;\n\n // print each value to stdout\n for (r = 0; r < m.r; ++r)\n {\n for (c = 0; c < m.c; ++c)\n printf(\"%f \", data_at(r,c));\n printf(\"\\n\");\n }\n}\n\n// print m including padding to standard out\nvoid matrix_print_padded(matrix m)\n{\n unsigned r, c;\n\n // set data and stride for data_at\n const unsigned stride = m.cstride;\n float *data = m.cpu_data;\n\n // print each value to stdout\n for (r = 0; r < m.rstride; ++r)\n {\n for (c = 0; c < m.cstride; ++c)\n printf(\"%f \", data_at(r,c));\n printf(\"\\n\");\n }\n}\n", "meta": {"hexsha": "b90d5299087b8c463ea453769a0deb79bbc46efc", "size": 29732, "ext": "c", "lang": "C", "max_stars_repo_path": "matrix_cpu/matrix.c", "max_stars_repo_name": "idfah/badger", "max_stars_repo_head_hexsha": "75028a7e42e4a02460f20f1aa82c289801de1b05", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matrix_cpu/matrix.c", "max_issues_repo_name": "idfah/badger", "max_issues_repo_head_hexsha": "75028a7e42e4a02460f20f1aa82c289801de1b05", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix_cpu/matrix.c", "max_forks_repo_name": "idfah/badger", "max_forks_repo_head_hexsha": "75028a7e42e4a02460f20f1aa82c289801de1b05", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3009404389, "max_line_length": 90, "alphanum_fraction": 0.5875151352, "num_tokens": 9605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4239835136237395}} {"text": "\n/*\n* -----------------------------------------------------------------\n* ode_lib.c\n* ODE Solver Library\n* Version: 2.0\n* Last Update: Oct 1, 2019\n* \n* This is the implementation of a computational library with\n* numerical tools for Ordinary Differential Equations (ODE).\n* ----------------------------------------------------------------- \n* Programmer: Americo Barbosa da Cunha Junior\n* americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n* Copyright (c) 2019 by Americo Barbosa da Cunha Junior\n* -----------------------------------------------------------------\n*/\n\n\n\n\n#include \n#include \n#include \n\n#include /* prototypes for CVODE functions and const */\n#include /* access to serial NVector */\n#include /* access to dense SUNMatrix */\n#include /* access to dense SUNLinearSolver */\n#include /* defs. of realtype, sunindextype */\n\n#include \n#include \n#include \n\n#include \"../include/ode_lib.h\"\n\n\n\n/*\n*------------------------------------------------------------\n* uround\n*\n* This function computes the machine unit roundoff\n* defined as the smallest u such that 1.0 + u > 1.0\n*\n* Output:\n* uround - machine unit roundoff\n*\n* last update: May 20, 2009\n*------------------------------------------------------------\n*/\n\ndouble uround(void)\n{\n double u = 1.0;\n double comp = 0.0;\n\n while(comp != 1.0)\n {\n\tu *= 0.5;\n\tcomp = 1.0 + u;\n }\n \n return 2.0*u;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* wnorm\n*\n* This function computes v1 and v2 vector weight norm\n* defined as\n* wnorm = sqrt( (1/n)*(sum (v1[i]*v2[i])^2) )\n*\n* Input:\n* n - vectors dimension\n* v - vector 1\n* v - vector 2\n*\n* Output:\n* wnorm - weight norm\n*\n* last update: May 20, 2009\n*------------------------------------------------------------\n*/\n\ndouble wnorm(int n,double *v1,double *v2)\n{\n int i;\n double wnorm = 0.0;\n \n for ( i = 0; i < n; i++ )\n\twnorm += v1[i]*v1[i]*v2[i]*v2[i];\n \n return sqrt( wnorm / (double)n );\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* ewset\n*\n* This function creates a error weight vector\n* defined as ewv[i] = rtol*abs(v[i]) + atol\n*\n* Input:\n* n - vector dimension\n* v - vector\n* atol - absolute tolerance\n* rtol - relative tolerance\n*\n* Output:\n* ewv - error weight vector\n*\n* last update: May 22, 2009\n*------------------------------------------------------------\n*/\n\nvoid ewtset(int n,double *v,double atol,double rtol,double *ewt)\n{\n int i;\n \n for ( i = 0; i < n; i++ )\n ewt[i] = rtol*fabs(v[i]) + atol;\n \n return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*------------------------------------------------------------\n* jacobian\n*\n* This function computes the jacobian matrix of ydot = f(y,t)\n* defiend as Jij = dfi/dyj\n*\n* Input:\n* n - vector dimension\n* f_data - pointer to external data\n* Fy - reaction mapping\n* y - composition vector\n* t - time step\n* atol - absolute tolerance\n* rtol - relative tolerance\n*\n* Output:\n* J - jacobian matrix\n* success or error\n*\n* last update: Oct 7, 2009\n------------------------------------------------------------*/\n\nint jacobian(CVRhsFn f,void *f_data,gsl_vector *Fy,gsl_vector *y,\n double t,double atol,double rtol,gsl_matrix *J)\n{\n unsigned int i, j, N1, N2;\n double roundoff, min_inc_mult;\n double fnorm, minInc, inc, inc_inv, yjsaved, srur;\n double *yd_data = NULL;\n double *Fyd_data = NULL;\n N_Vector yd = NULL;\n N_Vector Fyd = NULL;\n gsl_vector *ewt = NULL;\n \n \n min_inc_mult = 1.0e3;\n \n /* vectors dimensions */\n N1 = y->size;\n N2 = Fy->size;\n \n /* error weight vector */\n ewt = gsl_vector_calloc(N1);\n \n /* computing the unit roundoff */\n roundoff = uround();\n \n /* memory allocation and startup of yd and Fyd */\n yd = N_VNew_Serial(N1);\n Fyd = N_VNew_Serial(N2);\n if ( yd == NULL || Fyd == NULL )\n return GSL_ENOMEM;\n \n /* obtaining yd and Fyd compoments */\n yd_data = NV_DATA_S(yd);\n Fyd_data = NV_DATA_S(Fyd);\n \n /* setting yd equal y vector */\n for ( i = 0; i < N1; i++ )\n yd_data[i] = y->data[i];\n \n /* setting Fyd equal the null vector */\n for ( i = 0; i < N2; i++ )\n Fyd_data[i] = 0.0;\n \n /* defing error weight vector */\n ewtset(N1,y->data,atol,rtol,ewt->data);\n \n /* computing weight norm */\n fnorm = wnorm(N2,Fy->data,ewt->data);\n \n /* square root of the machine roundoff */\n srur = sqrt(roundoff);\n \n /* computing disturbance parameter */\n minInc = (fnorm != 0.0) ?\n\t (min_inc_mult*fabs(t)*roundoff*((double)N1)*fnorm) : 1.0;\n \n for ( j = 0; j < N1; j++ )\n {\n /* saving y[j] value */\n yjsaved = yd_data[j];\n \n /* disturbance */\n inc = GSL_MAX(srur*fabs(yjsaved),minInc/ewt->data[j]);\n \t\n \t/* disturbing y */\n yd_data[j] += inc;\n\t\n /* computing Fy disturbed */\n f(t,yd,Fyd,f_data);\n\t\n\t/* restoring yd[j] original value */\n yd_data[j] = yjsaved;\n\t\n\t/* computing the step */\n inc_inv = 1.0/inc;\n \n /* computing jacobian matrix column j */\n \tfor ( i = 0; i < N2; i++ )\n J->data[i*J->tda+j] = inc_inv*(Fyd_data[i] - Fy->data[i]);\n }\n \n /* releasing allocated memory */\n N_VDestroy_Serial(yd);\n N_VDestroy_Serial(Fyd);\n gsl_vector_free(ewt);\n yd = NULL;\n Fyd = NULL;\n yd_data = NULL;\n Fyd_data = NULL;\n ewt = NULL;\n \n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*------------------------------------------------------------\n* gradient\n*\n* This function computes the gradient matrix of R(phi)\n* defiend as: Aij = d R_i/d phi_j\n*\n* Input:\n* cvode_mem - ODE solver workspace\n* t0 - initial time\n* delta_t - time step\n* phi - composition vector\n* Rphi - reac tion mapping\n*\n* Output:\n* A - gradient matrix\n* success or error\n*\n* last update: Oct 1, 2019\n------------------------------------------------------------*/\n\nint gradient(void *cvode_mem,double t0,double delta_t,\n gsl_vector *phi,gsl_vector *Rphi,gsl_matrix *A)\n{\n unsigned int i, j, flag;\n double inc, inc_inv, phijsaved, srur;\n gsl_vector *Rphid = NULL;\n \n /* memory allocation for Rphid */\n Rphid = gsl_vector_calloc(Rphi->size);\n \n /* square root of 1.0e6 times the machine roundoff */\n srur = sqrt(1.0e6*DBL_EPSILON);\n \n for ( j = 0; j < phi->size; j++ )\n {\n /* save phi_j value */\n phijsaved = phi->data[j];\n \n /* disturbance */\n inc = phijsaved*srur + srur;\n \t\n \t/* disturbe phi_j */\n phi->data[j] += inc;\n\t\n /* compute R(phi) disturbed */\n\tflag = odesolver_reinit(t0,phi,cvode_mem);\n if ( flag != GSL_SUCCESS )\n return flag;\n \n\tflag = odesolver(cvode_mem,delta_t,Rphid);\n if ( flag != GSL_SUCCESS )\n return flag;\n\t\n\t/* restore phi_j original value */\n phi->data[j] = phijsaved;\n\t\n\t/* compute the step */\n inc_inv = 1.0/inc;\n \n /* compute gradient matrix column j */\n \tfor ( i = 0; i < Rphi->size; i++ )\n A->data[i*A->tda+j] = inc_inv*(Rphid->data[i] - Rphi->data[i]);\n }\n \n \n /* release allocated memory */\n gsl_vector_free(Rphid);\n Rphid = NULL;\n \n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* linear_approx\n*\n* This function computes the linear approximation\n* for a vector function F(x) near the point x0.\n* \n* F(x) = F(x0) + DF(x0)*(x-x0)\n* \n* Input:\n* x - vector x\n* x0 - vector x0\n* Fx0 - function at x0\n* DFx0 - jacobian matrix at x0\n*\n* Output:\n* Fx - linear approximation for F(x)\n*\n* last update: Jun 9, 2009\n*------------------------------------------------------------\n*/\n\nvoid linear_approx(gsl_vector *x,gsl_vector *x0,\n gsl_vector *Fx0,gsl_matrix *DFx0,gsl_vector *Fx)\n{\n gsl_vector *aux = NULL;\n \n /* memory allocation */\n aux = gsl_vector_alloc(x0->size);\n\n /* aux := x */\n gsl_vector_memcpy(aux,x);\n \n /* aux := x - x0 */\n gsl_vector_sub(aux,x0);\n \n /* Fx := F(x0) */\n gsl_vector_memcpy(Fx,Fx0);\n \n /* Fx := F(x0) + DF(x0)*(x-x0) */\n gsl_blas_dgemv(CblasNoTrans,1.0,DFx0,aux,1.0,Fx);\n \n /* releasing allocated memory */\n gsl_vector_free(aux);\n aux = NULL;\n \n return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* odesolver_init\n*\n* This function initiates the ODE solver workspace.\n*\n* Input:\n* f - right hand side function\n* f_data - right hand side function data\n* t0 - initial time\n* mxsteps - max # of solver iterations\n* atol - absolute tolerance\n* rtol - relative tolerance\n* x - initial condition\n* cvode_mem - ODE solver workspace\n*\n* Output:\n* success or error\n*\n* last update: Oct 1, 2019\n*------------------------------------------------------------\n*/\n\nint odesolver_init(CVRhsFn f,void *f_data,double t0,int mxsteps,\n\t\t double atol,double rtol,gsl_vector *x,void *cvode_mem)\n{\n int maxnef = 100; /* max. # of error test failures */\n int flag = CV_SUCCESS; /* return value flag */\n N_Vector y0 = NULL; /* initial condition vector */\n SUNMatrix A = NULL; /* Matrix for linear solver use */\n SUNLinearSolver LS = NULL; /* dense linear solver object */\n\n \n /* memory allocation for initial condition y0 */\n y0 = N_VMake_Serial(x->size,x->data);\n if ( y0 == NULL )\n\treturn GSL_ENOMEM;\n\n /* memory allocation for CVODE workspace */\n flag = CVodeInit(cvode_mem,f,t0,y0);\n if( flag != CV_SUCCESS )\n \treturn GSL_ENOMEM;\n\n /* specifies scalar absolute and relative tolerances */\n flag = CVodeSStolerances(cvode_mem,rtol,atol);\n if( flag != CV_SUCCESS )\n \treturn flag;\n\n /* set user data for right hand side function */ \n flag = CVodeSetUserData(cvode_mem,f_data);\n if( flag != CV_SUCCESS )\n return flag;\n \n /* Create dense SUNMatrix for use in linear solver */\n A = SUNDenseMatrix(x->size,x->size);\n if ( A == NULL )\n\treturn GSL_ENOMEM;\n\n /* Create dense SUNLinearSolver object for use by CVode */\n LS = SUNLinSol_Dense(y0, A);\n if ( LS == NULL )\n\treturn GSL_ENOMEM;\n\n /* Call CVodeSetLinearSolver to attach the matrix and linear solver to CVode */\n flag = CVodeSetLinearSolver(cvode_mem, LS, A);\n if( flag != CVLS_SUCCESS )\n \treturn flag;\n\n /* set solver max # of steps */\n flag = CVodeSetMaxNumSteps(cvode_mem,mxsteps);\n if( flag != CV_SUCCESS )\n return flag; \n\n /* set max # of error test failures permitted */\n flag = CVodeSetMaxErrTestFails(cvode_mem,maxnef);\n if( flag != CV_SUCCESS )\n return flag;\n \n /* release allocated memory for y0 */\n N_VDestroy_Serial(y0);\n y0 = NULL;\n\n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* odesolver_reinit\n*\n* This function reinitiates the ODE solver workspace.\n*\n* Input:\n* f - right hand side function\n* f_data - right hand side function data\n* t0 - initial time\n* x - initial condition\n* cvode_mem - ODE solver workspace\n*\n* Output:\n* success or error\n*\n* last update: Oct 1, 2019\n*------------------------------------------------------------\n*/\n\nint odesolver_reinit(double t0,gsl_vector *x,void *cvode_mem)\n{\n int flag = CV_SUCCESS; /* return value flag */\n N_Vector y0 = NULL; /* initial condition vector */\n \n /* memory allocation for y0 */\n y0 = N_VMake_Serial(x->size,x->data);\n if ( y0 == NULL )\n\treturn GSL_ENOMEM;\n \n /* restart CVODE workspace */\n flag = CVodeReInit(cvode_mem,t0,y0);\n if( flag != CV_SUCCESS )\n \treturn flag;\n \n /* release allocated memory */\n N_VDestroy_Serial(y0);\n y0 = NULL;\n\n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* odesolver\n*\n* This function performs the direct integration of the\n* governing equations.\n*\n* Input:\n* cvode_mem - ODE solver workspace\n* tf - final time\n* Fx - solution vector\n*\n* Output:\n* success or error\n*\n* last update: Oct 31, 2009\n*------------------------------------------------------------\n*/\n\nint odesolver(void *cvode_mem,double tf,gsl_vector *Fx)\n{\n double t;\n int flag = CV_SUCCESS;\n N_Vector y = NULL;\n \n /* memory allocation and startup of y */\n y = N_VMake_Serial(Fx->size,Fx->data);\n if ( y == NULL )\n\treturn GSL_ENOMEM;\n \n /* calling CVode solver */\n flag = CVode(cvode_mem,tf,y,&t,CV_NORMAL);\n if( flag != CV_SUCCESS )\n return flag;\n \n /* releasing allocated memory */\n N_VDestroy_Serial(y);\n y = NULL;\n\n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n", "meta": {"hexsha": "ad1602f605fadc38ebf8117cc6f612c833eab52e", "size": 13945, "ext": "c", "lang": "C", "max_stars_repo_path": "CRFlowLib-2.0/src/ode_lib.c", "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_issues_repo_path": "CRFlowLib-2.0/src/ode_lib.c", "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRFlowLib-2.0/src/ode_lib.c", "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "avg_line_length": 24.594356261, "max_line_length": 85, "alphanum_fraction": 0.4945858731, "num_tokens": 3692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.42367561790961367}} {"text": "// Copyright (c) 2005 Stanford University (USA).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org); you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public License as\n// published by the Free Software Foundation; either version 3 of the License,\n// or (at your option) any later version.\n//\n// Licensees holding a valid commercial license may use this file in\n// accordance with the commercial license agreement provided with the software.\n//\n// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n//\n// $URL$\n// $Id$\n// \n//\n// Author(s) : Daniel Russel \n\n#ifndef CGAL_POLYNOMIAL_INTERNAL_GSL_NUMERIC_SOLVER_H\n#define CGAL_POLYNOMIAL_INTERNAL_GSL_NUMERIC_SOLVER_H\n#include \n#include \n#include \n\n#ifdef CGAL_POLYNOMIAL_USE_GSL\n\n#include \n#include \n\nnamespace CGAL { namespace POLYNOMIAL { namespace internal {\n\n/*template \ninline double gsl_max_error()\n{\n if (CLEAN) return .0000005;\n else return 0;\n }*/\n\n\ntemplate \ninline void gsl_compute_roots(const double *begin, const double *end,\ndouble lb, double ub,\nstd::vector &roots_)\n{\n\n //double max_error=gsl_max_error();\n\n gsl_poly_complex_workspace *workspace;\n int degree= end-begin-1;\n workspace= gsl_poly_complex_workspace_alloc(degree+1);\n\n//! I can't use auto_ptr because it is an array\n double *roots= new double[2*degree];\n\n/*for ( int i=0; i< 2*fn.degree(); ++i){\n roots[i]=0;\n }*/\n\n int ret = gsl_poly_complex_solve(begin, degree+1, workspace,\n roots);\n roots_.reserve(ret);\n\n if (ret!=GSL_SUCCESS) {\n std::cerr << \"GSL solver did not converge on \";\n std::copy(begin, end, std::ostream_iterator(std::cerr, \" \"));\n std::cerr << std::endl;\n }\n\n double last= -std::numeric_limits::infinity();\n for ( int i=degree-1; i>=0; --i) {\n double r= roots[2*i];\n double c= roots[2*i+1];\n if (root_is_good(r, c, lb, ub)) {\n roots_.push_back(r);\n } else if (CLEAN && root_is_good(r,c, last, ub)) {\n\t last= r;\n\t}\n }\n\n std::sort(roots_.begin(), roots_.end(), std::greater() );\n delete roots;\n\n gsl_poly_complex_workspace_free(workspace);\n\n if (CLEAN) filter_solver_roots(begin,end, lb, ub, last, roots_);\n return;\n}\n\n\ntemplate \ninline void gsl_compute_cubic_roots(const double *begin, const double *end,\ndouble lb, double ub,\nstd::vector &roots_)\n{\n CGAL_Polynomial_precondition(begin[3] != 0);\n //double max_error=gsl_max_error();\n\n double r[3];\n int num_roots= gsl_poly_solve_cubic(begin[2]/begin[3],\n begin[1]/begin[3],\n begin[0]/begin[3], &r[0],&r[1],&r[2]);\n roots_.reserve(num_roots);\n double last= -std::numeric_limits::infinity();\n// I want reverse sorted roots\n for (int i=num_roots-1; i>=0; --i) {\n if (r[i]> lb && r[i] < ub) roots_.push_back(r[i]);\n\telse if (CLEAN && r[i] last){\n\t last= r[i];\n\t}\n }\n if (CLEAN) filter_solver_roots(begin, end, lb, ub, last, roots_);\n}\n\n\ninline void gsl_polynomial_compute_roots(const double *begin, const double *end,\ndouble lb, double ub,\nstd::vector &roots)\n{\n int degree= end-begin-1;\n switch( degree) {\n case -1:\n case 0:\n break;\n case 1:\n compute_linear_roots(begin,end, lb, ub, roots);\n break;\n case 2:\n compute_quadratic_roots(begin, end, lb, ub, roots);\n break;\n case 3:\n gsl_compute_cubic_roots(begin, end, lb, ub, roots);\n break;\n default:\n gsl_compute_roots(begin, end, lb, ub, roots);\n }\n}\n\n\ninline void gsl_polynomial_compute_cleaned_roots(const double *begin, const double *end,\ndouble lb, double ub,\nstd::vector &roots)\n{\n int degree= end-begin-1;\n switch( degree) {\n case -1:\n case 0:\n break;\n case 1:\n compute_linear_cleaned_roots(begin,end, lb, ub, roots);\n break;\n case 2:\n compute_quadratic_cleaned_roots(begin, end, lb, ub, roots);\n break;\n case 3:\n gsl_compute_cubic_roots(begin, end, lb, ub, roots);\n break;\n default:\n gsl_compute_roots(begin, end, lb, ub, roots);\n }\n}\n\n\ninline double gsl_evaluate_polynomial(const double *b, const double *e, double t)\n{\n if (b==e) return 0;\n/*double *d= new double[coefs.size()];\nfor (unsigned int i=0; i< coefs.size(); ++i){\n d[i]= coefs[i];\n }*/\n double v= gsl_poly_eval(b, e-b, t);\n return v;\n}\n\n\n/*\n\ninline void gsl_polynomial_compute_roots(const double *begin, const double *end,\n double lb, double ub,\n std::vector &roots){\n CGAL_assertion(0&& no_gsl_support_built);\n}\n\ninline void gsl_polynomial_compute_cleaned_roots(const double *begin, const double *end,\n double lb, double ub,\n std::vector &roots){\nCGAL_assertion(0&& no_gsl_support_built);\n}\n\ninline double gsl_evaluate_polynomial(const double *b, const double *e, double t) {\nCGAL_assertion(0&& no_gsl_support_built);\nreturn std::numeric_limits::nan();\n}\n*/\n\n/*// GSL\nvoid gsl_polynomial_compute_roots(const double *begin, const double *end,\n double lb, double ub, std::vector &roots);\n\nvoid gsl_polynomial_compute_cleaned_roots(const double *begin, const double *end,\ndouble lb, double ub, std::vector &roots);*/\n\nstruct GSL_numeric_solver\n{\n void operator()(const double *begin, const double *end,\n double lb, double ub,\n std::vector &roots) const\n {\n gsl_polynomial_compute_roots(begin, end, lb, ub, roots);\n }\n};\n\nstruct GSL_cleaned_numeric_solver\n{\n void operator()(const double *begin, const double *end,\n double lb, double ub,\n std::vector &roots) const\n {\n gsl_polynomial_compute_cleaned_roots(begin, end, lb, ub, roots);\n }\n};\n\n} } } //namespace CGAL::POLYNOMIAL::internal\n\n#endif // CGAL_POLYNOMIAL_USE_GSL\n\n#endif\n", "meta": {"hexsha": "6808909e1a27c243c20d416af9319309f2048ea6", "size": 6363, "ext": "h", "lang": "C", "max_stars_repo_path": "geo3d/include/CGAL/Polynomial/internal/GSL_numeric_solver.h", "max_stars_repo_name": "vipuserr/vipuserr-Geological-hazard", "max_stars_repo_head_hexsha": "2b29c03cdac6f5e1ceac4cd2f15b594040ef909c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/include/CGAL/Polynomial/internal/GSL_numeric_solver.h", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/include/CGAL/Polynomial/internal/GSL_numeric_solver.h", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 27.7860262009, "max_line_length": 88, "alphanum_fraction": 0.6467075279, "num_tokens": 1700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4236039578479139}} {"text": "// The MIT License (MIT)\n//\n// Copyright (c) 2018 Mateusz Pusz, Conor Williams, Oliver Schonrock\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace units::detail {\n\ntemplate\n[[nodiscard]] constexpr T abs(T v) noexcept\n{\n return v < 0 ? -v : v;\n}\n\n// the following functions enable gcd and related computations on ratios\n// with exponents. They avoid overflow. Further information here:\n// https://github.com/mpusz/units/issues/62#issuecomment-588152833\n\n// Computes (a * b) mod m relies on unsigned integer arithmetic, should not\n// overflow\n[[nodiscard]] constexpr std::uint64_t mulmod(std::uint64_t a, std::uint64_t b, std::uint64_t m)\n{\n std::uint64_t res = 0;\n\n if (b >= m) {\n if (m > UINT64_MAX / 2u) {\n b -= m;\n } else {\n b %= m;\n }\n }\n\n while (a != 0) {\n if (a & 1) {\n if (b >= m - res) {\n res -= m;\n }\n res += b;\n }\n a >>= 1;\n\n std::uint64_t temp_b = b;\n if (b >= m - b) {\n temp_b -= m;\n }\n b += temp_b;\n }\n\n return res;\n}\n\n// Calculates (a ^ e) mod m , should not overflow.\n[[nodiscard]] constexpr std::uint64_t modpow(std::uint64_t a, std::uint64_t e, std::uint64_t m)\n{\n a %= m;\n std::uint64_t result = 1;\n\n while (e > 0) {\n if (e & 1) {\n result = mulmod(result, a, m);\n }\n a = mulmod(a, a, m);\n e >>= 1;\n }\n return result;\n}\n\n// gcd(a * 10 ^ e, b), should not overflow\n[[nodiscard]] constexpr std::intmax_t gcdpow(std::intmax_t a, std::intmax_t e, std::intmax_t b) noexcept\n{\n assert(a > 0);\n assert(e >= 0);\n assert(b > 0);\n\n // gcd(i, j) = gcd(j, i mod j) for j != 0 Euclid;\n //\n // gcd(a 10^e, b) = gcd(b, a 10^e mod b)\n //\n // (a 10^e) mod b -> [ (a mod b) (10^e mod b) ] mod b\n\n return std::gcd(\n b, static_cast(mulmod(static_cast(a % b),\n modpow(10, static_cast(e), static_cast(b)),\n static_cast(b))));\n}\n\nconstexpr void cwap(std::intmax_t& lhs, std::intmax_t& rhs)\n{\n std::intmax_t tmp = lhs;\n lhs = rhs;\n rhs = tmp;\n}\n\n// Computes the rational gcd of n1/d1 x 10^e1 and n2/d2 x 10^e2\n[[nodiscard]] constexpr auto gcd_frac(std::intmax_t n1, std::intmax_t d1, std::intmax_t e1, std::intmax_t n2, std::intmax_t d2,\n std::intmax_t e2) noexcept\n{\n // Short cut for equal ratios\n if (n1 == n2 && d1 == d2 && e1 == e2) {\n return std::array{n1, d1, e1};\n }\n\n if (e2 > e1) {\n detail::cwap(n1, n2);\n detail::cwap(d1, d2);\n detail::cwap(e1, e2);\n }\n\n std::intmax_t exp = e2; // minimum\n\n // gcd(a/b,c/d) = gcd(aâ‹…d, câ‹…b) / bâ‹…d\n\n assert(std::numeric_limits::max() / n1 > d2);\n assert(std::numeric_limits::max() / n2 > d1);\n\n std::intmax_t num = detail::gcdpow(n1 * d2, e1 - e2, n2 * d1);\n\n assert(std::numeric_limits::max() / d1 > d2);\n\n std::intmax_t den = d1 * d2;\n\n std::intmax_t gcd = std::gcd(num, den);\n\n return std::array{num / gcd, den / gcd, exp};\n}\n\nconstexpr void normalize(std::intmax_t& num, std::intmax_t& den, std::intmax_t& exp)\n{\n if(num == 0) {\n den = 1;\n exp = 0;\n return;\n }\n\n std::intmax_t gcd = std::gcd(num, den);\n num = num * (den < 0 ? -1 : 1) / gcd;\n den = detail::abs(den) / gcd;\n\n while (num % 10 == 0) {\n num /= 10;\n ++exp;\n }\n while (den % 10 == 0) {\n den /= 10;\n --exp;\n }\n}\n\n[[nodiscard]] constexpr std::intmax_t safe_multiply(std::intmax_t lhs, std::intmax_t rhs)\n{\n constexpr std::intmax_t c = std::uintmax_t(1) << (sizeof(std::intmax_t) * 4);\n\n const std::intmax_t a0 = detail::abs(lhs) % c;\n const std::intmax_t a1 = detail::abs(lhs) / c;\n const std::intmax_t b0 = detail::abs(rhs) % c;\n const std::intmax_t b1 = detail::abs(rhs) / c;\n\n gsl_Expects(a1 == 0 || b1 == 0); // overflow in multiplication\n gsl_Expects(a0 * b1 + b0 * a1 < (c >> 1)); // overflow in multiplication\n gsl_Expects(b0 * a0 <= INTMAX_MAX); // overflow in multiplication\n gsl_Expects((a0 * b1 + b0 * a1) * c <= INTMAX_MAX - b0 * a0); // overflow in multiplication\n\n return lhs * rhs;\n}\n\n} // namespace units::detail\n", "meta": {"hexsha": "9ea155b6fcbc8795c1f154c7e47ece9629d8098b", "size": 5488, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/units/bits/ratio_maths.h", "max_stars_repo_name": "bebuch/units", "max_stars_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 571.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T14:57:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:53:22.000Z", "max_issues_repo_path": "src/core/include/units/bits/ratio_maths.h", "max_issues_repo_name": "bebuch/units", "max_issues_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 283.0, "max_issues_repo_issues_event_min_datetime": "2018-11-01T05:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:25:11.000Z", "max_forks_repo_path": "src/core/include/units/bits/ratio_maths.h", "max_forks_repo_name": "bebuch/units", "max_forks_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 70.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T01:04:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T01:57:29.000Z", "avg_line_length": 28.1435897436, "max_line_length": 127, "alphanum_fraction": 0.6064139942, "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4234174495093707}} {"text": "/* eigen/gsl_eigen.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_EIGEN_H__\n#define __GSL_EIGEN_H__\n\n#include \n#include \n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct {\n size_t size;\n double * d;\n double * sd;\n} gsl_eigen_symm_workspace;\n\ngsl_eigen_symm_workspace * gsl_eigen_symm_alloc (const size_t n);\nvoid gsl_eigen_symm_free (gsl_eigen_symm_workspace * w);\nint gsl_eigen_symm (gsl_matrix * A, gsl_vector * eval, gsl_eigen_symm_workspace * w);\n\ntypedef struct {\n size_t size;\n double * d;\n double * sd;\n double * gc;\n double * gs;\n} gsl_eigen_symmv_workspace;\n\ngsl_eigen_symmv_workspace * gsl_eigen_symmv_alloc (const size_t n);\nvoid gsl_eigen_symmv_free (gsl_eigen_symmv_workspace * w);\nint gsl_eigen_symmv (gsl_matrix * A, gsl_vector * eval, gsl_matrix * evec, gsl_eigen_symmv_workspace * w);\n\ntypedef struct {\n size_t size;\n double * d;\n double * sd;\n double * tau;\n} gsl_eigen_herm_workspace;\n\ngsl_eigen_herm_workspace * gsl_eigen_herm_alloc (const size_t n);\nvoid gsl_eigen_herm_free (gsl_eigen_herm_workspace * w);\nint gsl_eigen_herm (gsl_matrix_complex * A, gsl_vector * eval,\n gsl_eigen_herm_workspace * w);\n\ntypedef struct {\n size_t size;\n double * d;\n double * sd;\n double * tau;\n double * gc;\n double * gs;\n} gsl_eigen_hermv_workspace;\n\ngsl_eigen_hermv_workspace * gsl_eigen_hermv_alloc (const size_t n);\nvoid gsl_eigen_hermv_free (gsl_eigen_hermv_workspace * w);\nint gsl_eigen_hermv (gsl_matrix_complex * A, gsl_vector * eval, \n gsl_matrix_complex * evec,\n gsl_eigen_hermv_workspace * w);\n\n\n\ntypedef enum {\n GSL_EIGEN_SORT_VAL_ASC,\n GSL_EIGEN_SORT_VAL_DESC,\n GSL_EIGEN_SORT_ABS_ASC,\n GSL_EIGEN_SORT_ABS_DESC\n}\ngsl_eigen_sort_t;\n\n/* Sort eigensystem results based on eigenvalues.\n * Sorts in order of increasing value or increasing\n * absolute value.\n *\n * exceptions: GSL_EBADLEN\n */\n\nint gsl_eigen_symmv_sort(gsl_vector * eval, gsl_matrix * evec,\n gsl_eigen_sort_t sort_type);\n\nint gsl_eigen_hermv_sort(gsl_vector * eval, gsl_matrix_complex * evec,\n gsl_eigen_sort_t sort_type);\n\n\n/* The following functions are obsolete: */\n\n/* Eigensolve by Jacobi Method\n *\n * The data in the matrix input is destroyed.\n *\n * exceptions: \n */\nint\ngsl_eigen_jacobi(gsl_matrix * matrix,\n gsl_vector * eval,\n gsl_matrix * evec,\n unsigned int max_rot, \n unsigned int * nrot);\n\n\n/* Invert by Jacobi Method\n *\n * exceptions: \n */\nint\ngsl_eigen_invert_jacobi(const gsl_matrix * matrix,\n gsl_matrix * ainv,\n unsigned int max_rot);\n\n\n\n__END_DECLS\n\n#endif /* __GSL_EIGEN_H__ */\n", "meta": {"hexsha": "ea7bfb1a52c8f0be89b3c294d82c621d753156b0", "size": 3733, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/eigen/gsl_eigen.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/eigen/gsl_eigen.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/eigen/gsl_eigen.h", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 26.475177305, "max_line_length": 106, "alphanum_fraction": 0.700508974, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.4231125513504933}} {"text": "/*\n * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer\n *\n * Yan-Rong Li, liyanrong@mail.ihep.ac.cn\n * Jun 30, 2016\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"dnest.h\"\n#include \"model3.h\"\n\nint which_level_update;\nint num_params;\nDNestFptrSet *fptrset_thismodel3;\n\nvoid model3()\n{ \n int i, argc=0, narg=6;\n char **argv;\n\n argv = malloc(narg*sizeof(char *));\n for(i=0; ifrom_prior = from_prior_thismodel3;\n fptrset_thismodel3->log_likelihoods_cal = log_likelihoods_cal_thismodel3;\n fptrset_thismodel3->log_likelihoods_cal_initial = log_likelihoods_cal_thismodel3;\n fptrset_thismodel3->log_likelihoods_cal_restart = log_likelihoods_cal_thismodel3;\n fptrset_thismodel3->perturb = perturb_thismodel3;\n fptrset_thismodel3->print_particle = print_particle_thismodel3;\n fptrset_thismodel3->restart_action = restart_action_model3;\n \n /* run dnest */\n dnest(argc, argv, fptrset_thismodel3, num_params, NULL, NULL, NULL, \"./\", \"OPTIONS3\", NULL, NULL);\n \n /* free memory */\n dnest_free_fptrset(fptrset_thismodel3);\n\n for(i=0; i (size_levels - 20)?(size_levels-20):which_level_update;\n which_level = 0;\n if(which_level > 0 )\n {\n limit1 = limits[(which_level_update-1) * num_params *2 + which *2 ];\n limit2 = limits[(which_level_update-1) * num_params *2 + which *2 + 1];\n }\n else\n {\n limit1 = -6.0;\n limit2 = 6.0;\n }\n width = (limit2 - limit1);\n params[which] += width * dnest_randh();\n dnest_wrap(¶ms[which], -6.0, 6.0);\n return logH;\n}\n/*=======================================================*/\n\nvoid print_particle_thismodel3(FILE *fp, const void *model)\n{\n int i;\n double *params = (double *)model;\n for(i=0; i\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n/*\n#include \n#include \n#include \n#include \n*/\n\n#ifdef DEBUG_LINALG\n#include \n#endif\n\n\nnamespace boost { namespace numeric { namespace ublas {\n\n// specialization for double precision\ntemplate\ninline matrix // prod( m1, m2 )\nprod(const matrix &m1, const matrix &m2)\n{\n\n #ifdef DEBUG_LINALG\n auto start = std::chrono::system_clock::now();\n #endif\n\n boost::numeric::ublas::matrix AxB( m1.size1(), m2.size2() );\n\n // Note that a Map m(&data) gives a view into the data (can change it)\n // while assignments Matrix m = Map< Matrix > (&data)\n // lead to a data copy and lost connection between the reference and matrix\n Eigen::Map mA_( &(m1.data()[0]), m1.size2(), m1.size1() );\n Eigen::Map mB_( &(m2.data()[0]), m2.size2(), m2.size1() );\n Eigen::Map AxB_( &(AxB.data()[0]), AxB.size2(), AxB.size1() );\n\n AxB_ = mB_*mA_;\n\n #ifdef DEBUG_LINALG\n auto end = std::chrono::system_clock::now();\n std::chrono::duration elapsed_seconds = end - start;\n std::cout << \"\\n... ... ... \\x1b[0;34mEigen \"\n << \"[\" << m1.size1() << \"x\" << m1.size2() << \"]\"\n << \"*[\" << m2.size1() << \"x\" << m2.size2() << \"]\"\n << \" time: \" << elapsed_seconds.count()\n << \"s\\x1b[0;39m\";\n #endif\n\n return AxB;\n\n }\n\n// specialization for single precision\ntemplate\ninline matrix // prod( m1, m2 )\nprod(const matrix &m1, const matrix &m2) {\n\n #ifdef DEBUG_LINALG\n auto start = std::chrono::system_clock::now();\n #endif\n\n boost::numeric::ublas::matrix AxB(m1.size1(), m2.size2());\n\n Eigen::Map mA_(&(m1.data()[0]), m1.size2(), m1.size1());\n Eigen::Map mB_(&(m2.data()[0]), m2.size2(), m2.size1());\n Eigen::Map AxB_(&(AxB.data()[0]), AxB.size2(), AxB.size1());\n\n AxB_ = mB_*mA_;\n\n #ifdef DEBUG_LINALG\n auto end = std::chrono::system_clock::now();\n std::chrono::duration elapsed_seconds = end - start;\n std::cout << \"\\n... ... ... \\x1b[0;34mEigen \"\n << \"[\" << m1.size1() << \"x\" << m1.size2() << \"]\"\n << \"*[\" << m2.size1() << \"x\" << m2.size2() << \"]\"\n << \" time: \" << elapsed_seconds.count()\n << \"s\\x1b[0;39m\";\n #endif\n\n return AxB;\n}\n\n}}}\n\nnamespace votca { namespace ctp { namespace linalg {\n\ninline void invert_symm( const ub::matrix &A, ub::matrix &V){\n throw \"Inversion of a matrix, linalg_invert, is not implemented in eigen.h\";\n}\n\n/**\n * \\brief eigenvalues of a symmetric matrix A*x=E*x\n * @param E vector of eigenvalues\n * @param V input: matrix to diagonalize\n * @param V output: eigenvectors\n *\n * This function wraps Eigen::EigenSolver\n *\n */\ninline void eigenvalues_symm(const ub::matrix &A,\n ub::vector &E,\n ub::matrix &V)\n{\n\n #ifdef DEBUG_LINALG\n auto start = std::chrono::system_clock::now();\n #endif\n\n/*\n gsl_error_handler_t *handler = gsl_set_error_handler_off();\n\tconst size_t N = A.size1();\n\n\n V.resize(N, N, false);\n \n // gsl does not handle conversion of a symmetric_matrix \n ub::matrix _A( N,N );\n //make copy of A as A is destroyed by GSL\n _A = A;\n \n\tE.resize(N, false);\n\tV.resize(N, N, false);\n\tgsl_matrix_view A_view = gsl_matrix_view_array(&_A(0,0), N, N);\n\tgsl_vector_view E_view = gsl_vector_view_array(&E(0), N);\n\tgsl_matrix_view V_view = gsl_matrix_view_array(&V(0,0), N, N);\n\tgsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(N);\n\n\tint status = gsl_eigen_symmv(&A_view.matrix, &E_view.vector, &V_view.matrix, w);\n assert(status == 0);\n\tgsl_eigen_symmv_sort(&E_view.vector, &V_view.matrix, GSL_EIGEN_SORT_VAL_ASC);\n\tgsl_eigen_symmv_free(w);\n\tgsl_set_error_handler(handler); \n \n std::cout << \"\\nREFERENCE\";\n std::cout << \"\\n A\" << A;\n std::cout << \"\\n E\" << E;\n std::cout << \"\\n V\" << V;\n std::cout << \"\\nREFERENCE\\n\";\n \n*/ \n Eigen::Map A_( &(A.data()[0]), A.size2(), A.size1() );\n\n Eigen::SelfAdjointEigenSolver es(A_.transpose());\n /*\n std::cout << \"\\nEIGEN\";\n std::cout << \"\\n E\\n\" << es.eigenvalues();\n std::cout << \"\\n V\\n\" << es.eigenvectors();\n std::cout << \"\\nEIGEN\";\n */\n \n // copy back to UBLAS objects\n Eigen::Map( &E(0), A.size2() ) = es.eigenvalues();\n Eigen::Map( &V(0,0), A.size2(), A.size1() ) = es.eigenvectors().transpose();\n \n #ifdef DEBUG_LINALG\n auto end = std::chrono::system_clock::now();\n\n std::chrono::duration elapsed_seconds = end - start;\n\n std::cout << \"\\n... ... ... \\x1b[0;34mEigen Eigenvalues\"\n << \"[\" << A.size1() << \"x\" << A.size2() << \"]\"\n << \" time: \" << elapsed_seconds.count()\n << \"s\\x1b[0;39m\";\n #endif\n}\n\n}}}\n\n\n#endif // __VOTCA_CTP_EIGEN_H\n", "meta": {"hexsha": "8cd8b44130f9316d566b160019a382d96361a86d", "size": 6314, "ext": "h", "lang": "C", "max_stars_repo_path": "include/votca/ctp/eigen.h", "max_stars_repo_name": "jimbach/ctp", "max_stars_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/votca/ctp/eigen.h", "max_issues_repo_name": "jimbach/ctp", "max_issues_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/votca/ctp/eigen.h", "max_forks_repo_name": "jimbach/ctp", "max_forks_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7286432161, "max_line_length": 97, "alphanum_fraction": 0.6037377257, "num_tokens": 1839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.42276379108944856}} {"text": "// Copyright 2018 Jeremy Mason\n//\n// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be\n// copied, modified, or distributed except according to those terms.\n\n//! \\file sb_desc.c\n//! Contains functions that actually calculate the spherical Bessel descriptors.\n\n#include // dscal\n#include // pow\n#include // uint32_t\n#include // abort\n#include \"sbessel.h\" // _sbessel\n#include \"sb_desc.h\"\n#include \"sb_matrix.h\" // sb_mat_malloc\n#include \"sb_structs.h\" // sb_vec\n#include \"sb_utility.h\" // SB_CHK_ERR\n#include \"sb_vector.h\" // sb_vec_calloc\n#include \"safety.h\"\n\n// Lookup tables used in get_radial_basis. Built using function in `tables.c`.\nstatic const double _u_data[10152] = {\n #include \"unl.tbl\"\n};\nstatic const size_t _u_n_max = 140;\n\nstatic const double _c1_data[10011] = {\n #include \"c1.tbl\"\n};\nstatic const size_t _c1_n_max = 140;\n\nstatic const double _c2_data[10011] = {\n #include \"c2.tbl\"\n};\nstatic const size_t _c2_n_max = 140;\n\n/// Calculates the radial basis functions for the spherical Bessel descriptors.\n/// Numerical efficiency depends heavily on the lookup tables defined above, \n/// allowing the function to be reduced to evaluating the recursion relations.\n///\n/// # Parameters\n/// - `gnl`: pointer to a matrix to hold the result\n/// - `r_data`: radial coordinates of the atoms\n/// - `n_max`: defines the number of descriptors calculated\n/// - `l`: order of the spherical Bessel functions\n/// - `n_atom`: number of atoms in the environment\n/// - `rc`: cutoff radius for the environment\n///\n/// # Returns\n/// A copy of `gnl`\nstatic sb_mat * get_radial_basis(\n sb_mat * gnl,\n double * r_data,\n uint32_t l,\n uint32_t n_atom,\n double rc) {\n // access lookup tables directly\n const double * u_data = _u_data + l * (2 * _u_n_max - l + 5) / 2;\n const double * c1_data = _c1_data + l * (2 * _c1_n_max - l + 3) / 2;\n const double * c2_data = _c2_data + l * (2 * _c2_n_max - l + 3) / 2;\n\n // gnl->n_cols\n const size_t n_cols = gnl->n_cols;\n\n // forward declaration of variables without initializations\n size_t n, a;\n double u0, u1, u2, d0, d1, e;\n double * g_data;\n\n // fnl built in gnl\n g_data = gnl->data;\n for (n = 0; n < n_cols; ++n) {\n for (a = 0; a < n_atom; ++a) {\n g_data[a] = c1_data[n] * _sbessel(l, r_data[a] * u_data[n])\n - c2_data[n] * _sbessel(l, r_data[a] * u_data[n + 1]);\n }\n g_data += n_atom;\n }\n sb_mat_smul(gnl, pow(rc, -1.5));\n\n // initialize quantities used for recursion\n u1 = SB_SQR(u_data[0]);\n u2 = SB_SQR(u_data[1]);\n d1 = 1.;\n\n // convert to gnl\n g_data = gnl->data;\n for (n = 1; n < n_cols; ++n) {\n u0 = u1;\n u1 = u2;\n u2 = SB_SQR(u_data[n + 1]);\n\n e = (u0 * u2) / ((u0 + u1) * (u1 + u2));\n d0 = d1;\n d1 = 1. - e / d0;\n\n g_data += n_atom;\n cblas_dscal(n_atom, 1. / sqrt(d1), g_data, 1);\n cblas_daxpy(n_atom, sqrt(e / (d1 * d0)), g_data - n_atom, 1, g_data, 1);\n }\n\n return gnl;\n}\n\n/// Calculates spherical Bessel descriptors for the given atomic environment.\n/// `desc` should contain space for the descriptors, labelled by (n, l) and\n/// ordered lexicographically. `disp` should contain the relative Cartesian \n/// coordinates of the surrouding atoms in the format `[x_1, y_1, z_1, ...]`.\n/// `weights` should contain the weights used in the construction of the\n/// neighbor density function (e.g., `[1., ...]`). `restrict` is not used to\n/// help with portability.\n///\n/// # Parameters\n/// - `desc`: pointer to an array to hold the result\n/// - `disp`: pointer to an array of the relative displacements\n/// - `weights`: pointer to an array of the atomic weights\n/// - `rc`: cutoff radius for the environment\n/// - `n_atom`: number of atoms in the environment\n/// - `n_max`: defines the number of descriptors calculated\n///\n/// # Returns\n/// A copy of `desc`\n/// \n/// # Performance\n/// The following preprocessor definitions (usually in `safety.h`) enable \n/// various safety checks:\n/// - `SAFE_MEMORY`: `desc`, `disp`, and `weights` are not `NULL`\n/// - `SAFE_FINITE`: `rc` is nonnegative\n///\n/// # Warning\n/// You are reponsible for ensuring that enough memory is allocated for the\n/// relevant arrays, and should expect undefined behavior otherwise. The\n/// lengths should be:\n/// - `desc`: `(n_max + 1) * (n_max + 2) / 2`\n/// - `disp`: at least `3 * n_atom`\n/// - `weights`: at least `n_atom`\n/// \n/// # Examples\n/// ```\n/// #include // size_t\n/// #include // printf\n/// #include // uint32_t\n/// #include \"sb_desc.h\" // sb_descriptors\n/// \n/// /// An example where `sb_descriptors()` is used to calculate the spherical\n/// /// Bessel descriptors for an atomic environment containing four atoms; the\n/// /// first and second descriptors should be `0.031870` and `0.138078`.\n/// int main(void) {\n/// // Sets the number of descriptors returned.\n/// uint32_t n_max = 4;\n/// \n/// // Allocate memory for the result.\n/// double desc[15] = { 0. };\n/// \n/// // Number of atoms in the environment.\n/// uint32_t n_atom = 4;\n/// \n/// // Displacements to the surrounding atoms in Angstroms.\n/// // [x_1, y_1, z_1, ...]\n/// double disp[12] = {\n/// 1.3681827, -1.3103517, -1.3131874,\n/// -1.5151760, 1.3360077, -1.3477119,\n/// -1.3989598, -1.2973683, 1.3679189,\n/// 1.2279369, 1.3400378, 1.4797429\n/// };\n/// \n/// // Weights for the surrounding atoms.\n/// double weights[4] = { 1., 1., 1., 1. };\n/// \n/// // Cutoff radius in Angstroms.\n/// double rc = 3.7711; \n/// \n/// sb_descriptors(desc, disp, weights, rc, n_atom, n_max);\n/// \n/// // Output the result\n/// // Labelled by (n, l), ordered lexicographically\n/// printf(\"SB descriptors:\\n\");\n/// for (size_t a = 0; a < (n_max + 1) * (n_max + 2) / 2; ++a)\n/// printf(\"%.6f\\n\", desc[a]);\n/// \n/// printf(\"Completed successfully!\\n\");\n/// }\n/// ```\ndouble * sb_descriptors(\n double * desc_arr,\n double * disp_arr,\n const double * weights_arr,\n const double rc,\n const uint32_t n_atom,\n const uint32_t n_max) {\n#ifdef SAFE_MEMORY\n SB_CHK_ERR(!desc_arr, abort(), \"sb_descriptors: desc cannot be NULL\");\n SB_CHK_ERR(!disp_arr, abort(), \"sb_descriptors: disp cannot be NULL\");\n SB_CHK_ERR(!weights_arr, abort(), \"sb_descriptors: weights cannot be NULL\");\n#endif\n#ifdef SAFE_FINITE\n SB_CHK_ERR(rc < 0., abort(), \"sb_descriptors: rc cannot be negative\");\n#endif\n // Check that n_max is within limit defined by tables\n SB_CHK_ERR(n_max > _u_n_max || n_max > _c1_n_max || n_max > _c2_n_max,\n abort(), \"sb_descriptors: n_max above limit defined by lookup tables\");\n\n // Convert raw pointers to sb_vec and sb_mat\n sb_mat * disp = malloc(sizeof(sb_mat));\n SB_CHK_ERR(!disp, abort(), \"sb_descriptors: failed to allocate disp\");\n\n disp->n_rows = 3;\n disp->n_cols = n_atom;\n disp->n_elem = 3 * n_atom;\n disp->data = disp_arr;\n\n double * data1, * data2, * data3;\n size_t a, b;\n\n // Calculate radial coordinates\n sb_vec * radius = sb_vec_calloc(n_atom, 'r');\n data1 = disp->data;\n data2 = radius->data;\n for (a = 0; a < n_atom; ++a) {\n for (b = 0; b < 3; ++b) {\n *data2 += SB_SQR(data1[b]);\n }\n data1 += 3;\n data2 += 1;\n }\n sb_vec_sqrt(radius);\n\n // Normalize displacement vectors\n sb_mat_vdiv(disp, radius, 'c');\n sb_vec_smul(radius, 1. / rc);\n\n // Calculate angle cosines\n sb_mat * gamma = sb_mat_malloc(n_atom, n_atom);\n sb_mat_mm_mul(gamma, disp, disp, \"tn\");\n\n // Legendre polynomials\n sb_mat * * lp = malloc((n_max + 1) * sizeof(sb_mat *));\n SB_CHK_ERR(!lp, abort(), \"sb_descriptors: failed to allocate lp\");\n for (a = 0; a <= n_max; ++a) {\n lp[a] = sb_mat_malloc(n_atom, n_atom);\n }\n\n sb_mat_set_all(lp[0], 1.);\n sb_mat_memcpy(lp[1], gamma);\n for (a = 2; a <= n_max; ++a) { // l = a\n sb_mat_memcpy(lp[a], gamma);\n sb_mat_pmul(lp[a], lp[a - 1]);\n sb_mat_smul(lp[a], (2. * a - 1.) / (a - 1.));\n sb_mat_psub(lp[a], lp[a - 2]);\n sb_mat_smul(lp[a], (a - 1.) / a);\n }\n\n // Include multiplier here to simplify calculation below\n for (a = 0; a <= n_max; ++a) { // l = a\n sb_mat_smul(lp[a], (2. * a + 1.) / 12.566370614359172);\n }\n \n // Radial basis functions\n sb_mat * * gnl = malloc((n_max + 1) * sizeof(sb_mat *));\n SB_CHK_ERR(!gnl, abort(), \"sb_descriptors: failed to allocate gnl\");\n for (a = 0; a <= n_max; ++a) { // l = a\n gnl[a] = sb_mat_malloc(n_atom, n_max - a + 1);\n get_radial_basis(gnl[a], radius->data, a, n_atom, rc);\n // Scale by the weights\n for (b = 0; b < n_atom; ++b) {\n cblas_dscal(gnl[a]->n_cols, weights_arr[b], gnl[a]->data + b, n_atom);\n }\n }\n\n // radius can be used for workspace\n data1 = radius->data;\n for (a = 0; a <= n_max; ++a) { // l = a\n data2 = lp[a]->data;\n data3 = gnl[a]->data;\n for (b = a; b <= n_max; ++b) { // n = b\n cblas_dgemv(CblasColMajor, CblasNoTrans, n_atom, n_atom,\n 1., data2, n_atom, data3 + (b - a) * n_atom, 1, 0., data1, 1);\n desc_arr[b * (b + 1) / 2 + a] = cblas_ddot(n_atom, data3 + (b - a) * n_atom, 1, data1, 1);\n }\n }\n\n // Free memory\n for (a = 0; a <= n_max; ++a) {\n SB_MAT_FREE_ALL(lp[a], gnl[a]);\n }\n SB_FREE_ALL(disp, lp, gnl);\n SB_VEC_FREE_ALL(radius);\n SB_MAT_FREE_ALL(gamma);\n\n return desc_arr;\n}\n", "meta": {"hexsha": "eb2e3fb03e33f5f3257392acb30e70bc6b9a5e4e", "size": 9440, "ext": "c", "lang": "C", "max_stars_repo_path": "src/sb_desc.c", "max_stars_repo_name": "harharkh/sb_desc", "max_stars_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-07-08T22:34:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T20:06:47.000Z", "max_issues_repo_path": "src/sb_desc.c", "max_issues_repo_name": "harharkh/sb_desc", "max_issues_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T06:53:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T06:53:41.000Z", "max_forks_repo_path": "src/sb_desc.c", "max_forks_repo_name": "harharkh/sb_desc", "max_forks_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1088435374, "max_line_length": 96, "alphanum_fraction": 0.6181144068, "num_tokens": 3058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4223020123211147}} {"text": "/******************************************************************************\nCosmoLike Configuration Space Covariances for Projected Galaxy 2-Point Statistics\nhttps://github.com/CosmoLike/CosmoCov\nby CosmoLike developers\n******************************************************************************/\n\n#include \n#include \n#include \n#include \n// #include \"../class/include/class.h\"\n\n#include \n#include \n#include \n#include \n\n//void omega_a(double aa,double *om_m,double *om_v);\ndouble omv_vareos(double a);\nstatic inline double hoverh0(double a);\ndouble growfac(double a);\n//int func_for_growfac(double a,const double y[],double f[],void *params);\ndouble Tsqr_EH_wiggle(double khoverMPC);\n//double int_for_sigma_r_sqr(double k, void * args);\ndouble sigma_r_sqr();\n//double Delta_L_wiggle(double k);\n//double Delta_lin_wiggle(double k,double a);\ndouble p_lin(double k,double a);\n//double int_sig_R_knl(double logk, void *args);\n//double int_neff(double lnk, void *args);\n//double int_cur(double lnk, void *args);\n//void nonlin_scale(double amp, double *R_NL, double *neff, double *Curv);\n//double Halofit(double k, double amp, double omm, double omv,double w_z, double R_NL, double neff,double Curv, double P_delta_Lin);\n//void Delta_halofit(double **table_P_NL,double logkmin, double logkmax, double dk, double da);\n//double Delta_NL_Halofit(double k_NL, double a); //k in h/Mpc\ndouble Pdelta(double k_NL,double a); //k in coverH0 units\n\n//double int_for_chi(double a,void * args);\ndouble f_K(double chi);\ndouble chi(double a);\ndouble a_chi(double chi1);\n// extern void emu(double *xstar, double *ystar, double *kstar);\n\n//c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//variable Omega_v\n//c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ndouble omv_vareos(double a)\n{\n return(cosmology.Omega_v*exp(-3.*((cosmology.w0+cosmology.wa+1.)*log(a)+cosmology.wa*(1.-a))));\n}\n\n//c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//c evolution of omega matter and omega lamda with expansion factor\n\nvoid omega_a(double aa,double *om_m,double *om_v)\n{\n double a2,omega_curv;\n a2=aa*aa;\n omega_curv=1.0-cosmology.Omega_m- cosmology.Omega_v;\n *om_m=cosmology.Omega_m /(cosmology.Omega_m +aa*(omv_vareos(aa) *a2 +omega_curv));\n *om_v=omv_vareos(aa)*a2*aa/(cosmology.Omega_m+aa*(a2*omv_vareos(aa) +omega_curv));\n}\n//c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//growth factor including Dark energy parameters w0, wa\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n//function for growfac (DGL)\nint func_for_growfac(double a,const double y[],double f[],void *params)\n{\n //double *p=(double *)params;\n if (a == 0) {\n printf(\"a=0 in function 'func_for_growfac'!\\n\");\n exit(1);\n }\n double aa=a*a;\n double omegam=cosmology.Omega_m/(aa*a);\n double omegav=omv_vareos(a);\n double hub = hoverh0(a);\n double one_plus_mg_mu = 1.;\n hub = hub*hub;\n f[0]=y[1];\n if(cosmology.MGmu != 0){\n one_plus_mg_mu += cosmology.MGmu*omegav/hub/cosmology.Omega_v;\n }\n f[1]=y[0]*3.*cosmology.Omega_m/(2.*hub*aa*aa*a)*one_plus_mg_mu-y[1]/a*(2.-(omegam+(3.*(cosmology.w0+cosmology.wa*(1.-a))+1)*omegav)/(2.*hub));\n return GSL_SUCCESS;\n}\n\nstatic inline double hoverh0(double a){\n return sqrt(cosmology.Omega_m /(a*a*a) + (1.-cosmology.Omega_m -cosmology.Omega_v )/(a*a) + omv_vareos(a) );\n}\n\ndouble growfac(double a)\n{\n const double MINA=1.e-8;\n static cosmopara C;\n static double *ai;\n static double *table;\n double res;\n \n gsl_interp *intf=gsl_interp_alloc(gsl_interp_linear,Ntable.N_a);\n gsl_interp_accel *acc=gsl_interp_accel_alloc();\n \n if (recompute_expansion(C))\n {\n\n if(table!=0) free_double_vector(table,0, Ntable.N_a-1);\n if(ai!=0) free_double_vector(ai,0, Ntable.N_a-1); \n ai=create_double_vector(0, Ntable.N_a-1);\n table=create_double_vector(0, Ntable.N_a-1);\n \n int i;\n\n const gsl_odeiv_step_type *T=gsl_odeiv_step_rkf45;\n gsl_odeiv_step *s=gsl_odeiv_step_alloc(T,2);\n gsl_odeiv_control *c=gsl_odeiv_control_y_new(1.e-6,0.0);\n gsl_odeiv_evolve *e=gsl_odeiv_evolve_alloc(2);\n \n double t=MINA; //start a\n double t1=1.1; //final a\n double h=1.e-6; //initial step size\n double y[2]={MINA,MINA}; //initial conditions\n double norm;\n double par[0]={};\n gsl_odeiv_system sys={func_for_growfac,NULL,2,&par};\n \n for (i=1;i<=Ntable.N_a;i++) {\n ai[i-1]=i*t1/(1.*Ntable.N_a);\n while(t0.0)){\n fprintf(stderr,\"failed with sigma_r_sqr = %le\\n\", res);\n }\n assert(res>0.0);\n return res;\n}\n\n\n\ndouble Delta_L_wiggle(double k)\n{\n static cosmopara C;\n \n static double *table_P;\n static double dk = .0, logkmin = .0, logkmax = .0;\n \n double klog,f1,norm;\n int i; \n \n if (k < limits.k_min_mpc || k > limits.k_max_mpc){\n norm=cosmology.sigma_8*cosmology.sigma_8/sigma_r_sqr(); \n \n return norm*pow(k,cosmology.n_spec+ 0.5*cosmology.alpha_s*log(k/0.05)+3.0)*Tsqr_EH_wiggle(k);\n //printf(\"outside Delta_L_tab\\n\"); \n }\n else{ \n if (recompute_Delta(C))\n {\n if (cosmology.M_nu > 0){\n printf(\"Implementation of EH transfer function does not support massive neutrinos\\n EXIT\\n\");\n }\n update_cosmopara(&C);\n norm=cosmology.sigma_8*cosmology.sigma_8/sigma_r_sqr();\n \n if(table_P!=0) free_double_vector(table_P,0, Ntable.N_k_lin-1);\n table_P=create_double_vector(0, Ntable.N_k_lin-1);\n \n logkmin = log(limits.k_min_mpc);\n logkmax = log(limits.k_max_mpc);\n dk = (logkmax - logkmin)/(Ntable.N_k_lin-1.);\n klog = logkmin;\n \n for (i=0; i= 0.99999){a =0.99999;}\n if (recompute_cosmo3D(C)){\n update_cosmopara(&C);\n if (table_P_Lz!=0) free_double_matrix(table_P_Lz,0, Ntable.N_a-1, 0, Ntable.N_k_lin-1);\n table_P_Lz = create_double_matrix(0, Ntable.N_a-1, 0, Ntable.N_k_lin-1);\n grow0=growfac(1.);\n da = (1. - limits.a_min)/(Ntable.N_a-1.);\n aa = limits.a_min;\n for (i=0; i1.0) aa=1.0;\n amp=growfac(aa)/grow0;\n ampsqr=amp*amp;\n \n logkmin = log(limits.k_min_mpc);\n logkmax = log(limits.k_max_mpc);\n dk = (logkmax - logkmin)/(Ntable.N_k_lin-1.);\n klog = logkmin;\n for (j=0; j exp(logkmax)) return 0.0;\n klog = log(k/cosmology.coverH0);\n val = interpol2d(table_P_Lz, Ntable.N_a, limits.a_min, 1., da, a, Ntable.N_k_lin, logkmin, logkmax, dk, klog, 3.0+cosmology.n_spec, 0.0);\n if(isnan(val) || (k==0)) return 0.0;\n return 2.0*constants.pi_sqr*exp(val)/k/k/k; \n}\n\n\ndouble int_sig_R_knl(double lnk, void *args) // tak12 A4\n{\n double krsqr;\n \n double *params= (double *) args;\n double Rscale=params[0];\n //printf(\"Rscale %le k %le\\n\",Rscale,exp(lnk));\n krsqr= SQR(exp(lnk)*Rscale);\n return Delta_L_wiggle(exp(lnk))*exp(-krsqr);\n}\n\n\ndouble int_neff(double lnk, void *args) //tak12 A5\n{\n double krsqr;\n double *params= (double *) args;\n double Rscale=params[0];\n krsqr= SQR(exp(lnk)*Rscale);\n return Delta_L_wiggle(exp(lnk))*2.0*krsqr*exp(-krsqr); //see S03 eq. 59\n}\n\n\ndouble int_cur(double lnk, void *args) //tak12 A5\n{\n double krsqr;\n double *params= (double *) args;\n double Rscale=params[0];\n krsqr= SQR(exp(lnk)*Rscale);\n return Delta_L_wiggle(exp(lnk))*4.0*krsqr*(1.0-krsqr)*exp(-krsqr); // S03 eq.60\n}\n\n\n//iterative calculation of the nonlinear scale as defined in tak12 A4\nvoid nonlin_scale(double amp, double *R_NL, double *neff, double *Curv)\n{\n double sig_R,kmax,logkmax,sig_R_noamp,neffplus3;\n int iterstep; \n const int itermax = 40;\n int converged=0;\n double array[1];\n double logRmin = -3.0;\n double logRmax = 4.0; \n\n iterstep=0; \n while(converged==0)\n { \n array[0]=pow(10.,(logRmin+logRmax)/2.0);\n \n //flexible upper limit of integration depending on drop-off of filter function\n kmax = sqrt(5.*log(10.))/array[0];\n if (kmax<8000.0) logkmax = log(8000.0);\n sig_R_noamp=sqrt(int_gsl_integrate_medium_precision(int_sig_R_knl,(void*)array,-4.5,logkmax,NULL,512)); //integral goes over ln k exponent correspond to k_min~0.011\n \n sig_R=amp*sig_R_noamp; \n if (sig_R>1.0) logRmin=log10(array[0]);\n if (sig_R<1.0) logRmax=log10(array[0]);\n iterstep=iterstep+1;\n if(fabs(sig_R-1.0) < 0.0001 || iterstep>itermax) converged=1; \n } \n *R_NL=array[0]; //R where sig_R==1\n neffplus3=int_gsl_integrate_medium_precision(int_neff,(void*)array,-4.5,logkmax,NULL,512)/sig_R_noamp/sig_R_noamp;\n *neff= neffplus3 - 3.0;\n *Curv= int_gsl_integrate_medium_precision(int_cur,(void*)array,-4.5,logkmax,NULL,512)/sig_R_noamp/sig_R_noamp + SQR(neffplus3);\n \n //printf(\"%d %le\\n\",iterstep,amp); \n} \n\n\ndouble Halofit(double k, double amp, double omm, double omv,double w_z, double R_NL, double neff,double Curv, double P_delta_Lin)\n{\n double y_scale,n2eff,n3eff,n4eff;\n double a_n,b_n,c_n,gamma_n,alpha_n,beta_n,nu_n,f1,f2,f3;\n \n double Delta_H,Delta_H_Prime,Delta_Q;\n //determine nonlinear scale, neff and curvature, see tak12 A4, A5\n y_scale=k*R_NL;\n \n n2eff=neff*neff;\n n3eff=n2eff*neff;\n n4eff=n2eff*n2eff;\n \n //calculate coefficients \n a_n = pow(10.,1.5222+2.8553*neff + 2.3706*n2eff+0.9903*n3eff+0.2250*n4eff-0.6038*Curv+0.1749*omv*(1.0+w_z));\n b_n = pow(10., -0.5642+0.5864*neff + 0.5716*n2eff-1.5474*Curv +0.2279*omv*(1.0+w_z));\n c_n = pow(10., 0.3698+ 2.0404*neff + 0.8161*n2eff+0.5869*Curv);\n gamma_n = 0.1971-0.0843*neff + 0.8460*Curv;\n alpha_n = fabs(6.0835 + 1.3373*neff - 0.1959*n2eff - 5.5274*Curv);\n beta_n = 2.0379 - 0.7354*neff + 0.3157*n2eff + 1.2490*n3eff + 0.3980*n4eff - 0.1682*Curv;\n nu_n = pow(10,5.2105+3.6902*neff);\n \n f1 = pow(omm,(-0.0307));\n f2 = pow(omm,(-0.0585));\n f3 = pow(omm,(0.0743)); \n \n //TwoHaloTerm\n Delta_Q=P_delta_Lin*(pow((1.0+P_delta_Lin),beta_n)/(1.0+alpha_n*P_delta_Lin))*exp(-(y_scale/4.0+y_scale*y_scale/8.0));\n //OneHaloterm\n Delta_H_Prime=(a_n*pow(y_scale,3.0*f1))/(1.0+b_n*pow(y_scale,f2)+pow(c_n*f3*y_scale,3.0-gamma_n));\n Delta_H=Delta_H_Prime/(1.0+nu_n*pow(y_scale,-2.0)); // using mu=0.0 Tak A12\n //printf(\"Delta_Q %le Delta_H %le\\n\",Delta_Q,Delta_H);\n return Delta_H+Delta_Q;\n}\n\n\n\n\nvoid Delta_halofit(double **table_P_NL,double logkmin, double logkmax, double dk, double da)\n{ \n double rk,omm,omv,w_z,amp,grow0,aa,klog;\n double R_NL,Curv,neff,P_delta,P_delta_Lin;\n int i,j;\n \n grow0=growfac(1.);\n aa = limits.a_min;\n //binning in k and a must be the same as in emu\n for (i=0; i1.0) aa=1.0;\n omega_a(aa,&omm,&omv);\n w_z=cosmology.w0+cosmology.wa*(1.-aa);\n amp=growfac(aa)/grow0;\n nonlin_scale(amp, &R_NL, &neff, &Curv);\n //printf(\"%le %le %le %le\\n\",aa,R_NL,neff,Curv);\n klog = logkmin;\n for (j=0; j1.0) aa=1.0;\n omega_a(aa,&omm,&omv);\n amp=growfac(aa)/grow0;\n nonlin_scale(amp, &R_NL, &neff, &Curv);\n table[i] = 1./R_NL;\n }\n }\n res = interpol(table, Ntable.N_a, limits.a_min, 1., da, a, 0.0, 0.0); \n return res;\n}\n\n\n/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/\n//Pdelta is called with k in units H0/c since the comoving distance chi is in units c/H0. Upstream Pdelta all routines are in h/mpc \ndouble Pdelta(double k_NL,double a)\n{ \n static int P_type = -1;\n if (P_type == -1){\n if (strcmp(pdeltaparams.runmode,\"Halofit\")==0) P_type = 0;\n if (strcmp(pdeltaparams.runmode,\"halofit\")==0) P_type = 0;\n // if (strcmp(pdeltaparams.runmode,\"emu\")==0) P_type = 1;\n // if (strcmp(pdeltaparams.runmode,\"emu_only\")==0) P_type = 2;\n if (strcmp(pdeltaparams.runmode,\"linear\")==0) P_type = 3;\n // if (strcmp(pdeltaparams.runmode,\"CLASS\")==0) P_type = 4;\n // if (strcmp(pdeltaparams.runmode,\"class\")==0) P_type = 4;\n if (strcmp(pdeltaparams.runmode,\"cosmo_sim_test\") ==0) P_type = 5;\n\n }\n\n //printf(\"%s set\\n\",pdeltaparams.runmode);\n double pdelta = 0.,kintern=k_NL/cosmology.coverH0,error,k_nonlin,res;\n int status;\n switch (P_type){\n case 0: pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)/k_NL/k_NL/k_NL; break;\n // case 1: pdelta=2.0*constants.pi_sqr*Delta_NL_emu(kintern,a)/k_NL/k_NL/k_NL; break;\n // case 2: pdelta=2.0*constants.pi_sqr*Delta_NL_emu_only(kintern,a)/k_NL/k_NL/k_NL; break;\n case 3: pdelta=p_lin(k_NL,a); break;\n // case 4: pdelta=p_class(k_NL,a,1, &status); break;\n case 5: k_nonlin=nonlinear_scale_computation(a);\n if (kintern<0.01) pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)/k_NL/k_NL/k_NL;\n else{ \n error=0.01*pow((pdeltaparams.DIFF_A*kintern/k_nonlin),pdeltaparams.DIFF_n);\n pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)*(1.0+error)/k_NL/k_NL/k_NL;\n }\n break;\n default: \n printf(\"cosmo3D:Pdelta: %s Pdelta runmode not defined\\n\",pdeltaparams.runmode);\n printf(\"using Halofit (standard)\\n\");\n pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)/k_NL/k_NL/k_NL;\n break;\n }\n\n// double z = 1./a -1 ; \n//\t if (z > 4.) { \n//\t\t printf(\"\tz:%lf a:%lf \tk_Mpc:%lf PkRatio:%lf \\n\",z,a,kintern,PkRatio_baryons(kintern, a));\n//\t }\n \n // if (bary.isPkbary==1) pdelta = pdelta*PkRatio_baryons(kintern, a);\n return pdelta; \n} \n\n/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/\n\n/*============================================================\n *see BS 2.41 bzw Logbook for detailed calculation of chi from a.*/\n\ndouble int_for_chi(double a, void * args){\n //double res,asqr;\n //asqr=a*a;\n //res= 1./sqrt(a*cosmology.Omega_m + asqr*(1.-cosmology.Omega_m -cosmology.Omega_v ) + asqr*asqr*omv_vareos(a));\n //return res;\n return 1./(a*a*hoverh0(a)); //changed to call of hoverh0 to be ready for other parametrizations\n}\n\n/*for the calculation of chi we have to integrate from a(z2)=a up to a(z1)=1, which means todays expansion factor*/\t\ndouble chi(double a)\n{\n static cosmopara C;\n static double *table;\n static double da = 0.;\n double aa,res;\n int i;\n double array[1];\n \n if (recompute_expansion(C)){\n update_cosmopara(&C);\n da = (1.-limits.a_min)/(Ntable.N_a-1.);\n aa = limits.a_min;\n if (table!=0) free_double_vector(table, 0, Ntable.N_a-1);\n table = create_double_vector(0, Ntable.N_a-1);\n for (i=0; i chi_max){printf(\"called a_chi(chi) with chi > chi(limits.a_min\\nEXIT\\n\");exit(1);}\n return gsl_spline_eval(a_spline,chi1,a_accel);\n}\n\n/*===============================calculating the angular diameter distance f_K BS01 2.4, 2.30: f_K is a radial function that, depending on the curvature of the Universe, is a trigonometric, linear, or hyperbolic function of chi */\ndouble f_K(double chi)\n{ \n double K, K_h, f;\n K = (cosmology.Omega_m + cosmology.Omega_v - 1.);\n if (K > precision.medium) { /* open */\n K_h = sqrt(K); // K in units H0/c see BS eq. 2.30\n f = 1./K_h*sin(K_h*chi);\n //printf(\"open\\n\");\n } else if (K < -precision.medium) { /* closed */\n K_h = sqrt(-K); \n f = 1./K_h*sinh(K_h*chi);\n //printf(\"closed K=%le %le %le\\n\",K,cosmology.Omega_m,cosmology.Omega_v);\n } else { /* flat */\n f = chi;\n //printf(\"flatK=%le %le %le\\n\",K,cosmology.Omega_m,cosmology.Omega_v);\n }\n return f;\n}\n\n\n\n\n", "meta": {"hexsha": "8022360d78f07e7d14e8dd1a7d1b1768c1158a90", "size": 24529, "ext": "c", "lang": "C", "max_stars_repo_path": "cosmolike_core/theory/cosmo3D.c", "max_stars_repo_name": "joezuntz/CosmoCov", "max_stars_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-04-14T00:46:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:39:07.000Z", "max_issues_repo_path": "cosmolike_core/theory/cosmo3D.c", "max_issues_repo_name": "joezuntz/CosmoCov", "max_issues_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-12T19:43:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T16:27:09.000Z", "max_forks_repo_path": "cosmolike_core/theory/cosmo3D.c", "max_forks_repo_name": "joezuntz/CosmoCov", "max_forks_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T20:17:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:30:53.000Z", "avg_line_length": 35.6526162791, "max_line_length": 249, "alphanum_fraction": 0.6468262057, "num_tokens": 8813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709252, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4223019058898012}} {"text": "/* multifit/lmpar.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n\n#include \"qrsolv.c\"\n\nstatic size_t\ncount_nsing (const gsl_matrix * r)\n{\n /* Count the number of nonsingular entries. Returns the index of the\n first entry which is singular. */\n\n size_t n = r->size2;\n size_t i;\n\n for (i = 0; i < n; i++)\n {\n double rii = gsl_matrix_get (r, i, i);\n\n if (rii == 0)\n {\n break;\n }\n }\n\n return i;\n}\n\n\nstatic void\ncompute_newton_direction (const gsl_matrix * r, const gsl_permutation * perm,\n const gsl_vector * qtf, gsl_vector * x)\n{\n\n /* Compute and store in x the Gauss-Newton direction. If the\n Jacobian is rank-deficient then obtain a least squares\n solution. */\n\n const size_t n = r->size2;\n size_t i, j, nsing;\n\n for (i = 0 ; i < n ; i++)\n {\n double qtfi = gsl_vector_get (qtf, i);\n gsl_vector_set (x, i, qtfi);\n }\n\n nsing = count_nsing (r);\n\n#ifdef DEBUG\n printf(\"nsing = %d\\n\", nsing);\n printf(\"r = \"); gsl_matrix_fprintf(stdout, r, \"%g\"); printf(\"\\n\");\n printf(\"qtf = \"); gsl_vector_fprintf(stdout, x, \"%g\"); printf(\"\\n\");\n#endif\n\n for (i = nsing; i < n; i++)\n {\n gsl_vector_set (x, i, 0.0);\n }\n\n if (nsing > 0)\n {\n for (j = nsing; j > 0 && j--;)\n {\n double rjj = gsl_matrix_get (r, j, j);\n double temp = gsl_vector_get (x, j) / rjj;\n \n gsl_vector_set (x, j, temp);\n \n for (i = 0; i < j; i++)\n {\n double rij = gsl_matrix_get (r, i, j);\n double xi = gsl_vector_get (x, i);\n gsl_vector_set (x, i, xi - rij * temp);\n }\n }\n }\n\n gsl_permute_vector_inverse (perm, x);\n}\n\nstatic void\ncompute_newton_correction (const gsl_matrix * r, const gsl_vector * sdiag,\n const gsl_permutation * p, gsl_vector * x,\n double dxnorm,\n const gsl_vector * diag, gsl_vector * w)\n{\n size_t n = r->size2;\n size_t i, j;\n\n for (i = 0; i < n; i++)\n {\n size_t pi = gsl_permutation_get (p, i);\n\n double dpi = gsl_vector_get (diag, pi);\n double xpi = gsl_vector_get (x, pi);\n\n gsl_vector_set (w, i, dpi * (dpi * xpi) / dxnorm);\n }\n\n for (j = 0; j < n; j++)\n {\n double sj = gsl_vector_get (sdiag, j);\n double wj = gsl_vector_get (w, j);\n\n double tj = wj / sj;\n\n gsl_vector_set (w, j, tj);\n\n for (i = j + 1; i < n; i++)\n {\n double rij = gsl_matrix_get (r, i, j);\n double wi = gsl_vector_get (w, i);\n\n gsl_vector_set (w, i, wi - rij * tj);\n }\n }\n}\n\nstatic void\ncompute_newton_bound (const gsl_matrix * r, const gsl_vector * x, \n double dxnorm, const gsl_permutation * perm, \n const gsl_vector * diag, gsl_vector * w)\n{\n /* If the jacobian is not rank-deficient then the Newton step\n provides a lower bound for the zero of the function. Otherwise\n set this bound to zero. */\n\n size_t n = r->size2;\n\n size_t i, j;\n\n size_t nsing = count_nsing (r);\n\n if (nsing < n)\n {\n gsl_vector_set_zero (w);\n return;\n }\n\n for (i = 0; i < n; i++)\n {\n size_t pi = gsl_permutation_get (perm, i);\n\n double dpi = gsl_vector_get (diag, pi);\n double xpi = gsl_vector_get (x, pi);\n\n gsl_vector_set (w, i, dpi * (dpi * xpi / dxnorm));\n }\n\n for (j = 0; j < n; j++)\n {\n double sum = 0;\n\n for (i = 0; i < j; i++)\n {\n sum += gsl_matrix_get (r, i, j) * gsl_vector_get (w, i);\n }\n\n {\n double rjj = gsl_matrix_get (r, j, j);\n double wj = gsl_vector_get (w, j);\n\n gsl_vector_set (w, j, (wj - sum) / rjj);\n }\n }\n}\n\n/* compute scaled gradient g = D^{-1} J^T f (see More' eq 7.2) */\nstatic void\ncompute_gradient_direction (const gsl_matrix * r, const gsl_permutation * p,\n const gsl_vector * qtf, const gsl_vector * diag,\n gsl_vector * g)\n{\n const size_t n = r->size2;\n\n size_t i, j;\n\n for (j = 0; j < n; j++)\n {\n double sum = 0;\n\n for (i = 0; i <= j; i++)\n {\n sum += gsl_matrix_get (r, i, j) * gsl_vector_get (qtf, i);\n }\n\n {\n size_t pj = gsl_permutation_get (p, j);\n double dpj = gsl_vector_get (diag, pj);\n\n gsl_vector_set (g, j, sum / dpj);\n }\n }\n}\n\n/* compute gradient g = J^T f */\nstatic void\ncompute_gradient (const gsl_matrix * r, const gsl_vector * qtf,\n gsl_vector * g)\n{\n const size_t n = r->size2;\n\n size_t i, j;\n\n for (j = 0; j < n; j++)\n {\n double sum = 0;\n\n for (i = 0; i <= j; i++)\n {\n sum += gsl_matrix_get (r, i, j) * gsl_vector_get (qtf, i);\n }\n\n gsl_vector_set (g, j, sum);\n }\n}\n\nstatic int\nlmpar (gsl_matrix * r, const gsl_permutation * perm, const gsl_vector * qtf,\n const gsl_vector * diag, double delta, double * par_inout,\n gsl_vector * newton, gsl_vector * gradient, gsl_vector * sdiag, \n gsl_vector * x, gsl_vector * w)\n{\n double dxnorm, gnorm, fp, fp_old, par_lower, par_upper, par_c;\n\n double par = *par_inout;\n\n size_t iter = 0;\n\n#ifdef DEBUG\n printf(\"ENTERING lmpar\\n\");\n#endif\n\n\n compute_newton_direction (r, perm, qtf, newton);\n\n#ifdef DEBUG\n printf (\"newton = \");\n gsl_vector_fprintf (stdout, newton, \"%g\");\n printf (\"\\n\");\n\n printf (\"diag = \");\n gsl_vector_fprintf (stdout, diag, \"%g\");\n printf (\"\\n\");\n#endif\n\n /* Evaluate the function at the origin and test for acceptance of\n the Gauss-Newton direction. */\n\n dxnorm = scaled_enorm (diag, newton);\n\n fp = dxnorm - delta;\n\n#ifdef DEBUG\n printf (\"dxnorm = %g, delta = %g, fp = %g\\n\", dxnorm, delta, fp);\n#endif\n\n if (fp <= 0.1 * delta)\n {\n gsl_vector_memcpy (x, newton);\n#ifdef DEBUG\n printf (\"took newton (fp = %g, delta = %g)\\n\", fp, delta);\n#endif\n\n *par_inout = 0;\n\n return GSL_SUCCESS;\n }\n\n#ifdef DEBUG\n printf (\"r = \");\n gsl_matrix_fprintf (stdout, r, \"%g\");\n printf (\"\\n\");\n\n printf (\"newton = \");\n gsl_vector_fprintf (stdout, newton, \"%g\");\n printf (\"\\n\");\n\n printf (\"dxnorm = %g\\n\", dxnorm);\n#endif\n\n\n compute_newton_bound (r, newton, dxnorm, perm, diag, w);\n\n#ifdef DEBUG\n printf(\"perm = \"); gsl_permutation_fprintf(stdout, perm, \"%d\");\n\n printf (\"diag = \");\n gsl_vector_fprintf (stdout, diag, \"%g\");\n printf (\"\\n\");\n\n printf (\"w = \");\n gsl_vector_fprintf (stdout, w, \"%g\");\n printf (\"\\n\");\n#endif\n\n\n {\n double wnorm = enorm (w);\n double phider = wnorm * wnorm;\n\n /* w == zero if r rank-deficient, \n then set lower bound to zero form MINPACK, lmder.f \n Hans E. Plesser 2002-02-25 (hans.plesser@itf.nlh.no) */\n if ( wnorm > 0 )\n par_lower = fp / (delta * phider);\n else\n par_lower = 0.0;\n }\n\n#ifdef DEBUG\n printf(\"par = %g\\n\", par );\n printf(\"par_lower = %g\\n\", par_lower);\n#endif\n\n compute_gradient_direction (r, perm, qtf, diag, gradient);\n\n gnorm = enorm (gradient);\n\n#ifdef DEBUG\n printf(\"gradient = \"); gsl_vector_fprintf(stdout, gradient, \"%g\"); printf(\"\\n\");\n printf(\"gnorm = %g\\n\", gnorm);\n#endif\n\n par_upper = gnorm / delta;\n\n if (par_upper == 0)\n {\n par_upper = GSL_DBL_MIN / GSL_MIN_DBL(delta, 0.1);\n }\n\n#ifdef DEBUG\n printf(\"par_upper = %g\\n\", par_upper);\n#endif\n\n if (par > par_upper)\n {\n#ifdef DEBUG\n printf(\"set par to par_upper\\n\");\n#endif\n\n par = par_upper;\n }\n else if (par < par_lower)\n {\n#ifdef DEBUG\n printf(\"set par to par_lower\\n\");\n#endif\n\n par = par_lower;\n }\n\n if (par == 0)\n {\n par = gnorm / dxnorm;\n#ifdef DEBUG\n printf(\"set par to gnorm/dxnorm = %g\\n\", par);\n#endif\n\n }\n\n /* Beginning of iteration */\n\niteration:\n\n iter++;\n\n#ifdef DEBUG\n printf(\"lmpar iteration = %d\\n\", iter);\n#endif\n\n#ifdef BRIANSFIX\n /* Seems like this is described in the paper but not in the MINPACK code */\n\n if (par < par_lower || par > par_upper) \n {\n par = GSL_MAX_DBL (0.001 * par_upper, sqrt(par_lower * par_upper));\n }\n#endif\n\n /* Evaluate the function at the current value of par */\n\n if (par == 0)\n {\n par = GSL_MAX_DBL (0.001 * par_upper, GSL_DBL_MIN);\n#ifdef DEBUG\n printf(\"par = 0, set par to = %g\\n\", par);\n#endif\n\n }\n\n /* Compute the least squares solution of [ R P x - Q^T f, sqrt(par) D x]\n for A = Q R P^T */\n\n#ifdef DEBUG\n printf (\"calling qrsolv with par = %g\\n\", par);\n#endif\n\n {\n double sqrt_par = sqrt(par);\n\n qrsolv (r, perm, sqrt_par, diag, qtf, x, sdiag, w);\n }\n\n dxnorm = scaled_enorm (diag, x);\n\n fp_old = fp;\n\n fp = dxnorm - delta;\n\n#ifdef DEBUG\n printf (\"After qrsolv dxnorm = %g, delta = %g, fp = %g\\n\", dxnorm, delta, fp);\n printf (\"sdiag = \") ; gsl_vector_fprintf(stdout, sdiag, \"%g\"); printf(\"\\n\");\n printf (\"x = \") ; gsl_vector_fprintf(stdout, x, \"%g\"); printf(\"\\n\");\n printf (\"r = \") ; gsl_matrix_fprintf(stdout, r, \"%g\"); printf(\"\\nXXX\\n\");\n#endif\n\n /* If the function is small enough, accept the current value of par */\n\n if (fabs (fp) <= 0.1 * delta)\n goto line220;\n\n if (par_lower == 0 && fp <= fp_old && fp_old < 0)\n goto line220;\n\n /* Check for maximum number of iterations */\n\n if (iter == 10)\n goto line220;\n\n /* Compute the Newton correction */\n\n compute_newton_correction (r, sdiag, perm, x, dxnorm, diag, w);\n\n#ifdef DEBUG\n printf (\"newton_correction = \");\n gsl_vector_fprintf(stdout, w, \"%g\"); printf(\"\\n\");\n#endif\n\n {\n double wnorm = enorm (w);\n par_c = fp / (delta * wnorm * wnorm);\n }\n\n#ifdef DEBUG\n printf(\"fp = %g\\n\", fp);\n printf(\"par_lower = %g\\n\", par_lower);\n printf(\"par_upper = %g\\n\", par_upper);\n printf(\"par_c = %g\\n\", par_c);\n#endif\n\n\n /* Depending on the sign of the function, update par_lower or par_upper */\n\n if (fp > 0)\n {\n if (par > par_lower)\n {\n par_lower = par;\n#ifdef DEBUG\n printf(\"fp > 0: set par_lower = par = %g\\n\", par);\n#endif\n\n }\n }\n else if (fp < 0)\n {\n if (par < par_upper)\n {\n#ifdef DEBUG\n printf(\"fp < 0: set par_upper = par = %g\\n\", par);\n#endif\n par_upper = par;\n }\n }\n\n /* Compute an improved estimate for par */\n\n#ifdef DEBUG\n printf(\"improved estimate par = MAX(%g, %g) \\n\", par_lower, par+par_c);\n#endif\n\n par = GSL_MAX_DBL (par_lower, par + par_c);\n\n#ifdef DEBUG\n printf(\"improved estimate par = %g \\n\", par);\n#endif\n\n\n goto iteration;\n\nline220:\n\n#ifdef DEBUG\n printf(\"LEAVING lmpar, par = %g\\n\", par);\n#endif\n\n *par_inout = par;\n\n return GSL_SUCCESS;\n}\n\n\n\n", "meta": {"hexsha": "1e7a3d1286261b4e534d5f8d9b03fde204be4933", "size": 11344, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit/lmpar.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/lmpar.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/lmpar.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 21.690248566, "max_line_length": 82, "alphanum_fraction": 0.5700811001, "num_tokens": 3392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.4218058406909709}} {"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n * Copyright 2018 - Matteo Ragni, Matteo Cocetti - University of Trento\r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in\r\n * all copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\r\n\r\n#include \r\n#include \"libeuler.h\"\r\n\r\n/**\r\n * @brief Internal: Strut that will be passed to euler functions callbacks\r\n */\r\ntypedef struct euler_passthrough\r\n{\r\n double ts; /**< Integration steps. Taken from options struct */\r\n double alpha; /**< Tustin coefficient. Taken from options struct */\r\n lapack_int u_offset; /**< Input offset for \\f$t+h\\f$ callbacks. Taken from options struct */\r\n euler_ode_function f; /**< Vector field to integrate. Taken from input struct */\r\n euler_ode_jacobian df; /**< Jacobian of the vector field. Taken from options struct */\r\n const double *xk; /**< Current state. Taken from parameters */\r\n lapack_int x_size; /**< Ode dimension, taken from the input struct */\r\n double *work_f; /**< Working space. Allocated in integration step */\r\n double *work_df; /**< Working space. Allocated in integration step */\r\n void *data; /**< User supplied data. Taken from parameters */\r\n} euler_passtrough;\r\n\r\n/**\r\n * @brief Euler implicit step wrapper\r\n * \r\n * The vector field wrapper implements the following:\r\n * \\f{\r\n * g(\\cdot) = -x(t+h) + x(t) + (1-\\alpha) h f(x(t), u_{1..u_{off}, p} + \r\n * \\alpha h f(x(t+h), u_{u_{off}..dim(u)}, p)\r\n * \\f}\r\n * by using user supplied vector field callback. The implicit step search the root\r\n * of \\f$g(\\cdot)\\f$.\r\n */\r\nvoid euler_function_wrapper(double *f, const double t, const double *x, const double *u, const double **p, void *data);\r\n\r\n/**\r\n * @brief Euler implicit step wrapper jacobian\r\n * \r\n * The vector field wrapper implements the following jacobian matrix:\r\n * \\f{\r\n * \\nabla_{x(t+h)} g(\\cdot) = -I + \\alpha h \\nabla_{x(t+h)} f(x(t+h), u_{u_{off}..dim(u)}, p) \r\n * \\f}\r\n * by using user supplied vector field callback\r\n */\r\nvoid euler_jacobian_wrapper(double *f, const double t, const double *x, const double *u, const double **p, void *data);\r\n\r\n euler_ret euler(const euler_options *opt, double *xp, const double t, const double *x, const double *u, const double **p, void *data)\r\n{\r\n\r\n /* EXPLICIT IMPLEMENTATION */\r\n/* Performin a very simple step if alpha == 0 */\r\nif (opt->alpha == 0)\r\n{\r\n opt->f(xp, t, x, u, p, opt->data);\r\n cblas_dscal(opt->x_size, opt->ts, xp, 1);\r\n cblas_daxpy(opt->x_size, 1, x, 1, xp, 1);\r\n return EULER_SUCCESS;\r\n }\r\n\r\n /* IMPLICIT IMPLEMENTTION */\r\n /* Allocating working memory */\r\n double *work_f = (double *)calloc(2 * opt->x_size, sizeof(double));\r\n if (!work_f)\r\n return EULER_EMALLOC;\r\n double *work_df = (double *)calloc(2 * opt->x_size * opt->x_size, sizeof(double));\r\n if(!work_df) {\r\n free(work_f);\r\n return EULER_EMALLOC;\r\n }\r\n /* Setting up the identity matrix in work_df second space, once forever */\r\n for (lapack_int i = 0; i < opt->x_size; i++)\r\n work_df[(opt->x_size * opt->x_size) + i + i * opt->x_size] = -1.0;\r\n\r\n /* Setting up options for Euler step */\r\n newton_options newton_opts = {\r\n opt->ordering, opt->x_size, opt->x_size, \r\n opt->s_tol, opt->x_tol, opt->max_iter,\r\n euler_function_wrapper,\r\n euler_jacobian_wrapper\r\n };\r\n\r\n euler_passtrough pt = {\r\n opt->ts, opt->alpha, opt->u_offset,\r\n opt->f, opt->df, x, opt->x_size,\r\n work_f, work_df,\r\n opt->data\r\n };\r\n\r\n cblas_dcopy(opt->x_size, x, 1, xp, 1);\r\n newton_ret nwt = newton_solve(&newton_opts, t, xp, u, p, ((void *)&pt)); \r\n\r\n /* Freeing space */\r\n free(work_f);\r\n free(work_df);\r\n if (nwt > NEWTON_MAX_ITER)\r\n return EULER_GENERIC;\r\n return EULER_SUCCESS;\r\n}\r\n\r\nvoid euler_function_wrapper(double *f, const double t, const double *x, const double *u, const double **p, void *data) {\r\n euler_passtrough *_data = ((euler_passtrough *)data);\r\n\r\n /* Evaluating f(x(k), u(k)) and f(x(k+1), u(k+1)), storing result in work_f */\r\n _data->f(_data->work_f, t, _data->xk, u, p, _data->data);\r\n _data->f(_data->work_f + _data->x_size, t, x, u + _data->u_offset, p, _data->data);\r\n\r\n /* Computing: x(k) - x(k+1) + (1-alpha) ts f(x(k), u(k)) + alpha ts f(x(k+1), u(k+1)) */\r\n cblas_dscal(_data->x_size, (1 - _data->alpha) * _data->ts, _data->work_f, 1);\r\n cblas_dscal(_data->x_size, _data->alpha * _data->ts, _data->work_f + _data->x_size, 1);\r\n cblas_daxpy(_data->x_size, 1, _data->work_f + _data->x_size, 1, _data->work_f, 1);\r\n cblas_daxpy(_data->x_size, -1, x, 1, _data->work_f, 1);\r\n cblas_daxpy(_data->x_size, 1, _data->xk, 1, _data->work_f, 1);\r\n\r\n /* Copying result in output */\r\n cblas_dcopy(_data->x_size, _data->work_f, 1, f, 1);\r\n}\r\n\r\nvoid euler_jacobian_wrapper(double *df, const double t, const double *x, const double *u, const double **p, void *data) {\r\n euler_passtrough *_data = ((euler_passtrough *)data);\r\n\r\n /* Evaluating JAC(f)(x(k+1), u(k+1)) */\r\n _data->df(_data->work_df, t, x, u + _data->u_offset, p, _data->data);\r\n\r\n /* Computing: -I + alpha ts JAC(f)(x(k+1), u(k+1)) (still using level 1 Blas) */\r\n cblas_dscal(_data->x_size * _data->x_size, _data->alpha * _data->ts, _data->work_df, 1);\r\n cblas_daxpy(_data->x_size * _data->x_size, 1, _data->work_df + _data->x_size * _data->x_size, 1, _data->work_df, 1);\r\n\r\n /* Copying result in output */\r\n cblas_dcopy(_data->x_size * _data->x_size, _data->work_df, 1, df, 1);\r\n}", "meta": {"hexsha": "1ac2368a21a4359a65a52cb272a36338cafa33fe", "size": 6541, "ext": "c", "lang": "C", "max_stars_repo_path": "libeuler.c", "max_stars_repo_name": "MatteoRagni/libeuler", "max_stars_repo_head_hexsha": "7dd73c1b383b6c32086da4880a82326ebf47b71b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T07:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-22T02:16:51.000Z", "max_issues_repo_path": "libeuler.c", "max_issues_repo_name": "MatteoRagni/libeuler", "max_issues_repo_head_hexsha": "7dd73c1b383b6c32086da4880a82326ebf47b71b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libeuler.c", "max_forks_repo_name": "MatteoRagni/libeuler", "max_forks_repo_head_hexsha": "7dd73c1b383b6c32086da4880a82326ebf47b71b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6066666667, "max_line_length": 138, "alphanum_fraction": 0.6358354992, "num_tokens": 1966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4216652646100422}} {"text": "/*\nMultisteps: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file rk_4_4.c\n * \\brief Source file to optimize Runge-Kutta 5 steps 4th order methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"rk.h\"\n#include \"rk_4_4.h\"\n\n#define DEBUG_RK_4_4 0 ///< macro to debug.\n\n/**\n * Function to obtain the coefficients of a 4 steps 4th order Runge-Kutta \n * method.\n */\nint\nrk_tb_4_4 (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb, *r;\n#if DEBUG_RK_4_4\n fprintf (stderr, \"rk_tb_4_4: start\\n\");\n#endif\n tb = optimize->coefficient;\n r = optimize->random_data;\n t4 (tb) = 1.L;\n t1 (tb) = r[0];\n t2 (tb) = r[1];\n t3 (tb) = 1.L;\n b43 (tb) = (0.25L - 1.L / 3.L * t1 (tb)\n - (1.L / 3.L - 0.5L * t1 (tb)) * t2 (tb))\n / (t3 (tb) * (t3 (tb) - t2 (tb)) * (t3 (tb) - t1 (tb)));\n if (isnan (b43 (tb)))\n return 0;\n b42 (tb) = (1.L / 3.L - 0.5L * t1 (tb)\n - b43 (tb) * t3 (tb) * (t3 (tb) - t1 (tb)))\n / (t2 (tb) * (t2 (tb) - t1 (tb)));\n if (isnan (b42 (tb)))\n return 0;\n b41 (tb) = (0.5L - b42 (tb) * t2 (tb) - b43 (tb) * t3 (tb)) / t1 (tb);\n if (isnan (b41 (tb)))\n return 0;\n b32 (tb) = (1.L / 12.L - 1.L / 6.L * t1 (tb))\n / (b43 (tb) * t2 (tb) * (t2 (tb) - t1 (tb)));\n if (isnan (b32 (tb)))\n return 0;\n b31 (tb) = ((0.125L - 1.L / 6.L * t2 (tb)) / (b43 (tb) * (t3 (tb) - t2 (tb)))\n - b32 (tb) * t2 (tb)) / t1 (tb);\n if (isnan (b31 (tb)))\n return 0;\n b21 (tb) = 1.L / 24.L / (t1 (tb) * b43 (tb) * b32 (tb));\n if (isnan (b21 (tb)))\n return 0;\n rk_b_4 (tb);\n#if DEBUG_RK_4_4\n fprintf (stderr, \"rk_tb_4_4: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 4 steps 4th order, 5th order in\n * equations depending only in time, Runge-Kutta method.\n */\nint\nrk_tb_4_4t (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb, *r;\n#if DEBUG_RK_4_4\n fprintf (stderr, \"rk_tb_4_4t: start\\n\");\n#endif\n tb = optimize->coefficient;\n r = optimize->random_data;\n t4 (tb) = 1.L;\n t1 (tb) = r[0];\n t2 (tb) = 0.5L * (t1 (tb) - 0.6L) / (t1 (tb) - 0.5L);\n t3 (tb) = 1.L;\n b43 (tb) = (0.25L - 1.L / 3.L * t1 (tb)\n - (1.L / 3.L - 0.5L * t1 (tb)) * t2 (tb))\n / (t3 (tb) * (t3 (tb) - t2 (tb)) * (t3 (tb) - t1 (tb)));\n if (isnan (b43 (tb)))\n return 0;\n b42 (tb) = (1.L / 3.L - 0.5L * t1 (tb)\n - b43 (tb) * t3 (tb) * (t3 (tb) - t1 (tb)))\n / (t2 (tb) * (t2 (tb) - t1 (tb)));\n if (isnan (b42 (tb)))\n return 0;\n b41 (tb) = (0.5L - b42 (tb) * t2 (tb) - b43 (tb) * t3 (tb)) / t1 (tb);\n if (isnan (b41 (tb)))\n return 0;\n b32 (tb) = (1.L / 12.L - 1.L / 6.L * t1 (tb))\n / (b43 (tb) * t2 (tb) * (t2 (tb) - t1 (tb)));\n if (isnan (b32 (tb)))\n return 0;\n b31 (tb) = ((0.125L - 1.L / 6.L * t2 (tb)) / (b43 (tb) * (t3 (tb) - t2 (tb)))\n - b32 (tb) * t2 (tb)) / t1 (tb);\n if (isnan (b31 (tb)))\n return 0;\n b21 (tb) = 1.L / 24.L / (t1 (tb) * b43 (tb) * b32 (tb));\n if (isnan (b21 (tb)))\n return 0;\n rk_b_4 (tb);\n#if DEBUG_RK_4_4\n fprintf (stderr, \"rk_tb_4_4t: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to calculate the objective function of a 4 steps 4th order \n * Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_4_4 (RK * rk) ///< RK struct.\n{\n long double *tb;\n long double o;\n#if DEBUG_RK_4_4\n fprintf (stderr, \"rk_objective_tb_4_4: start\\n\");\n#endif\n tb = rk->tb->coefficient;\n o = fminl (0.L, b20 (tb));\n if (b21 (tb) < 0.L)\n o += b21 (tb);\n if (b30 (tb) < 0.L)\n o += b30 (tb);\n if (b31 (tb) < 0.L)\n o += b31 (tb);\n if (b32 (tb) < 0.L)\n o += b32 (tb);\n if (b40 (tb) < 0.L)\n o += b40 (tb);\n if (b41 (tb) < 0.L)\n o += b41 (tb);\n if (b42 (tb) < 0.L)\n o += b42 (tb);\n if (b43 (tb) < 0.L)\n o += b43 (tb);\n if (o < 0.L)\n {\n o = 40.L - o;\n goto end;\n }\n o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\nend:\n#if DEBUG_RK_4_4\n fprintf (stderr, \"rk_objective_tb_4_4: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_4_4: end\\n\");\n#endif\n return o;\n}\n\n/**\n * Function to calculate the objective function of a 4 steps 4th order, 5th\n * order in equations depending only in time, Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_4_4t (RK * rk) ///< RK struct.\n{\n long double *tb;\n long double o;\n#if DEBUG_RK_4_4\n fprintf (stderr, \"rk_objective_tb_4_4: start\\n\");\n#endif\n tb = rk->tb->coefficient;\n o = fminl (0.L, b20 (tb));\n if (b21 (tb) < 0.L)\n o += b21 (tb);\n if (b30 (tb) < 0.L)\n o += b30 (tb);\n if (b31 (tb) < 0.L)\n o += b31 (tb);\n if (b32 (tb) < 0.L)\n o += b32 (tb);\n if (b40 (tb) < 0.L)\n o += b40 (tb);\n if (b41 (tb) < 0.L)\n o += b41 (tb);\n if (b42 (tb) < 0.L)\n o += b42 (tb);\n if (b43 (tb) < 0.L)\n o += b43 (tb);\n if (o < 0.L)\n {\n o = 40.L - o;\n goto end;\n }\n o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\nend:\n#if DEBUG_RK_4_4\n fprintf (stderr, \"rk_objective_tb_4_4: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_4_4: end\\n\");\n#endif\n return o;\n}\n", "meta": {"hexsha": "2d2dc82c27211ba1dad284dbfe07a76f46f641f7", "size": 6832, "ext": "c", "lang": "C", "max_stars_repo_path": "rk_4_4.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rk_4_4.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rk_4_4.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7723577236, "max_line_length": 80, "alphanum_fraction": 0.574941452, "num_tokens": 2635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389327, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.42165035500289605}} {"text": "#include \n#include \n\n#include \n\nint\nmain()\n{\n gsl_spmatrix *A = gsl_spmatrix_alloc(5, 4); /* triplet format */\n gsl_spmatrix *B, *C;\n size_t i, j;\n\n /* build the sparse matrix */\n gsl_spmatrix_set(A, 0, 2, 3.1);\n gsl_spmatrix_set(A, 0, 3, 4.6);\n gsl_spmatrix_set(A, 1, 0, 1.0);\n gsl_spmatrix_set(A, 1, 2, 7.2);\n gsl_spmatrix_set(A, 3, 0, 2.1);\n gsl_spmatrix_set(A, 3, 1, 2.9);\n gsl_spmatrix_set(A, 3, 3, 8.5);\n gsl_spmatrix_set(A, 4, 0, 4.1);\n\n printf(\"printing all matrix elements:\\n\");\n for (i = 0; i < 5; ++i)\n for (j = 0; j < 4; ++j)\n printf(\"A(%zu,%zu) = %g\\n\", i, j,\n gsl_spmatrix_get(A, i, j));\n\n /* print out elements in triplet format */\n printf(\"matrix in triplet format (i,j,Aij):\\n\");\n gsl_spmatrix_fprintf(stdout, A, \"%.1f\");\n\n /* convert to compressed column format */\n B = gsl_spmatrix_ccs(A);\n\n printf(\"matrix in compressed column format:\\n\");\n printf(\"i = [ \");\n for (i = 0; i < B->nz; ++i)\n printf(\"%d, \", B->i[i]);\n printf(\"]\\n\");\n\n printf(\"p = [ \");\n for (i = 0; i < B->size2 + 1; ++i)\n printf(\"%d, \", B->p[i]);\n printf(\"]\\n\");\n\n printf(\"d = [ \");\n for (i = 0; i < B->nz; ++i)\n printf(\"%g, \", B->data[i]);\n printf(\"]\\n\");\n\n /* convert to compressed row format */\n C = gsl_spmatrix_crs(A);\n\n printf(\"matrix in compressed row format:\\n\");\n printf(\"i = [ \");\n for (i = 0; i < C->nz; ++i)\n printf(\"%d, \", C->i[i]);\n printf(\"]\\n\");\n\n printf(\"p = [ \");\n for (i = 0; i < C->size1 + 1; ++i)\n printf(\"%d, \", C->p[i]);\n printf(\"]\\n\");\n\n printf(\"d = [ \");\n for (i = 0; i < C->nz; ++i)\n printf(\"%g, \", C->data[i]);\n printf(\"]\\n\");\n\n gsl_spmatrix_free(A);\n gsl_spmatrix_free(B);\n gsl_spmatrix_free(C);\n\n return 0;\n}\n", "meta": {"hexsha": "ed0018245dd66ec88206b71a4e11b3c6a3b2b315", "size": 1745, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/spmatrix.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/doc/examples/spmatrix.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/doc/examples/spmatrix.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 22.6623376623, "max_line_length": 66, "alphanum_fraction": 0.5346704871, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.42147787746983845}} {"text": "/* specfunc/laguerre.c\n * \n * Copyright (C) 2007 Brian Gough\n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n\n/* based on the large 2b-4a asymptotic for 1F1\n * [Abramowitz+Stegun, 13.5.21]\n * L^a_n(x) = (a+1)_n / n! 1F1(-n,a+1,x)\n *\n * The second term (ser_term2) is from Slater,\"The Confluent\n * Hypergeometric Function\" p.73. I think there may be an error in\n * the first term of the expression given there, comparing with AS\n * 13.5.21 (cf sin(a\\pi+\\Theta) vs sin(a\\pi) + sin(\\Theta)) - but the\n * second term appears correct.\n *\n */\nstatic\nint\nlaguerre_large_n(const int n, const double alpha, const double x,\n gsl_sf_result * result)\n{\n const double a = -n;\n const double b = alpha + 1.0;\n const double eta = 2.0*b - 4.0*a;\n const double cos2th = x/eta;\n const double sin2th = 1.0 - cos2th;\n const double eps = asin(sqrt(cos2th)); /* theta = pi/2 - eps */\n const double pre_h = 0.25*M_PI*M_PI*eta*eta*cos2th*sin2th;\n gsl_sf_result lg_b;\n gsl_sf_result lnfact;\n int stat_lg = gsl_sf_lngamma_e(b+n, &lg_b);\n int stat_lf = gsl_sf_lnfact_e(n, &lnfact);\n double pre_term1 = 0.5*(1.0-b)*log(0.25*x*eta);\n double pre_term2 = 0.25*log(pre_h);\n double lnpre_val = lg_b.val - lnfact.val + 0.5*x + pre_term1 - pre_term2;\n double lnpre_err = lg_b.err + lnfact.err + GSL_DBL_EPSILON * (fabs(pre_term1)+fabs(pre_term2));\n\n double phi1 = 0.25*eta*(2*eps + sin(2.0*eps));\n double ser_term1 = -sin(phi1);\n\n double A1 = (1.0/12.0)*(5.0/(4.0*sin2th)+(3.0*b*b-6.0*b+2.0)*sin2th - 1.0);\n double ser_term2 = -A1 * cos(phi1)/(0.25*eta*sin(2.0*eps));\n\n double ser_val = ser_term1 + ser_term2;\n double ser_err = ser_term2*ser_term2 + GSL_DBL_EPSILON * (fabs(ser_term1) + fabs(ser_term2));\n int stat_e = gsl_sf_exp_mult_err_e(lnpre_val, lnpre_err, ser_val, ser_err, result);\n result->err += 2.0 * GSL_SQRT_DBL_EPSILON * fabs(result->val);\n return GSL_ERROR_SELECT_3(stat_e, stat_lf, stat_lg);\n}\n\n\n/* Evaluate polynomial based on confluent hypergeometric representation.\n *\n * L^a_n(x) = (a+1)_n / n! 1F1(-n,a+1,x)\n *\n * assumes n > 0 and a != negative integer greater than -n\n */\nstatic\nint\nlaguerre_n_cp(const int n, const double a, const double x, gsl_sf_result * result)\n{\n gsl_sf_result lnfact;\n gsl_sf_result lg1;\n gsl_sf_result lg2;\n double s1, s2;\n int stat_f = gsl_sf_lnfact_e(n, &lnfact);\n int stat_g1 = gsl_sf_lngamma_sgn_e(a+1.0+n, &lg1, &s1);\n int stat_g2 = gsl_sf_lngamma_sgn_e(a+1.0, &lg2, &s2);\n double poly_1F1_val = 1.0;\n double poly_1F1_err = 0.0;\n int stat_e;\n int k;\n\n double lnpre_val = (lg1.val - lg2.val) - lnfact.val;\n double lnpre_err = lg1.err + lg2.err + lnfact.err + 2.0 * GSL_DBL_EPSILON * fabs(lnpre_val);\n\n for(k=n-1; k>=0; k--) {\n double t = (-n+k)/(a+1.0+k) * (x/(k+1));\n double r = t + 1.0/poly_1F1_val;\n if(r > 0.9*GSL_DBL_MAX/poly_1F1_val) {\n /* internal error only, don't call the error handler */\n INTERNAL_OVERFLOW_ERROR(result);\n }\n else {\n /* Collect the Horner terms. */\n poly_1F1_val = 1.0 + t * poly_1F1_val;\n poly_1F1_err += GSL_DBL_EPSILON + fabs(t) * poly_1F1_err;\n }\n }\n\n stat_e = gsl_sf_exp_mult_err_e(lnpre_val, lnpre_err,\n poly_1F1_val, poly_1F1_err,\n result);\n\n return GSL_ERROR_SELECT_4(stat_e, stat_f, stat_g1, stat_g2);\n}\n\n\n/* Evaluate the polynomial based on the confluent hypergeometric\n * function in a safe way, with no restriction on the arguments.\n *\n * assumes x != 0\n */\nstatic\nint\nlaguerre_n_poly_safe(const int n, const double a, const double x, gsl_sf_result * result)\n{\n const double b = a + 1.0;\n const double mx = -x;\n const double tc_sgn = (x < 0.0 ? 1.0 : (GSL_IS_ODD(n) ? -1.0 : 1.0));\n gsl_sf_result tc;\n int stat_tc = gsl_sf_taylorcoeff_e(n, fabs(x), &tc);\n\n if(stat_tc == GSL_SUCCESS) {\n double term = tc.val * tc_sgn;\n double sum_val = term;\n double sum_err = tc.err;\n int k;\n for(k=n-1; k>=0; k--) {\n term *= ((b+k)/(n-k))*(k+1.0)/mx;\n sum_val += term;\n sum_err += 4.0 * GSL_DBL_EPSILON * fabs(term);\n }\n result->val = sum_val;\n result->err = sum_err + 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(stat_tc == GSL_EOVRFLW) {\n result->val = 0.0; /* FIXME: should be Inf */\n result->err = 0.0;\n return stat_tc;\n }\n else {\n result->val = 0.0;\n result->err = 0.0;\n return stat_tc;\n }\n}\n\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_laguerre_1_e(const double a, const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n {\n result->val = 1.0 + a - x;\n result->err = 2.0 * GSL_DBL_EPSILON * (1.0 + fabs(a) + fabs(x));\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_sf_laguerre_2_e(const double a, const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(a == -2.0) {\n result->val = 0.5*x*x;\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n double c0 = 0.5 * (2.0+a)*(1.0+a);\n double c1 = -(2.0+a);\n double c2 = -0.5/(2.0+a);\n result->val = c0 + c1*x*(1.0 + c2*x);\n result->err = 2.0 * GSL_DBL_EPSILON * (fabs(c0) + 2.0 * fabs(c1*x) * (1.0 + 2.0 * fabs(c2*x)));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_sf_laguerre_3_e(const double a, const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(a == -2.0) {\n double x2_6 = x*x/6.0;\n result->val = x2_6 * (3.0 - x);\n result->err = x2_6 * (3.0 + fabs(x)) * 2.0 * GSL_DBL_EPSILON;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(a == -3.0) {\n result->val = -x*x/6.0;\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n double c0 = (3.0+a)*(2.0+a)*(1.0+a) / 6.0;\n double c1 = -c0 * 3.0 / (1.0+a);\n double c2 = -1.0/(2.0+a);\n double c3 = -1.0/(3.0*(3.0+a));\n result->val = c0 + c1*x*(1.0 + c2*x*(1.0 + c3*x));\n result->err = 1.0 + 2.0 * fabs(c3*x);\n result->err = 1.0 + 2.0 * fabs(c2*x) * result->err;\n result->err = 2.0 * GSL_DBL_EPSILON * (fabs(c0) + 2.0 * fabs(c1*x) * result->err);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_sf_laguerre_n_e(const int n, const double a, const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(n < 0) {\n DOMAIN_ERROR(result);\n }\n else if(n == 0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(n == 1) {\n result->val = 1.0 + a - x;\n result->err = 2.0 * GSL_DBL_EPSILON * (1.0 + fabs(a) + fabs(x));\n return GSL_SUCCESS;\n }\n else if(x == 0.0) {\n double product = a + 1.0;\n int k;\n for(k=2; k<=n; k++) {\n product *= (a + k)/k;\n }\n result->val = product;\n result->err = 2.0 * (n + 1.0) * GSL_DBL_EPSILON * fabs(product) + GSL_DBL_EPSILON;\n return GSL_SUCCESS;\n }\n else if(x < 0.0 && a > -1.0) {\n /* In this case all the terms in the polynomial\n * are of the same sign. Note that this also\n * catches overflows correctly.\n */\n return laguerre_n_cp(n, a, x, result);\n }\n else if(n < 5 || (x > 0.0 && a < -n-1)) {\n /* Either the polynomial will not lose too much accuracy\n * or all the terms are negative. In any case,\n * the error estimate here is good. We try both\n * explicit summation methods, as they have different\n * characteristics. One may underflow/overflow while the\n * other does not.\n */\n if(laguerre_n_cp(n, a, x, result) == GSL_SUCCESS)\n return GSL_SUCCESS;\n else\n return laguerre_n_poly_safe(n, a, x, result);\n }\n else if(n > 1.0e+07 && x > 0.0 && a > -1.0 && x < 2.0*(a+1.0)+4.0*n) {\n return laguerre_large_n(n, a, x, result);\n }\n else if(a >= 0.0 || (x > 0.0 && a < -n-1)) {\n gsl_sf_result lg2;\n int stat_lg2 = gsl_sf_laguerre_2_e(a, x, &lg2);\n double Lkm1 = 1.0 + a - x;\n double Lk = lg2.val;\n double Lkp1;\n int k;\n\n for(k=2; kval = Lk;\n result->err = (fabs(lg2.err/lg2.val) + GSL_DBL_EPSILON) * n * fabs(Lk);\n return stat_lg2;\n }\n else {\n /* Despair... or magic? */\n return laguerre_n_poly_safe(n, a, x, result);\n }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_laguerre_1(double a, double x)\n{\n EVAL_RESULT(gsl_sf_laguerre_1_e(a, x, &result));\n}\n\ndouble gsl_sf_laguerre_2(double a, double x)\n{\n EVAL_RESULT(gsl_sf_laguerre_2_e(a, x, &result));\n}\n\ndouble gsl_sf_laguerre_3(double a, double x)\n{\n EVAL_RESULT(gsl_sf_laguerre_3_e(a, x, &result));\n}\n\ndouble gsl_sf_laguerre_n(int n, double a, double x)\n{\n EVAL_RESULT(gsl_sf_laguerre_n_e(n, a, x, &result));\n}\n", "meta": {"hexsha": "53dfa6e38bb8250d06cf012e9f7c0d43795b8d13", "size": 9933, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/laguerre.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/specfunc/laguerre.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/specfunc/laguerre.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 29.5625, "max_line_length": 100, "alphanum_fraction": 0.6120004027, "num_tokens": 3549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4214778690642693}} {"text": "/* multfit/lmder.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\ntypedef struct\n {\n size_t iter;\n double xnorm;\n double fnorm;\n double delta;\n double par;\n gsl_matrix *J; /* Jacobian matrix */\n gsl_matrix *r; /* R matrix in J = Q R P^T */\n gsl_vector *tau;\n gsl_vector *diag; /* scaling matrix D = diag(d1,...,dp) */\n gsl_vector *qtf; /* Q^T f */\n gsl_vector *newton;\n gsl_vector *gradient; /* gradient g = J^T f */\n gsl_vector *x_trial; /* trial step x + dx */\n gsl_vector *f_trial; /* trial function f(x + dx) */\n gsl_vector *df;\n gsl_vector *sdiag;\n gsl_vector *rptdx;\n const gsl_vector *weights; /* data weights */\n gsl_vector *w;\n gsl_vector *work1;\n gsl_permutation * perm;\n }\nlmder_state_t;\n\nstatic int lmder_alloc (void *vstate, size_t n, size_t p);\nstatic int lmder_set (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx);\nstatic int lmsder_set (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx);\nstatic int set (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx, int scale);\nstatic int lmder_iterate (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx);\nstatic void lmder_free (void *vstate);\nstatic int iterate (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx, int scale);\n\n#include \"lmutil.c\"\n#include \"lmpar.c\"\n#include \"lmset.c\"\n#include \"lmiterate.c\"\n\n\nstatic int\nlmder_alloc (void *vstate, size_t n, size_t p)\n{\n lmder_state_t *state = (lmder_state_t *) vstate;\n gsl_matrix *r, *J;\n gsl_vector *tau, *diag, *qtf, *newton, *gradient, *x_trial, *f_trial,\n *df, *sdiag, *rptdx, *w, *work1;\n gsl_permutation *perm;\n\n J = gsl_matrix_alloc (n, p);\n\n if (J == 0)\n {\n GSL_ERROR (\"failed to allocate space for J\", GSL_ENOMEM);\n }\n\n state->J = J;\n\n r = gsl_matrix_alloc (n, p);\n\n if (r == 0)\n {\n GSL_ERROR (\"failed to allocate space for r\", GSL_ENOMEM);\n }\n\n state->r = r;\n\n tau = gsl_vector_calloc (GSL_MIN(n, p));\n\n if (tau == 0)\n {\n gsl_matrix_free (r);\n\n GSL_ERROR (\"failed to allocate space for tau\", GSL_ENOMEM);\n }\n\n state->tau = tau;\n\n diag = gsl_vector_calloc (p);\n\n if (diag == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n\n GSL_ERROR (\"failed to allocate space for diag\", GSL_ENOMEM);\n }\n\n state->diag = diag;\n\n qtf = gsl_vector_calloc (n);\n\n if (qtf == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n gsl_vector_free (diag);\n\n GSL_ERROR (\"failed to allocate space for qtf\", GSL_ENOMEM);\n }\n\n state->qtf = qtf;\n\n newton = gsl_vector_calloc (p);\n\n if (newton == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n gsl_vector_free (diag);\n gsl_vector_free (qtf);\n\n GSL_ERROR (\"failed to allocate space for newton\", GSL_ENOMEM);\n }\n\n state->newton = newton;\n\n gradient = gsl_vector_calloc (p);\n\n if (gradient == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n gsl_vector_free (diag);\n gsl_vector_free (qtf);\n gsl_vector_free (newton);\n\n GSL_ERROR (\"failed to allocate space for gradient\", GSL_ENOMEM);\n }\n\n state->gradient = gradient;\n\n x_trial = gsl_vector_calloc (p);\n\n if (x_trial == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n gsl_vector_free (diag);\n gsl_vector_free (qtf);\n gsl_vector_free (newton);\n gsl_vector_free (gradient);\n\n GSL_ERROR (\"failed to allocate space for x_trial\", GSL_ENOMEM);\n }\n\n state->x_trial = x_trial;\n\n f_trial = gsl_vector_calloc (n);\n\n if (f_trial == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n gsl_vector_free (diag);\n gsl_vector_free (qtf);\n gsl_vector_free (newton);\n gsl_vector_free (gradient);\n gsl_vector_free (x_trial);\n\n GSL_ERROR (\"failed to allocate space for f_trial\", GSL_ENOMEM);\n }\n\n state->f_trial = f_trial;\n\n df = gsl_vector_calloc (n);\n\n if (df == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n gsl_vector_free (diag);\n gsl_vector_free (qtf);\n gsl_vector_free (newton);\n gsl_vector_free (gradient);\n gsl_vector_free (x_trial);\n gsl_vector_free (f_trial);\n\n GSL_ERROR (\"failed to allocate space for df\", GSL_ENOMEM);\n }\n\n state->df = df;\n\n sdiag = gsl_vector_calloc (p);\n\n if (sdiag == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n gsl_vector_free (diag);\n gsl_vector_free (qtf);\n gsl_vector_free (newton);\n gsl_vector_free (gradient);\n gsl_vector_free (x_trial);\n gsl_vector_free (f_trial);\n gsl_vector_free (df);\n\n GSL_ERROR (\"failed to allocate space for sdiag\", GSL_ENOMEM);\n }\n\n state->sdiag = sdiag;\n\n\n rptdx = gsl_vector_calloc (n);\n\n if (rptdx == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n gsl_vector_free (diag);\n gsl_vector_free (qtf);\n gsl_vector_free (newton);\n gsl_vector_free (gradient);\n gsl_vector_free (x_trial);\n gsl_vector_free (f_trial);\n gsl_vector_free (df);\n gsl_vector_free (sdiag);\n\n GSL_ERROR (\"failed to allocate space for rptdx\", GSL_ENOMEM);\n }\n\n state->rptdx = rptdx;\n\n w = gsl_vector_calloc (n);\n\n if (w == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n gsl_vector_free (diag);\n gsl_vector_free (qtf);\n gsl_vector_free (newton);\n gsl_vector_free (gradient);\n gsl_vector_free (x_trial);\n gsl_vector_free (f_trial);\n gsl_vector_free (df);\n gsl_vector_free (sdiag);\n gsl_vector_free (rptdx);\n\n GSL_ERROR (\"failed to allocate space for w\", GSL_ENOMEM);\n }\n\n state->w = w;\n\n work1 = gsl_vector_calloc (p);\n\n if (work1 == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n gsl_vector_free (diag);\n gsl_vector_free (qtf);\n gsl_vector_free (newton);\n gsl_vector_free (gradient);\n gsl_vector_free (x_trial);\n gsl_vector_free (f_trial);\n gsl_vector_free (df);\n gsl_vector_free (sdiag);\n gsl_vector_free (rptdx);\n gsl_vector_free (w);\n\n GSL_ERROR (\"failed to allocate space for work1\", GSL_ENOMEM);\n }\n\n state->work1 = work1;\n\n perm = gsl_permutation_calloc (p);\n\n if (perm == 0)\n {\n gsl_matrix_free (r);\n gsl_vector_free (tau);\n gsl_vector_free (diag);\n gsl_vector_free (qtf);\n gsl_vector_free (newton);\n gsl_vector_free (gradient);\n gsl_vector_free (x_trial);\n gsl_vector_free (f_trial);\n gsl_vector_free (df);\n gsl_vector_free (sdiag);\n gsl_vector_free (rptdx);\n gsl_vector_free (w);\n gsl_vector_free (work1);\n\n GSL_ERROR (\"failed to allocate space for perm\", GSL_ENOMEM);\n }\n\n state->perm = perm;\n\n return GSL_SUCCESS;\n}\n\nstatic int\nlmder_set (void *vstate, const gsl_vector * swts,\n gsl_multifit_function_fdf * fdf, gsl_vector * x,\n gsl_vector * f, gsl_vector * dx)\n{\n int status = set (vstate, swts, fdf, x, f, dx, 0);\n return status ;\n}\n\nstatic int\nlmsder_set (void *vstate, const gsl_vector * swts,\n gsl_multifit_function_fdf * fdf, gsl_vector * x,\n gsl_vector * f, gsl_vector * dx)\n{\n int status = set (vstate, swts, fdf, x, f, dx, 1);\n return status ;\n}\n\nstatic int\nlmder_iterate (void *vstate, const gsl_vector * swts,\n gsl_multifit_function_fdf * fdf, gsl_vector * x,\n gsl_vector * f, gsl_vector * dx)\n{\n int status = iterate (vstate, swts, fdf, x, f, dx, 0);\n return status;\n}\n\nstatic int\nlmsder_iterate (void *vstate, const gsl_vector * swts,\n gsl_multifit_function_fdf * fdf, gsl_vector * x,\n gsl_vector * f, gsl_vector * dx)\n{\n int status = iterate (vstate, swts, fdf, x, f, dx, 1);\n return status;\n}\n\nstatic int\nlmder_gradient (void *vstate, gsl_vector * g)\n{\n lmder_state_t *state = (lmder_state_t *) vstate;\n compute_gradient(state->r, state->qtf, g);\n return GSL_SUCCESS;\n}\n\nstatic int\nlmder_jac (void *vstate, gsl_matrix * J)\n{\n lmder_state_t *state = (lmder_state_t *) vstate;\n int s = gsl_matrix_memcpy(J, state->J);\n\n return s;\n}\n\nstatic void\nlmder_free (void *vstate)\n{\n lmder_state_t *state = (lmder_state_t *) vstate;\n\n if (state->perm)\n gsl_permutation_free (state->perm);\n\n if (state->work1)\n gsl_vector_free (state->work1);\n\n if (state->w)\n gsl_vector_free (state->w);\n\n if (state->rptdx)\n gsl_vector_free (state->rptdx);\n\n if (state->sdiag)\n gsl_vector_free (state->sdiag);\n\n if (state->df)\n gsl_vector_free (state->df);\n\n if (state->f_trial)\n gsl_vector_free (state->f_trial);\n\n if (state->x_trial)\n gsl_vector_free (state->x_trial);\n\n if (state->gradient)\n gsl_vector_free (state->gradient);\n\n if (state->newton)\n gsl_vector_free (state->newton);\n\n if (state->qtf)\n gsl_vector_free (state->qtf);\n\n if (state->diag)\n gsl_vector_free (state->diag);\n\n if (state->tau)\n gsl_vector_free (state->tau);\n\n if (state->r)\n gsl_matrix_free (state->r);\n\n if (state->J)\n gsl_matrix_free (state->J);\n}\n\nstatic const gsl_multifit_fdfsolver_type lmder_type =\n{\n \"lmder\", /* name */\n sizeof (lmder_state_t),\n &lmder_alloc,\n &lmder_set,\n &lmder_iterate,\n &lmder_gradient,\n &lmder_jac,\n &lmder_free\n};\n\nstatic const gsl_multifit_fdfsolver_type lmsder_type =\n{\n \"lmsder\", /* name */\n sizeof (lmder_state_t),\n &lmder_alloc,\n &lmsder_set,\n &lmsder_iterate,\n &lmder_gradient,\n &lmder_jac,\n &lmder_free\n};\n\nconst gsl_multifit_fdfsolver_type *gsl_multifit_fdfsolver_lmder = &lmder_type;\nconst gsl_multifit_fdfsolver_type *gsl_multifit_fdfsolver_lmsder = &lmsder_type;\n", "meta": {"hexsha": "e931a58b9fee1f9d170e639a53a85efb6aaf302f", "size": 11054, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit/lmder.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/lmder.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/lmder.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.135371179, "max_line_length": 152, "alphanum_fraction": 0.6440202642, "num_tokens": 3195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4213693249477454}} {"text": "/* wavelet/dwt.c\n * \n * Copyright (C) 2004 Ivo Alxneit\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* function dwt_step is based on the public domain function pwt.c\n * available from http://www.numerical-recipes.com\n */\n\n#include \n#include \n#include \n#include \n\n#define ELEMENT(a,stride,i) ((a)[(stride)*(i)])\n\nstatic int binary_logn (const size_t n);\nstatic void dwt_step (const gsl_wavelet * w, double *a, size_t stride, size_t n, gsl_wavelet_direction dir, gsl_wavelet_workspace * work);\n\nstatic int\nbinary_logn (const size_t n)\n{\n size_t ntest;\n size_t logn = 0;\n size_t k = 1;\n\n while (k < n)\n {\n k *= 2;\n logn++;\n }\n\n ntest = ((size_t)1 << logn);\n\n if (n != ntest)\n {\n return -1; /* n is not a power of 2 */\n }\n\n return logn;\n}\n\nstatic void\ndwt_step (const gsl_wavelet * w, double *a, size_t stride, size_t n,\n gsl_wavelet_direction dir, gsl_wavelet_workspace * work)\n{\n double ai, ai1;\n size_t i, ii;\n size_t jf;\n size_t k;\n size_t n1, ni, nh, nmod;\n\n for (i = 0; i < work->n; i++)\n {\n work->scratch[i] = 0.0;\n }\n\n nmod = w->nc * n;\n nmod -= w->offset; /* center support */\n\n n1 = n - 1;\n nh = n >> 1;\n\n if (dir == gsl_wavelet_forward)\n {\n for (ii = 0, i = 0; i < n; i += 2, ii++)\n {\n double h = 0, g = 0;\n\n ni = i + nmod;\n \n for (k = 0; k < w->nc; k++)\n {\n jf = n1 & (ni + k);\n h += w->h1[k] * ELEMENT (a, stride, jf);\n g += w->g1[k] * ELEMENT (a, stride, jf);\n }\n\n work->scratch[ii] += h;\n work->scratch[ii + nh] += g;\n }\n }\n else\n {\n for (ii = 0, i = 0; i < n; i += 2, ii++)\n {\n ai = ELEMENT (a, stride, ii);\n ai1 = ELEMENT (a, stride, ii + nh);\n ni = i + nmod;\n for (k = 0; k < w->nc; k++)\n {\n jf = (n1 & (ni + k));\n work->scratch[jf] += (w->h2[k] * ai + w->g2[k] * ai1);\n }\n }\n }\n\n for (i = 0; i < n; i++)\n {\n ELEMENT (a, stride, i) = work->scratch[i];\n }\n}\n\nint\ngsl_wavelet_transform (const gsl_wavelet * w, \n double *data, size_t stride, size_t n,\n gsl_wavelet_direction dir, \n gsl_wavelet_workspace * work)\n{\n size_t i;\n\n if (work->n < n)\n {\n GSL_ERROR (\"not enough workspace provided\", GSL_EINVAL);\n }\n\n if (binary_logn (n) == -1)\n {\n GSL_ERROR (\"n is not a power of 2\", GSL_EINVAL);\n }\n\n if (n < 2)\n {\n return GSL_SUCCESS;\n }\n\n if (dir == gsl_wavelet_forward)\n {\n for (i = n; i >= 2; i >>= 1)\n {\n dwt_step (w, data, stride, i, dir, work);\n }\n }\n else\n {\n for (i = 2; i <= n; i <<= 1)\n {\n dwt_step (w, data, stride, i, dir, work);\n }\n }\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_wavelet_transform_forward (const gsl_wavelet * w, \n double *data, size_t stride, size_t n,\n gsl_wavelet_workspace * work)\n{\n return gsl_wavelet_transform (w, data, stride, n, gsl_wavelet_forward, work);\n}\n\nint\ngsl_wavelet_transform_inverse (const gsl_wavelet * w, \n double *data, size_t stride, size_t n,\n gsl_wavelet_workspace * work)\n{\n return gsl_wavelet_transform (w, data, stride, n, gsl_wavelet_backward, work);\n}\n\n\n/* Leaving this out for now BJG */\n#if 0\nint\ngsl_dwt_vector (const gsl_wavelet * w, gsl_vector *v, gsl_wavelet_direction\n dir, gsl_wavelet_workspace * work)\n{\n return gsl_dwt (w, v->data, v->stride, v->size, dir, work);\n}\n#endif\n\nint\ngsl_wavelet2d_transform (const gsl_wavelet * w, \n double *data, size_t tda, size_t size1,\n size_t size2, gsl_wavelet_direction dir,\n gsl_wavelet_workspace * work)\n{\n size_t i;\n\n if (size1 != size2)\n {\n GSL_ERROR (\"2d dwt works only with square matrix\", GSL_EINVAL);\n }\n\n if (work->n < size1)\n {\n GSL_ERROR (\"not enough workspace provided\", GSL_EINVAL);\n }\n\n if (binary_logn (size1) == -1)\n {\n GSL_ERROR (\"n is not a power of 2\", GSL_EINVAL);\n }\n\n if (size1 < 2)\n {\n return GSL_SUCCESS;\n }\n\n if (dir == gsl_wavelet_forward)\n {\n for (i = 0; i < size1; i++) /* for every row j */\n {\n gsl_wavelet_transform (w, &ELEMENT(data, tda, i), 1, size1, dir, work);\n }\n for (i = 0; i < size2; i++) /* for every column j */\n {\n gsl_wavelet_transform (w, &ELEMENT(data, 1, i), tda, size2, dir, work);\n }\n }\n else\n {\n for (i = 0; i < size2; i++) /* for every column j */\n {\n gsl_wavelet_transform (w, &ELEMENT(data, 1, i), tda, size2, dir, work);\n }\n for (i = 0; i < size1; i++) /* for every row j */\n {\n gsl_wavelet_transform (w, &ELEMENT(data, tda, i), 1, size1, dir, work);\n }\n }\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_wavelet2d_nstransform (const gsl_wavelet * w, \n double *data, size_t tda, size_t size1,\n size_t size2, gsl_wavelet_direction dir,\n gsl_wavelet_workspace * work)\n{\n size_t i, j;\n\n if (size1 != size2)\n {\n GSL_ERROR (\"2d dwt works only with square matrix\", GSL_EINVAL);\n }\n\n if (work->n < size1)\n {\n GSL_ERROR (\"not enough workspace provided\", GSL_EINVAL);\n }\n\n if (binary_logn (size1) == -1)\n {\n GSL_ERROR (\"n is not a power of 2\", GSL_EINVAL);\n }\n\n if (size1 < 2)\n {\n return GSL_SUCCESS;\n }\n\n if (dir == gsl_wavelet_forward)\n {\n for (i = size1; i >= 2; i >>= 1)\n {\n for (j = 0; j < i; j++) /* for every row j */\n {\n dwt_step (w, &ELEMENT(data, tda, j), 1, i, dir, work);\n }\n for (j = 0; j < i; j++) /* for every column j */\n {\n dwt_step (w, &ELEMENT(data, 1, j), tda, i, dir, work);\n }\n }\n }\n else\n {\n for (i = 2; i <= size1; i <<= 1)\n {\n for (j = 0; j < i; j++) /* for every column j */\n {\n dwt_step (w, &ELEMENT(data, 1, j), tda, i, dir, work);\n }\n for (j = 0; j < i; j++) /* for every row j */\n {\n dwt_step (w, &ELEMENT(data, tda, j), 1, i, dir, work);\n }\n }\n }\n\n return GSL_SUCCESS;\n}\n\n\nint\ngsl_wavelet2d_transform_forward (const gsl_wavelet * w, \n double *data, size_t tda, size_t size1,\n size_t size2, gsl_wavelet_workspace * work)\n{\n return gsl_wavelet2d_transform (w, data, tda, size1, size2, gsl_wavelet_forward, work);\n}\n\nint\ngsl_wavelet2d_transform_inverse (const gsl_wavelet * w, \n double *data, size_t tda, size_t size1,\n size_t size2, gsl_wavelet_workspace * work)\n{\n return gsl_wavelet2d_transform (w, data, tda, size1, size2, gsl_wavelet_backward, work);\n}\n\nint\ngsl_wavelet2d_nstransform_forward (const gsl_wavelet * w, \n double *data, size_t tda, size_t size1,\n size_t size2, gsl_wavelet_workspace * work)\n{\n return gsl_wavelet2d_nstransform (w, data, tda, size1, size2, gsl_wavelet_forward, work);\n}\n\nint\ngsl_wavelet2d_nstransform_inverse (const gsl_wavelet * w, \n double *data, size_t tda, size_t size1,\n size_t size2, gsl_wavelet_workspace * work)\n{\n return gsl_wavelet2d_nstransform (w, data, tda, size1, size2, gsl_wavelet_backward, work);\n}\n\n\nint\ngsl_wavelet2d_transform_matrix (const gsl_wavelet * w, \n gsl_matrix * a,\n gsl_wavelet_direction dir, \n gsl_wavelet_workspace * work)\n{\n return gsl_wavelet2d_transform (w, a->data, \n a->tda, a->size1, a->size2, \n dir, work);\n}\n\nint\ngsl_wavelet2d_transform_matrix_forward (const gsl_wavelet * w, \n gsl_matrix * a,\n gsl_wavelet_workspace * work)\n{\n return gsl_wavelet2d_transform (w, a->data, \n a->tda, a->size1, a->size2, \n gsl_wavelet_forward, work);\n}\n\nint\ngsl_wavelet2d_transform_matrix_inverse (const gsl_wavelet * w, \n gsl_matrix * a,\n gsl_wavelet_workspace * work)\n{\n return gsl_wavelet2d_transform (w, a->data, \n a->tda, a->size1, a->size2, \n gsl_wavelet_backward, work);\n}\n\nint\ngsl_wavelet2d_nstransform_matrix (const gsl_wavelet * w, \n gsl_matrix * a,\n gsl_wavelet_direction dir, \n gsl_wavelet_workspace * work)\n{\n return gsl_wavelet2d_nstransform (w, a->data, \n a->tda, a->size1, a->size2, \n dir, work);\n}\n\nint\ngsl_wavelet2d_nstransform_matrix_forward (const gsl_wavelet * w, \n gsl_matrix * a,\n gsl_wavelet_workspace * work)\n{\n return gsl_wavelet2d_nstransform (w, a->data, \n a->tda, a->size1, a->size2, \n gsl_wavelet_forward, work);\n}\n\nint\ngsl_wavelet2d_nstransform_matrix_inverse (const gsl_wavelet * w, \n gsl_matrix * a,\n gsl_wavelet_workspace * work)\n{\n return gsl_wavelet2d_nstransform (w, a->data, \n a->tda, a->size1, a->size2, \n gsl_wavelet_backward, work);\n}\n\n\n", "meta": {"hexsha": "519e955380d48be9f83de7e4792de70cb667bd41", "size": 10833, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/wavelet/dwt.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/wavelet/dwt.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/wavelet/dwt.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.2871536524, "max_line_length": 138, "alphanum_fraction": 0.5090925875, "num_tokens": 2990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.42130541500737867}} {"text": "#include \n#include \n\n#if PETSC_VERSION_LE(3,3,0)\n#define TSRegister(s,f) TSRegister(s,0,0,f)\n#endif\n\ntypedef struct {\n PetscReal Omega; /* frequency */\n PetscReal Xi; /* damping */\n} UserParams;\n\n#undef __FUNCT__\n#define __FUNCT__ \"Residual1\"\nPetscErrorCode Residual1(TS ts,PetscReal t,Vec X,Vec A,Vec R,void *ctx)\n{\n UserParams *user = (UserParams *)ctx;\n PetscReal Omega = user->Omega;\n PetscScalar *x,*a,*r;\n PetscErrorCode ierr;\n PetscFunctionBegin;\n\n ierr = VecGetArray(X,&x);CHKERRQ(ierr);\n ierr = VecGetArray(A,&a);CHKERRQ(ierr);\n ierr = VecGetArray(R,&r);CHKERRQ(ierr);\n\n r[0] = a[0] + (Omega*Omega)*x[0];\n\n ierr = VecRestoreArray(X,&x);CHKERRQ(ierr);\n ierr = VecRestoreArray(A,&a);CHKERRQ(ierr);\n ierr = VecRestoreArray(R,&r);CHKERRQ(ierr);\n\n ierr = VecAssemblyBegin(R);CHKERRQ(ierr);\n ierr = VecAssemblyEnd (R);CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"Tangent1\"\nPetscErrorCode Tangent1(TS ts,PetscReal t,Vec X,Vec A,PetscReal shiftA,Mat J,Mat P,void *ctx)\n{\n UserParams *user = (UserParams *)ctx;\n PetscReal Omega = user->Omega;\n PetscReal T = 0;\n PetscErrorCode ierr;\n PetscFunctionBegin;\n\n T = shiftA + (Omega*Omega);\n\n ierr = MatSetValue(P,0,0,T,INSERT_VALUES);CHKERRQ(ierr);\n ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n ierr = MatAssemblyEnd (P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n if (J != P) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n }\n\n PetscFunctionReturn(0);\n}\n#if PETSC_VERSION_LT(3,5,0)\nPetscErrorCode Tangent1_Legacy(TS ts,PetscReal t,Vec U,Vec V,PetscReal shift,Mat *J,Mat *P,MatStructure *m,void *ctx)\n{*m = SAME_NONZERO_PATTERN; return Tangent1(ts,t,U,V,shift,*J,*P,ctx);}\n#define Tangent1 Tangent1_Legacy\n#endif\n\n#undef __FUNCT__\n#define __FUNCT__ \"Residual2\"\nPetscErrorCode Residual2(TS ts,PetscReal t,Vec X,Vec V,Vec A,Vec R,void *ctx)\n{\n UserParams *user = (UserParams *)ctx;\n PetscReal Omega = user->Omega, Xi = user->Xi;\n PetscScalar *x,*v,*a,*r;\n PetscErrorCode ierr;\n PetscFunctionBegin;\n\n ierr = VecGetArray(X,&x);CHKERRQ(ierr);\n ierr = VecGetArray(V,&v);CHKERRQ(ierr);\n ierr = VecGetArray(A,&a);CHKERRQ(ierr);\n ierr = VecGetArray(R,&r);CHKERRQ(ierr);\n\n r[0] = a[0] + (2*Xi*Omega)*v[0] + (Omega*Omega)*x[0];\n\n ierr = VecRestoreArray(X,&x);CHKERRQ(ierr);\n ierr = VecRestoreArray(V,&v);CHKERRQ(ierr);\n ierr = VecRestoreArray(A,&a);CHKERRQ(ierr);\n ierr = VecRestoreArray(R,&r);CHKERRQ(ierr);\n\n ierr = VecAssemblyBegin(R);CHKERRQ(ierr);\n ierr = VecAssemblyEnd (R);CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"Tangent2\"\nPetscErrorCode Tangent2(TS ts,PetscReal t,Vec X,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P,void *ctx)\n{\n UserParams *user = (UserParams *)ctx;\n PetscReal Omega = user->Omega, Xi = user->Xi;\n PetscReal T = 0;\n PetscErrorCode ierr;\n PetscFunctionBegin;\n\n T = shiftA + shiftV * (2*Xi*Omega) + (Omega*Omega);\n\n ierr = MatSetValue(P,0,0,T,INSERT_VALUES);CHKERRQ(ierr);\n ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n ierr = MatAssemblyEnd (P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n if (J != P) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n }\n\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"Monitor\"\nPetscErrorCode Monitor(TS ts,PetscInt i,PetscReal t,Vec U,void *ctx)\n{\n const char *filename = (const char *)ctx;\n static FILE *fp = 0;\n Vec X,V;\n const PetscScalar *x,*v;\n TSConvergedReason reason;\n PetscErrorCode ierr;\n PetscFunctionBegin;\n if (i<0) PetscFunctionReturn(0); /*XXX temporary petsc-dev fix */\n\n if (!fp) {ierr = PetscFOpen(PETSC_COMM_SELF,filename,\"w\",&fp);CHKERRQ(ierr);}\n ierr = TSGetSolution2(ts,&X,&V);CHKERRQ(ierr);\n ierr = VecGetArrayRead(X,&x);CHKERRQ(ierr);\n ierr = VecGetArrayRead(V,&v);CHKERRQ(ierr);\n ierr = PetscFPrintf(PETSC_COMM_SELF,fp,\"%g %g %g\\n\",(double)t,(double)x[0],(double)v[0]);CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(X,&x);CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(V,&v);CHKERRQ(ierr);\n ierr = TSGetConvergedReason(ts,&reason); CHKERRQ(ierr);\n if (reason) {ierr = PetscFClose(PETSC_COMM_SELF,fp);CHKERRQ(ierr); fp=0;}\n\n PetscFunctionReturn(0);\n}\n\nEXTERN_C_BEGIN\nPetscErrorCode TSCreate_Alpha2(TS);\nEXTERN_C_END\n\n#undef __FUNCT__\n#define __FUNCT__ \"main\"\nint main(int argc, char *argv[]) {\n\n TS ts;\n Vec R;\n Mat J;\n Vec X,V;\n PetscScalar *x,*v;\n UserParams user;\n PetscBool out;\n char output[PETSC_MAX_PATH_LEN] = {0};\n PetscErrorCode ierr;\n\n ierr = PetscInitialize(&argc,&argv,0,0);CHKERRQ(ierr);\n ierr = TSRegister(TSALPHA2,TSCreate_Alpha2);CHKERRQ(ierr);\n\n user.Omega = 1.0;\n user.Xi = 0.0;\n ierr = PetscOptionsBegin(PETSC_COMM_SELF,\"\",\"Oscillator Options\",\"TS\");CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-frequency\",\"Frequency\",__FILE__,user.Omega,&user.Omega,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-damping\", \"Damping\", __FILE__,user.Xi, &user.Xi, NULL);CHKERRQ(ierr);\n ierr = PetscOptionsString(\"-output\",\"Output\",__FILE__,output,output,sizeof(output),&out);CHKERRQ(ierr);\n ierr = PetscOptionsEnd();CHKERRQ(ierr);\n if (out && !output[0]) {ierr = PetscStrcpy(output,\"Oscillator.out\");CHKERRQ(ierr);}\n\n ierr = TSCreate(PETSC_COMM_SELF,&ts);CHKERRQ(ierr);\n ierr = TSSetType(ts,TSALPHA2);CHKERRQ(ierr);\n ierr = TSSetDuration(ts,PETSC_MAX_INT,2*M_PI * 5);CHKERRQ(ierr);\n ierr = TSSetTimeStep(ts,0.01);CHKERRQ(ierr);\n\n ierr = VecCreateSeq(PETSC_COMM_SELF,1,&R);CHKERRQ(ierr);\n ierr = VecSetUp(R);CHKERRQ(ierr);\n ierr = MatCreateSeqDense(PETSC_COMM_SELF,1,1,NULL,&J);CHKERRQ(ierr);\n ierr = MatSetUp(J);CHKERRQ(ierr);\n if (user.Xi <= 0.0) {\n ierr = TSSetIFunction(ts,R,Residual1,&user);CHKERRQ(ierr);\n ierr = TSSetIJacobian(ts,J,J,Tangent1,&user);CHKERRQ(ierr);\n } else {\n ierr = TSSetIFunction2(ts,R,Residual2,&user);CHKERRQ(ierr);\n ierr = TSSetIJacobian2(ts,J,J,Tangent2,&user);CHKERRQ(ierr);\n }\n ierr = VecDestroy(&R);CHKERRQ(ierr);\n ierr = MatDestroy(&J);CHKERRQ(ierr);\n\n if (output[0]) {\n ierr = TSMonitorSet(ts,Monitor,output,NULL);CHKERRQ(ierr);\n }\n\n ierr = VecCreateSeq(PETSC_COMM_SELF,1,&X);CHKERRQ(ierr);\n ierr = VecCreateSeq(PETSC_COMM_SELF,1,&V);CHKERRQ(ierr);\n ierr = VecGetArray(X,&x);CHKERRQ(ierr);\n ierr = VecGetArray(V,&v);CHKERRQ(ierr);\n x[0] = 1.0;\n v[0] = 0.0;\n ierr = VecRestoreArray(X,&x);CHKERRQ(ierr);\n ierr = VecRestoreArray(V,&v);CHKERRQ(ierr);\n\n ierr = TSSetSolution2(ts,X,V);CHKERRQ(ierr);\n ierr = TSSetFromOptions(ts);CHKERRQ(ierr);\n ierr = TSSolve2(ts,X,V);CHKERRQ(ierr);\n\n ierr = VecDestroy(&X);CHKERRQ(ierr);\n ierr = VecDestroy(&V);CHKERRQ(ierr);\n ierr = TSDestroy(&ts);CHKERRQ(ierr);\n ierr = PetscFinalize();CHKERRQ(ierr);\n\n return 0;\n}\n", "meta": {"hexsha": "a37418b5ab8e3987408e175105fb548521a9547a", "size": 6922, "ext": "c", "lang": "C", "max_stars_repo_path": "test/Oscillator.c", "max_stars_repo_name": "otherlab/petiga", "max_stars_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-08-31T21:20:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T10:40:32.000Z", "max_issues_repo_path": "test/Oscillator.c", "max_issues_repo_name": "otherlab/petiga", "max_issues_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Oscillator.c", "max_forks_repo_name": "otherlab/petiga", "max_forks_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T12:55:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T10:40:40.000Z", "avg_line_length": 31.8986175115, "max_line_length": 117, "alphanum_fraction": 0.6930078012, "num_tokens": 2185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.42096312375149497}} {"text": "/* linalg/qr_ur.c\n * \n * Copyright (C) 2019, 2020 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * this module contains routines for the QR factorization of a matrix\n * using the recursive Level 3 BLAS algorithm of Elmroth and Gustavson with\n * additional modifications courtesy of Julien Langou.\n */\n\nstatic double qrtr_householder_transform (double *v0, gsl_vector * v);\n\n/*\ngsl_linalg_QR_UR_decomp()\n Compute the QR decomposition of the \"triangle on top of rectangle\" matrix\n\n [ S ] = Q [ R ]\n [ A ] [ 0 ]\n\nwhere S is N-by-N upper triangular and A is M-by-N dense.\n\nInputs: S - on input, upper triangular N-by-N matrix\n on output, R factor in upper triangle\n A - on input, dense M-by-N matrix\n on output, Householder matrix V\n T - (output) block reflector matrix, N-by-N\n\nNotes:\n1) Based on the Elmroth/Gustavson algorithm, taking into account the\nsparse structure of the S matrix\n\n2) The Householder matrix V has the special form:\n\n N\nV = [ I ] N\n [ V~ ] M\n\nThe matrix V~ is stored in A on output; the identity is not stored\n\n3) The orthogonal matrix is\n\nQ = I - V T V^T\n*/\n\nint\ngsl_linalg_QR_UR_decomp (gsl_matrix * S, gsl_matrix * A, gsl_matrix * T)\n{\n const size_t M = A->size1;\n const size_t N = S->size1;\n\n if (N != S->size2)\n {\n GSL_ERROR (\"S matrix must be square\", GSL_ENOTSQR);\n }\n else if (N != A->size2)\n {\n GSL_ERROR (\"S and A have different number of columns\", GSL_EBADLEN);\n }\n else if (T->size1 != N || T->size2 != N)\n {\n GSL_ERROR (\"T matrix has wrong dimensions\", GSL_EBADLEN);\n }\n else if (N == 1)\n {\n /* base case, compute Householder transform for single column matrix */\n double * T00 = gsl_matrix_ptr(T, 0, 0);\n double * S00 = gsl_matrix_ptr(S, 0, 0);\n gsl_vector_view v = gsl_matrix_column(A, 0);\n *T00 = qrtr_householder_transform(S00, &v.vector);\n return GSL_SUCCESS;\n }\n else\n {\n /*\n * partition matrices:\n *\n * N1 N2 N1 N2\n * N1 [ S11 S12 ] and N1 [ T11 T12 ]\n * N2 [ 0 S22 ] N2 [ 0 T22 ]\n * M [ A1 A2 ]\n */\n int status;\n const size_t N1 = N / 2;\n const size_t N2 = N - N1;\n\n gsl_matrix_view S11 = gsl_matrix_submatrix(S, 0, 0, N1, N1);\n gsl_matrix_view S12 = gsl_matrix_submatrix(S, 0, N1, N1, N2);\n gsl_matrix_view S22 = gsl_matrix_submatrix(S, N1, N1, N2, N2);\n\n gsl_matrix_view A1 = gsl_matrix_submatrix(A, 0, 0, M, N1);\n gsl_matrix_view A2 = gsl_matrix_submatrix(A, 0, N1, M, N2);\n\n gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1);\n gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2);\n gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2);\n\n /*\n * Eq. 2: recursively factor\n *\n * N1 N1\n * N1 [ S11 ] = Q1 [ R11 ] N1\n * N2 [ 0 ] [ 0 ] N2\n * M [ A1 ] [ 0 ] M\n */\n status = gsl_linalg_QR_UR_decomp(&S11.matrix, &A1.matrix, &T11.matrix);\n if (status)\n return status;\n\n /*\n * Eq. 3:\n *\n * N2 N2 N2\n * N1 [ R12 ] = Q1^T [ S12 ] = [ S12 - W ] N1\n * N2 [ S22~ ] [ S22 ] [ S22 ] N2\n * M [ A2~ ] [ A2 ] [ A2 - V1~ W ] M\n *\n * where W = T11^T ( S12 + V1~^T A2 ), using T12 as temporary storage, and\n *\n * N1\n * V1 = [ I ] N1\n * [ 0 ] N2\n * [ V1~ ] M\n */\n gsl_matrix_memcpy(&T12.matrix, &S12.matrix); /* W := S12 */\n gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A1.matrix, &A2.matrix, 1.0, &T12.matrix); /* W := S12 + V1~^T A2 */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &T11.matrix, &T12.matrix); /* W := T11^T W */\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A1.matrix, &T12.matrix, 1.0, &A2.matrix); /* A2 := A2 - V1~ W */\n gsl_matrix_sub(&S12.matrix, &T12.matrix); /* R12 := S12 - W */\n\n /*\n * Eq. 4: recursively factor\n *\n * [ S22~ ] = Q2~ [ R22 ]\n * [ A2~ ] [ 0 ]\n */\n status = gsl_linalg_QR_UR_decomp(&S22.matrix, &A2.matrix, &T22.matrix);\n if (status)\n return status;\n\n /*\n * Eq. 13: update T12 := -T11 * V1^T * V2 * T22\n *\n * where:\n *\n * N1 N2\n * V1 = [ I ] N1 V2 = [ 0 ] N1\n * [ 0 ] N2 [ I ] N2\n * [ V1~ ] M [ V2~ ] M\n *\n * Note: V1^T V2 = V1~^T V2~\n */\n\n gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A1.matrix, &A2.matrix, 0.0, &T12.matrix); /* T12 := V1~^T * V2~ */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &T11.matrix, &T12.matrix); /* T12 := -T11 * T12 */\n gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix); /* T12 := T12 * T22 */\n\n return GSL_SUCCESS;\n }\n}\n\n/*\nqrtr_householder_transform()\n This routine is an optimized version of\ngsl_linalg_householder_transform(), designed for the QR\ndecomposition of M-by-N matrices of the form:\n\nB = [ S ]\n [ A ]\n\nwhere S is N-by-N upper triangular, and A is M-by-N dense.\nThis routine computes a householder transformation (tau,v) of a \nx so that P x = [ I - tau*v*v' ] x annihilates x(1:n-1). x will\nbe a subcolumn of the matrix B, and so its structure will be:\n\nx = [ x0 ] <- 1 nonzero value for the diagonal element of S\n [ 0 ] <- N - j - 1 zeros, where j is column of matrix in [0,N-1]\n [ x ] <- M nonzero values for the dense part A\n\nInputs: v0 - pointer to diagonal element of S\n on input, v0 = x0;\n v - on input, x vector\n on output, householder vector v\n*/\n\nstatic double\nqrtr_householder_transform (double *v0, gsl_vector * v)\n{\n /* replace v[0:M-1] with a householder vector (v[0:M-1]) and\n coefficient tau that annihilate v[1:M-1] */\n\n double alpha, beta, tau ;\n \n /* compute xnorm = || [ 0 ; v ] ||, ignoring zero part of vector */\n double xnorm = gsl_blas_dnrm2(v);\n\n if (xnorm == 0) \n {\n return 0.0; /* tau = 0 */\n }\n\n alpha = *v0;\n beta = - GSL_SIGN(alpha) * hypot(alpha, xnorm) ;\n tau = (beta - alpha) / beta ;\n \n {\n double s = (alpha - beta);\n \n if (fabs(s) > GSL_DBL_MIN) \n {\n gsl_blas_dscal (1.0 / s, v);\n *v0 = beta;\n }\n else\n {\n gsl_blas_dscal (GSL_DBL_EPSILON / s, v);\n gsl_blas_dscal (1.0 / GSL_DBL_EPSILON, v);\n *v0 = beta;\n }\n }\n \n return tau;\n}\n", "meta": {"hexsha": "71aa27b28f34736aff43cd60eacd5eac0ca222b7", "size": 7647, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ur.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ur.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ur.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 30.95951417, "max_line_length": 129, "alphanum_fraction": 0.5632274094, "num_tokens": 2477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.42049287901864013}} {"text": "//Gets deltas (1st order) and delta-deltas (2nd order) differences of X.\n//Only the deltas and delta-deltas are output in Y.\n//Thus, Y must be pre-allocated to have twice the size of X.\n\n//I implement this just like FIR for speed and shorter code,\n//except non-causal and mid-sample of B is 0,\n//so I don't explicitly make B (e.g., B[n] just equals sc*n).\n\n//Note that this may treat edge samples differently than other code.\n//But this could be changed with a few lines of additional code here,\n//without changing the super-efficient FIR implementation.\n//That is, since out-of-range samps were assumed to be 0, nothing was\n//added to Y for them, so can just add something later.\n\n#include \n#include \n\n#ifdef __cplusplus\nnamespace ov {\nextern \"C\" {\n#endif\n\nint get_delta_deltas_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int N);\nint get_delta_deltas_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim, const int N);\n\n\nint get_delta_deltas_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int N)\n{\n const float z = 0.0f;\n int r, c, n;\n float sc = 1.0f;\n\n //Checks\n if (R<1) { fprintf(stderr,\"error in get_delta_deltas_s: R (nrows Y) must be positive\\n\"); return 1; }\n if (C<1) { fprintf(stderr,\"error in get_delta_deltas_s: C (ncols Y) must be positive\\n\"); return 1; }\n if (N<1) { fprintf(stderr,\"error in get_delta_deltas_s: N (delta winlength) must be positive\\n\"); return 1; }\n\n //Get sc (normalizer)\n for (n=2; n<=N; n++) { sc += n*n; }\n sc = 0.5f/sc;\n\n //Initialize Y\n cblas_scopy(2*R*C,&z,0,&Y[0],1);\n\n if (dim==0)\n {\n if (iscolmajor)\n {\n for (c=0; c\n#elif defined HAVE_ATLAS_CBLAS_H\n #include \n#endif\n}\n\nnamespace nm { namespace math {\n\n\n/*\n * Solves a system of linear equations A*X = B with a general NxN matrix A using the LU factorization computed by GETRF.\n *\n * From ATLAS 3.8.0.\n */\ntemplate \nint getrs(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE Trans, const int N, const int NRHS, const DType* A,\n const int lda, const int* ipiv, DType* B, const int ldb)\n{\n // enum CBLAS_DIAG Lunit, Uunit; // These aren't used. Not sure why they're declared in ATLAS' src.\n\n if (!N || !NRHS) return 0;\n\n const DType ONE = 1;\n\n if (Order == CblasColMajor) {\n if (Trans == CblasNoTrans) {\n nm::math::laswp(NRHS, B, ldb, 0, N, ipiv, 1);\n nm::math::trsm(Order, CblasLeft, CblasLower, CblasNoTrans, CblasUnit, N, NRHS, ONE, A, lda, B, ldb);\n nm::math::trsm(Order, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb);\n } else {\n nm::math::trsm(Order, CblasLeft, CblasUpper, Trans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb);\n nm::math::trsm(Order, CblasLeft, CblasLower, Trans, CblasUnit, N, NRHS, ONE, A, lda, B, ldb);\n nm::math::laswp(NRHS, B, ldb, 0, N, ipiv, -1);\n }\n } else {\n if (Trans == CblasNoTrans) {\n nm::math::trsm(Order, CblasRight, CblasLower, CblasTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb);\n nm::math::trsm(Order, CblasRight, CblasUpper, CblasTrans, CblasUnit, NRHS, N, ONE, A, lda, B, ldb);\n nm::math::laswp(NRHS, B, ldb, 0, N, ipiv, -1);\n } else {\n nm::math::laswp(NRHS, B, ldb, 0, N, ipiv, 1);\n nm::math::trsm(Order, CblasRight, CblasUpper, CblasNoTrans, CblasUnit, NRHS, N, ONE, A, lda, B, ldb);\n nm::math::trsm(Order, CblasRight, CblasLower, CblasNoTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb);\n }\n }\n return 0;\n}\n\n\n/*\n* Function signature conversion for calling LAPACK's getrs functions as directly as possible.\n*\n* For documentation: http://www.netlib.org/lapack/double/dgetrs.f\n*\n* This function should normally go in math.cpp, but we need it to be available to nmatrix.cpp.\n*/\ntemplate \ninline int clapack_getrs(const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE trans, const int n, const int nrhs,\n const void* a, const int lda, const int* ipiv, void* b, const int ldb) {\n return getrs(order, trans, n, nrhs, reinterpret_cast(a), lda, ipiv, reinterpret_cast(b), ldb);\n}\n\n\n} } // end nm::math\n\n#endif // GETRS_H\n", "meta": {"hexsha": "8a6ddb268a7ee32a374b73b9691cc7e8cb834648", "size": 5152, "ext": "h", "lang": "C", "max_stars_repo_path": "ext/nmatrix/math/getrs.h", "max_stars_repo_name": "blackwinter-attic/nmatrix", "max_stars_repo_head_hexsha": "cb2cd26195d544ac03b347e293c071faed6f90a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ext/nmatrix/math/getrs.h", "max_issues_repo_name": "blackwinter-attic/nmatrix", "max_issues_repo_head_hexsha": "cb2cd26195d544ac03b347e293c071faed6f90a6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ext/nmatrix/math/getrs.h", "max_forks_repo_name": "blackwinter-attic/nmatrix", "max_forks_repo_head_hexsha": "cb2cd26195d544ac03b347e293c071faed6f90a6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6307692308, "max_line_length": 125, "alphanum_fraction": 0.6843944099, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.42040309100541867}} {"text": "#include \"matrix.h\"\n#include \n#include \n#include \n#include \n\nMatrix *create_mat(char *path) {\n Matrix *m = malloc(sizeof(Matrix));\n m->row_len = 0;\n m->col_len = 0;\n FILE *myfile = fopen(path, \"r\");\n int ch = 0;\n while (ch != EOF) {\n ch = fgetc(myfile);\n if (m->row_len == 0 && ch == ' ') {\n m->col_len++;\n }\n if (ch == '\\n') {\n m->row_len++;\n }\n };\n\n m->col_len++;\n\n m->p_mat = calloc(m->row_len, sizeof(float *));\n for (int i = 0; i < m->row_len; i++) {\n m->p_mat[i] = calloc(m->col_len, sizeof(float));\n }\n\n rewind(myfile);\n\n for (int i = 0; i < m->row_len; i++) {\n for (int j = 0; j < m->col_len; j++) {\n if (!fscanf(myfile, \"%f\", &m->p_mat[i][j])) {\n break;\n }\n }\n }\n\n fclose(myfile);\n return m;\n}\n\nvoid delete_mat(Matrix *mat) {\n for (int i = 0; i < mat->row_len; i++) {\n free(mat->p_mat[i]);\n }\n free(mat->p_mat);\n free(mat);\n}\n\nvoid copy_mat(Matrix *target, Matrix *source) {\n delete_mat(target);\n target->row_len = source->row_len;\n target->col_len = source->col_len;\n target->p_mat = calloc(target->row_len, sizeof(float *));\n for (int i = 0; i < target->row_len; i++) {\n target->p_mat[i] = calloc(target->col_len, sizeof(float));\n }\n for (int i = 0; i < target->row_len; i++) {\n for (int j = 0; j < target->col_len; j++) {\n target->p_mat[i][j] = source->p_mat[i][j];\n }\n }\n}\n\nMatrix *multiple_mat(Matrix *mat1, Matrix *mat2) {\n Matrix *result = malloc(sizeof(Matrix));\n result->row_len = mat1->row_len;\n result->col_len = mat2->col_len;\n result->p_mat = calloc(result->row_len, sizeof(float *));\n for (int i = 0; i < result->row_len; ++i)\n result->p_mat[i] = calloc(result->col_len, sizeof(float));\n\n#pragma omp parallel for\n for (int i = 0; i < result->row_len; i++) {\n for (int k = 0; k < mat1->col_len; k++) {\n float tmp = mat1->p_mat[i][k];\n for (int j = 0; j < result->col_len; j++) {\n result->p_mat[i][j] += tmp * mat2->p_mat[k][j];\n }\n }\n }\n\n return result;\n}\nvoid write_mat(char *path, Matrix *mat) {\n FILE *myfile = fopen(path, \"w\");\n for (int i = 0; i < mat->row_len; i++) {\n for (int j = 0; j < mat->col_len; j++) {\n if (j == mat->col_len - 1) {\n fprintf(myfile, \"%f\\n\", mat->p_mat[i][j]);\n } else {\n fprintf(myfile, \"%f \", mat->p_mat[i][j]);\n }\n }\n }\n}\n\nvoid display_mat(Matrix *m1) {\n for (int i = 0; i < m1->row_len; i++) {\n for (int j = 0; j < m1->col_len; j++) {\n if (j == m1->col_len - 1) {\n printf(\"%f\\n\", m1->p_mat[i][j]);\n } else {\n printf(\"%f \", m1->p_mat[i][j]);\n }\n }\n }\n}\n\nMatrix *calc_with_OpenBLAS(Matrix *m1, Matrix *m2) {\n Matrix *result = malloc(sizeof(Matrix));\n result->row_len = m1->row_len;\n result->col_len = m2->col_len;\n result->p_mat = calloc(result->row_len, sizeof(float *));\n for (int i = 0; i < result->row_len; ++i)\n result->p_mat[i] = calloc(result->col_len, sizeof(float));\n const int M = m1->row_len;\n const int N = m2->col_len;\n const int K = m1->col_len;\n int lda = K;\n int ldb = N;\n int ldc = N;\n float *A = calloc(M * K, sizeof(float));\n float *B = calloc(K * N, sizeof(float));\n float *C = calloc(M * N, sizeof(float));\n int k = 0;\n for (int i = 0; i < M; i++) {\n for (int j = 0; j < K; j++) {\n A[k] = m1->p_mat[i][j];\n k += 1;\n }\n }\n k = 0;\n for (int i = 0; i < K; i++) {\n for (int j = 0; j < N; j++) {\n B[k] = m2->p_mat[i][j];\n k += 1;\n }\n }\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.0f, A, lda,\n B, ldb, 1.0f, C, ldc);\n k = 0;\n for (int i = 0; i < result->row_len; i++) {\n for (int j = 0; j < result->col_len; j++) {\n result->p_mat[i][j] = C[k];\n k++;\n }\n }\n free(A);\n free(B);\n free(C);\n return result;\n}", "meta": {"hexsha": "84b44490bc990c46c11dbb56b94d5abf29aee154", "size": 3834, "ext": "c", "lang": "C", "max_stars_repo_path": "project/3/matrix.c", "max_stars_repo_name": "Aries-Dawn/Cpp-Program-Design", "max_stars_repo_head_hexsha": "9d4fc9a902fff2f76e41314f5d6c52871d30a511", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/3/matrix.c", "max_issues_repo_name": "Aries-Dawn/Cpp-Program-Design", "max_issues_repo_head_hexsha": "9d4fc9a902fff2f76e41314f5d6c52871d30a511", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/3/matrix.c", "max_forks_repo_name": "Aries-Dawn/Cpp-Program-Design", "max_forks_repo_head_hexsha": "9d4fc9a902fff2f76e41314f5d6c52871d30a511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.735483871, "max_line_length": 79, "alphanum_fraction": 0.5219092332, "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.42021195567875247}} {"text": "/**\n * Subroutines to correct for the intra-pixel sensitivity\n * variation in e.g. NICMOS pixels. There are routines\n * to corect both, an extracted SPC's and a list\n * of PET pixels.\n *\n */\n#include \"fitsio.h\"\n#include \n#include \n#include \n#include \"aXe_grism.h\"\n#include \"aXe_utils.h\"\n#include \"aXe_errors.h\"\n#include \"spc_spc.h\"\n#include \"spce_pathlength.h\"\n#include \"fringe_conf.h\"\n#include \"spc_wl_calib.h\"\n#include \"trfit_utils.h\"\n#include \"ipixcorr_utils.h\"\n\n#define MAX(x,y) (((x)>(y))?(x):(y))\n#define MIN(x,y) (((x)<(y))?(x):(y))\n\n/**\n * Function: get_intpix_corr\n * The function determines and returns a correction factor with\n * values stored in an interpolator at a certain wavelength.\n * To derive the result the dispersion solution is inverted,\n * then the trace position for the wavelength is determined.\n * The the fractional pixel value in y is computed and the\n * corresponding correction factor is returned.\n *\n * Parameters:\n * @param actbeam - beam to correct\n * @param cdisp - the dispersion coefficients for the beam\n * @param ipcorr - the correction values stored in an interpolator\n * @param lambda - the wavelength to correct\n *\n * Returns:\n * @return cfactor - the correction factor\n */\ndouble\nget_intpix_corr(beam *actbeam, gsl_vector *cdisp, interpolator *ipcorr,\n\t\tfloat lambda)\n{\n double tlength;\n\n double xvalue;\n double yfract;\n\n double cfactor=0.0;\n\n // get the trace length for the dispersion\n // solution and wavelength\n tlength = get_tlength_from_dispersion(cdisp, lambda);\n\n // compute the x-offset from the reference point\n // for this trace length value\n xvalue = get_xvalue_from_tlength(actbeam, tlength);\n\n // compute the fractional y-value\n yfract = get_yfract_for_xvalue(actbeam, xvalue);\n\n // get the correction factor\n cfactor = eval_interp(ipcorr, yfract);\n\n fprintf(stdout, \"xdiff: %e, yfrac: %e, factor: %e \", xvalue, yfract, cfactor);\n\n //fprintf(stdout, \"lambda: %f, tlength: %f, xval: %f, yval: %f, yfract: %f, cfactor: %f\\n\",\n // \t lambda, tlength, actbeam->refpoint.x+xvalue, actbeam->refpoint.y+actbeam->spec_trace->func (xvalue, actbeam->spec_trace->data),yfract, cfactor);\n\n // return the correction factor\n return cfactor;\n}\n\n\n/**\n * Function: get_yfract_for_xvalue\n * The function computes the fractional y-value for a trace\n * position in a beam. The trace position is given as the\n * x-offset position with respect to the reference position\n *\n * Parameters:\n * @param actbeam - beam to correct\n * @param xvalue - the x-value\n *\n * Returns:\n * @return yfract - the fractional y-value\n */\ndouble\nget_yfract_for_xvalue(const beam *actbeam, double xvalue)\n{\n double dy;\n double yabs;\n double yfract;\n\n // compute the y-value relative to the reference point\n dy = actbeam->spec_trace->func (xvalue, actbeam->spec_trace->data);\n\n // compute the absolute y-value on the chip\n yabs = actbeam->refpoint.y + dy;\n\n // compute the fractional pixel of this y-value\n yfract = yabs - floor(yabs);\n\n // return the fractional y-value\n return yfract;\n}\n\n\n/**\n * Function: get_xvalue_from_tlength\n * The function computes the x-offset position from the reference point\n * for a given tracelength in a given beam.\n * The solution is numerically derived and therefore\n * does work for any reasonable tracefunction.\n *\n * Parameters:\n * @param actbeam - the beam to compute the x-offset\n * @param tlength - tracelength\n *\n * Returns:\n * @return xdiff - the x-offset\n */\ndouble\nget_xvalue_from_tlength(beam *actbeam, double tlength)\n{\n int iter=0;\n int status;\n\n double xdiff=0.0;\n d_point x_interv;\n\n // define and initialize the solver\n const gsl_root_fsolver_type *T = gsl_root_fsolver_brent;\n gsl_root_fsolver *s = gsl_root_fsolver_alloc (T);\n\n gsl_function F;\n tlength_pars *tpars;\n\n // derive the x-interval from the beam boundaries\n x_interv = get_xinterv_from_beam(actbeam);\n // fprintf(stdout, \"xpos: %f, ypos: %f\\n\", x_interv.x, x_interv.y);\n\n // allocate and fill the parameters\n tpars = (tlength_pars *) malloc(sizeof(tlength_pars));\n tpars->actbeam = actbeam;\n tpars->tlength = tlength;\n\n // fille the GSL-function\n F.function = &zero_tlength;\n F.params = tpars;\n\n // set the boundaries for the solver\n gsl_root_fsolver_set (s, &F, x_interv.x, x_interv.y);\n\n\n // iterate to find the zeropoint\n do\n {\n // increment the iteration counter\n iter++;\n\n // iterate on the solver\n status = gsl_root_fsolver_iterate (s);\n\n // get a new guess from the solver\n xdiff = gsl_root_fsolver_root (s);\n\n // derive and set new boundaries\n x_interv.x = gsl_root_fsolver_x_lower (s);\n x_interv.y = gsl_root_fsolver_x_upper (s);\n\n // check the accuracy\n status = gsl_root_test_interval (x_interv.x, x_interv.y,\n\t\t\t\t 0, 0.0001);\n //--------------CAVEAT---------------------------------------\n // until March 28th 08 the code, wriongly was:\n //status = gsl_root_test_interval (x_interv.x, x_interv.x,\n // 0, 0.0001);\n // somehow this made no difference.....\n //-----------------------------------------------------------\n }\n // check for the break condition\n while (status == GSL_CONTINUE && iter < MAX_ITER);\n\n // free the memory\n free(tpars);\n\n // free the memory\n gsl_root_fsolver_free (s);\n\n // return the result\n return xdiff;\n}\n\n/**\n * Function: zero_tlength\n * Helper function for the 1D-root finding routine.\n * Evaluates a functional value at the position given\n * in the first parameter using the values given\n * as second parameter.\n *\n * Parameters:\n * @param x - the independent value\n * @param params - ingredients to evaluate the function value\n *\n * Returns:\n * @return tzero - the function value\n */\ndouble\nzero_tlength (double x, void *params)\n{\n double tzero;\n\n // extract the components from the parameter-structure\n beam *actbeam = ((tlength_pars *) params)->actbeam;\n double tlength = ((tlength_pars *) params)->tlength;\n\n // compute the function value\n tzero = actbeam->spec_trace->path_len (x, actbeam->spec_trace->data) - tlength;\n\n // return the function value\n return tzero;\n}\n\n\n/**\n * Function: get_xinterv_from_beam\n * Determines the maximum and minimum extension of a given\n * beam along the x-axis. For security the interval is extended\n * at both ends by a fixed amount (quantified in the header-file).\n *\n * Parameters:\n * @param actbeam - the beam\n *\n * Returns:\n * @return x_interv - xmin, xmax covered by the beam\n */\nd_point\nget_xinterv_from_beam(const beam *actbeam)\n{\n d_point x_interv;\n\n // compute the beam extension\n // towards the negative x-axis\n x_interv.x = (double)MIN(actbeam->corners[0].x,\n\t\t\t MIN(actbeam->corners[1].x,\n\t\t\t MIN(actbeam->corners[2].x,\n\t\t\t\t actbeam->corners[3].x)))-actbeam->refpoint.x - INTERVEXT;\n\n // compute the beam extension\n // towards the positive x-axis\n x_interv.y = (double)MAX(actbeam->corners[0].x,\n\t\t\t MAX(actbeam->corners[1].x,\n\t\t\t MAX(actbeam->corners[2].x,\n\t\t\t\t actbeam->corners[3].x)))-actbeam->refpoint.x + INTERVEXT;\n\n // return the interval\n return x_interv;\n}\n\n\n/**\n * Function: get_tlength_from_dispersion\n * The function computes and returnes the trace length for\n * a given diseprsion solution and wavelength. The tracelength\n * value is returned. Currently only linear and quadratic\n * dispersio solution are considered.\n *\n * Parameters:\n * @param cdisp - the dispersion coefficient polynomial\n * @param lambda - the wavelength\n *\n * Returns:\n * @return tlength - the trace length\n */\ndouble\nget_tlength_from_dispersion(gsl_vector *cdisp, float lambda)\n{\n double tlength=0.0;\n //double tlength_a=0.0;\n double det;\n\n // check whether the polynomial is linear\n if (cdisp->size == 2)\n {\n // compute the tracelength for linear dispersion\n tlength = (lambda-gsl_vector_get(cdisp, 0))/gsl_vector_get(cdisp, 1);\n }\n // check whether the polynomial is quadratic\n else if (cdisp->size == 3)\n {\n // compute the determinante\n det = gsl_vector_get(cdisp, 1) * gsl_vector_get(cdisp, 1)\n\t\t - 4.0 * gsl_vector_get(cdisp, 0) * gsl_vector_get(cdisp, 2);\n\n // gove error if det < 0.0\n if (det < 0.0)\n\taXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"get_tlength_from_dispersion: Can not determine the tracelength since det < 0.0!\\n\");\n\n // compute the tracelength\n tlength = (-gsl_vector_get(cdisp, 1)+sqrt(det))/(2.0*gsl_vector_get(cdisp, 2));\n // tlength_a = (-gsl_vector_get(cdisp, 1)-sqrt(det))/(2.0*gsl_vector_get(cdisp, 2));\n // fprintf(stdout, \"plus: %f, minus: f\\n\", tlength, tlength_a);\n }\n else\n {\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"get_tlength_from_dispersion: The dispersion solution has %i coefficients and can not be inverted!\\n\", cdisp->size);\n }\n\n // return the tracelength\n return tlength;\n}\n\n\n/**\n * Function: condense_dispersion\n * The function strips off leading zeroes in the high order terms\n * of the dispersion solution derived from the configuration file.\n * These usually become a problem in the inversion to derive the\n * tracelength.\n *\n * Parameters:\n * @param disp__input - the configuration file dispersion\n *\n * Returns:\n * @return cdisp - the effective dispersion relation\n */\ngsl_vector *\ncondense_dispersion(gsl_vector *disp_input)\n{\n int index;\n int i;\n\n gsl_vector *cdisp;\n\n // get the size of the incomingg dispersion\n // vector\n index = disp_input->size;\n\n // determine the true size by subtracting\n // high order zeros\n while (index > -1 && !gsl_vector_get(disp_input, index-1))\n index--;\n\n // allocate space for the new vector\n cdisp = gsl_vector_alloc(index);\n\n // tranasfer the relevant values\n // from the old to the new vector\n for (i=0; i < index; i++)\n gsl_vector_set(cdisp, i, gsl_vector_get(disp_input, i));\n\n // return the new dispersion vector\n return cdisp;\n}\n\n/**\n * Function: fitting_ipc_corr\n *\n * Parameters:\n * @param actbeam - the beam to examine\n * @param conf_file_path - the full pathname too the configuration file\n * @param ipcorr - the interpolator with the correction factor\n * @param SPC - the full spectrum to correct\n * @param obs - the grism image\n * @param data_matrix - background subtracted grism image\n * @param ipc_file_path - file name for the phase data\n *\n * Returns:\n * @return icorr - marker whether the correction was applied or not (1/0)\n */\nint\nfitting_ipc_corr(beam act_beam, char conf_file_path[], interpolator *ipcorr,\n\t\t full_spectr *SPC, observation *obs, gsl_matrix *data_matrix,\n\t\t char ipc_file_path[], beam *beam_ptr)\n{\n aperture_conf *conf;\n\n d_point fit_qual;\n\n int icorr = 0;\n\n trace_func *tracefun = act_beam.spec_trace;\n double *tracedata = (double *)(tracefun->data);\n\n // load the configuration file\n conf = get_aperture_descriptor(conf_file_path);\n\n // determine the phase data and fix the phase\n // by fitting a function to it\n fit_qual = kappa_sigma_klipp_ipc(conf, obs, data_matrix, act_beam, ipc_file_path);\n\n // report on the shift and the quality\n fprintf(stdout, \"shift-difference: %e, quality: %e\\n\", fit_qual.x, fit_qual.y);\n\n // check whether the quality is good enough\n if (fit_qual.y < MAXQUALITY)\n {\n // apply a correction to the\n // reference point to achive the\n // right corrections\n act_beam.refpoint.y += fit_qual.x;\n beam_ptr->refpoint.y += fit_qual.x;\n beam_ptr->ignore = -100;\n\n // report the new y-shift\n fprintf(stdout, \"new y-shift: %e\\n\", act_beam.refpoint.y - (double)(int)(act_beam.refpoint.y + tracedata[1]));\n\n // apply the sensitivity correction to the spectrum\n intpix_corr_beam(act_beam, conf_file_path, ipcorr, SPC);\n\n // set the correction marker\n icorr=1;\n }\n\n // free allocated memory\n free_aperture_conf(conf);\n\n // return the marker\n return icorr;\n}\n\n/**\n * Function: intpix_corr_beam\n * The functio corrects a full spectrum for the intrapixel sensitivity\n * variations.\n * For every spectral element its fractional y-value is determined,\n * and then the correction factor for this y-value is computed\n * and applied to the appropriate elements of the spectral bin.\n *\n * Parameters:\n * @param actbeam - the beam to examine\n * @param conf_file_path - the full pathname too the configuration file\n * @param ipcorr - the interpolator with the correction factor\n * @param SPC - the full spectrum to correct\n *\n * Returns:\n * @return -\n */\nvoid\nintpix_corr_beam(beam actbeam, char conf_file_path[], interpolator *ipcorr,\n\t\t full_spectr *SPC)\n{\n int index=0;\n int for_grism=1;\n\n double cfactor;\n\n double lambda;\n\n gsl_vector *cdisp;\n\n d_point pixel;\n\n dispstruct *beam_disp;\n\n aperture_conf *conf;\n\n // load the configuration file\n conf = get_aperture_descriptor(conf_file_path);\n\n // check whether it is grism (for_grism=1)\n // or prism (for_grism=0) data\n // give an error if there is a prism solution\n for_grism = check_for_grism (conf_file_path, actbeam.ID);\n if (!for_grism)\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"intpix_corr_beam: Only grism dispersion solution can be corrected.\\n\");\n\n // get the wavelength dispersion relation at\n // position \"refpoint\". conf->refx and conf->refy\n // are used at this point to allow for a non (0,0) centered\n // 2D field dependence.\n pixel.x = actbeam.refpoint.x - conf->refx;\n pixel.y = actbeam.refpoint.y - conf->refy;\n\n // derive the dispersion at the object position\n beam_disp = get_dispstruct_at_pos(conf_file_path, for_grism,\n\t\t\t\t actbeam.ID, pixel);\n\n // skipp high order zeroes in the dispersion solution\n cdisp = condense_dispersion(beam_disp->pol);\n\n for (index=0; index < SPC->nelems; index++)\n {\n lambda = SPC->fgr_spec->spec[index].lambda_mean;\n\n if (!gsl_isnan (lambda) && lambda)\n\t{\n\t cfactor = get_intpix_corr(&actbeam, cdisp, ipcorr, lambda);\n\n \t fprintf(stdout, \"lambda: %e, factor: %e\\n\", lambda, cfactor);\n\t /*\n\t SPC->fgr_spec->spec[index].count = SPC->fgr_spec->spec[index].count / cfactor;\n\t SPC->fgr_spec->spec[index].error = SPC->fgr_spec->spec[index].error / cfactor;\n\t SPC->fgr_spec->spec[index].flux = SPC->fgr_spec->spec[index].flux / cfactor;\n\t SPC->fgr_spec->spec[index].ferror = SPC->fgr_spec->spec[index].ferror / cfactor;\n\n\t SPC->bck_spec->spec[index].count = SPC->bck_spec->spec[index].count / cfactor;\n\t SPC->bck_spec->spec[index].error = SPC->bck_spec->spec[index].error / cfactor;\n\t SPC->bck_spec->spec[index].flux = SPC->bck_spec->spec[index].flux / cfactor;\n\t SPC->bck_spec->spec[index].ferror = SPC->bck_spec->spec[index].ferror / cfactor;\n\n\t SPC->obj_spec->spec[index].count = SPC->obj_spec->spec[index].count / cfactor;\n\t SPC->obj_spec->spec[index].error = SPC->obj_spec->spec[index].error / cfactor;\n\t SPC->obj_spec->spec[index].flux = SPC->obj_spec->spec[index].flux / cfactor;\n\t SPC->obj_spec->spec[index].ferror = SPC->obj_spec->spec[index].ferror / cfactor;\n\n\t this is the wqrong version!!\n\t SPC->fgr_spec->spec[index].count = SPC->fgr_spec->spec[index].count * cfactor;\n\t SPC->fgr_spec->spec[index].error = SPC->fgr_spec->spec[index].error * cfactor;\n\t SPC->fgr_spec->spec[index].flux = SPC->fgr_spec->spec[index].flux * cfactor;\n\t SPC->fgr_spec->spec[index].ferror = SPC->fgr_spec->spec[index].ferror * cfactor;\n\n\t SPC->bck_spec->spec[index].count = SPC->bck_spec->spec[index].count * cfactor;\n\t SPC->bck_spec->spec[index].error = SPC->bck_spec->spec[index].error * cfactor;\n\t SPC->bck_spec->spec[index].flux = SPC->bck_spec->spec[index].flux * cfactor;\n\t SPC->bck_spec->spec[index].ferror = SPC->bck_spec->spec[index].ferror * cfactor;\n\n\t SPC->obj_spec->spec[index].count = SPC->obj_spec->spec[index].count * cfactor;\n\t SPC->obj_spec->spec[index].error = SPC->obj_spec->spec[index].error * cfactor;\n\t SPC->obj_spec->spec[index].flux = SPC->obj_spec->spec[index].flux * cfactor;\n\t SPC->obj_spec->spec[index].ferror = SPC->obj_spec->spec[index].ferror * cfactor;\n\t */\n\t}\n }\n\n // free the configuration structure\n free_aperture_conf(conf);\n\n // free the dispersion struct\n free_dispstruct(beam_disp);\n\n // free the memory for the dispersion\n gsl_vector_free(cdisp);\n}\n\n\n/**\n * Function: get_ipc_lambdas\n * The function computes the wavelengths for a list of x-offsets from the\n * reference point of a certain beam. The wavelength values are\n * returned as a gsl-vector.\n *\n * Parameters:\n * @param actbeam - the beam\n * @param conf_file_path - the full path to the aXe configuration file\n * @param xvalues - the list of x-offsets\n *\n * Returns:\n * @return lambdas - the list of wavelength values\n */\ngsl_vector *\nget_ipc_lambdas(const beam actbeam, char conf_file_path[], gsl_vector *xvalues)\n{\n aperture_conf *conf;\n\n dispstruct *disp;\n calib_function *wl_calib;\n\n gsl_vector *lambdas;\n\n d_point pixel;\n int for_grism;\n\n int i;\n\n // load the configuration file\n conf = get_aperture_descriptor(conf_file_path);\n\n // check whether it is grism (for_grism=1)\n // or prism (for_grism=0) data\n for_grism = check_for_grism (conf_file_path, actbeam.ID);\n\n // determine the referencee point position\n pixel.x = actbeam.refpoint.x - conf->refx;\n pixel.y = actbeam.refpoint.y - conf->refy;\n\n // determine the dispersion at the reference point\n disp = get_dispstruct_at_pos(conf_file_path, for_grism,\n\t\t\t actbeam.ID,pixel);\n\n // make a calibration structure from the dispersion\n wl_calib = create_calib_from_gsl_vector(for_grism, disp->pol);\n\n // convert the x-values to tracelength-values\n abscissa_to_pathlength (actbeam.spec_trace, xvalues);\n\n // allocate memory for the wavelengths\n lambdas = gsl_vector_alloc(xvalues->size);\n\n // go over all tracelength values\n for (i=0; i < (int)xvalues->size; i++)\n {\n // determine and store the wavelength for each tracelength\n gsl_vector_set(lambdas, i,\n\t\t wl_calib->func(gsl_vector_get(xvalues, i), wl_calib->order,\n\t\t\t\t wl_calib->coeffs));\n }\n\n // free the configuration structure\n free_aperture_conf(conf);\n\n // free the memory in the calibration structure\n free_calib(wl_calib);\n\n // free the dispersion structure\n free_dispstruct(disp);\n\n // return the wavelengths\n return lambdas;\n}\n\n\n/**\n * Function: get_ipc_cvalues\n * The function computes the intra-pixel correction factors for a certain\n * beam on a set of trace positions specified by their x-offset from\n * the reference point.\n * For every x-offset position the trace positon and its fractional y-pixel\n * (in absolute coordinates) is evaluated. Then the correction factor is\n * determined using the input interpolator.\n *\n * Parameters:\n * @param actbeam - the beam to correct\n * @param ipcorr - the correction values depending on fractional y-pixel\n * @param xvalues - the list x-offsets from the reference point\n *\n * Returns:\n * @return cvalues - the list of correction values\n */\ngsl_vector *\nget_ipc_cvalues(const beam actbeam, interpolator *ipcorr, gsl_vector *xvalues)\n{\n gsl_vector *cvalues;\n double yfract=0.0;\n int i;\n\n // allocate memory\n cvalues = gsl_vector_alloc(xvalues->size);\n\n // go over all x-values\n for (i=0; i < (int)xvalues->size; i++)\n {\n // determine the y-fraction for the x-value\n yfract = get_yfract_for_xvalue(&actbeam, gsl_vector_get(xvalues, i));\n\n // detyermine and store the correction factor in the array\n gsl_vector_set(cvalues, i, eval_interp(ipcorr, yfract));\n }\n\n // return the array\n return cvalues;\n}\n\n\n/**\n * Function: get_ipc_xvalues\n * The function computes a list of x-offsets from the reference\n * point of a beam. the regularly space offsets span the range\n * of x-values covered by the pixels of the beam.\n *\n * Parameters:\n * @param actbeam - the beam to compute the x-offsets for\n *\n * Returns:\n * @return xvalues - the list of x-offsets\n */\ngsl_vector *\nget_ipc_xvalues(const beam actbeam)\n{\n gsl_vector *xvalues;\n d_point xrange;\n\n int npoints;\n int i;\n\n // determine the x-range covered by the beam\n xrange = get_xinterv_from_beam(&actbeam);\n\n // determine the number of points within the x-range\n npoints = (xrange.y - xrange.x) / XSTEPSIZE + 1;\n\n // allocate and fill a proper vector\n // with the x-values\n xvalues = gsl_vector_alloc(npoints);\n for (i=0; i < npoints; i++)\n {\n gsl_vector_set(xvalues, i, xrange.x + (double)i * XSTEPSIZE);\n }\n\n // return the vector with the x-values\n return xvalues;\n}\n\n\n/**\n * Function: get_ipclambda\n * The function creates an interpolator for the intra-pixel correction\n * as a function of wavelength based on this correction as function\n * of fractional y-pixel and the full calibration information\n * on a beam.\n * The interpolator is created after stepping along the beam trace\n * and combining the wavelength values with the correction values\n * at the trace positions.\n *\n * Parameters:\n * @param actbeam - the beam to find the correction values for\n * @param conf_file_path - the full path to the aXe cofiguration file\n * @param ipcorr - the correction values as function of y-fraction\n *\n * Returns:\n * @return ipclambda - the correction values as function of wavelength\n */\ninterpolator *\nget_ipclambda(beam actbeam, char conf_file_path[],\n\t interpolator *ipcorr)\n{\n gsl_vector *xvalues;\n gsl_vector *cvalues;\n gsl_vector *lambdas;\n\n double *cv;\n double *lv;\n\n interpolator *ipclambda;\n\n int i=0;\n int j=0;\n\n // get the x values around the reference point\n xvalues = get_ipc_xvalues(actbeam);\n\n // get the correction factors for these x-values\n cvalues = get_ipc_cvalues(actbeam, ipcorr, xvalues);\n\n // get the wavelength at the correction factors\n lambdas = get_ipc_lambdas(actbeam, conf_file_path, xvalues);\n\n // allocate memory for the dependent values\n cv = (double *) malloc(cvalues->size * sizeof(double));\n if (!cv) {\n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t \"Memory allocation failed\");\n }\n\n // allocate memory for the independent values\n lv = (double *) malloc(cvalues->size * sizeof(double));\n if (!lv) {\n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t \"Memory allocation failed\");\n }\n\n if (gsl_vector_get(lambdas, lambdas->size-1) > gsl_vector_get(lambdas, 0))\n {\n // transfer the values from the\n // gsl vectors to the c-vectors\n for (i = 0; i < (int)cvalues->size; i++)\n\t{\n\t cv[i] = gsl_vector_get(cvalues, i);\n\t lv[i] = gsl_vector_get(lambdas, i);\n\t}\n }\n else\n {\n // transfer the values from the\n // gsl vectors to the c-vectors\n // invert the order from the\n // gsl-vectors\n j = cvalues->size - 1;\n for (i = 0; i < (int)cvalues->size; i++)\n\t{\n\t cv[j] = gsl_vector_get(cvalues, i);\n\t lv[j] = gsl_vector_get(lambdas, i);\n\t j--;\n\t}\n }\n\n // create the interpolator\n ipclambda = create_interp(cvalues->size, FILTER_INTERP_TYPE, lv, cv);\n\n\n // free the memory allocated to\n // the vectors\n gsl_vector_free(xvalues);\n gsl_vector_free(cvalues);\n gsl_vector_free(lambdas);\n\n // return the interpolator\n return ipclambda;\n}\n\n\n/**\n * Function: apply_corr_pet\n * The function applies an intra-pixel sensitivity correction to\n * a list of PET pixels. The correction values are given depending\n * on the wavelength of the pixel, and are applied to the PET pixels\n * in place.\n *\n * Parameters:\n * @param ipclambda - the ipc correction factor as function of wavelength\n * @param PET - the list of PET pixels to correct\n *\n * Returns:\n * -\n */\nvoid\napply_corr_pet(interpolator *ipclambda, ap_pixel *PET)\n{\n int j = 0;\n\n double cvalue=0.0;\n\n // go along the PET pixels until you meet\n // the last\n while (PET[j].p_x != -1)\n {\n // get the correction factor\n cvalue = eval_interp(ipclambda, PET[j].lambda);\n\n // apply the corection factor\n // to the counts and the error\n PET[j].count = PET[j].count / cvalue;\n PET[j].error = PET[j].error / cvalue;\n\n // fprintf(stdout, \"lambda: %f, correction: %f\\n\", PET[j].lambda, cvalue);\n j++;\n }\n\n}\n\n/**\n * Function: intpix_corr_pet\n * The function applies the intra-pixel sensitivity correction to\n * a list of PET pixels. The values in the pixels are corrected in\n * place using the correction function, gemoetrical parameters and\n * dispersion relation in the various parameters.\n *\n * Parameters:\n * @param actbeam - the beam to correct\n * @param conf_file_path - full path to the axe configuration file\n * @param ipcorr - the ipc correction function\n * @param PET - the list of PET pixels to correct\n *\n * Returns:\n * -\n */\nvoid\nintpix_corr_pet(beam actbeam, char conf_file_path[],\n\t\tinterpolator *ipcorr, ap_pixel *PET)\n{\n interpolator *ipclambda;\n aperture_conf *conf;\n\n int for_grism=0;\n\n // load the configuration file\n conf = get_aperture_descriptor(conf_file_path);\n\n // check whether it is grism (for_grism=1)\n // or prism (for_grism=0) data\n // give an error if there is a prism solution\n for_grism = check_for_grism (conf_file_path, actbeam.ID);\n if (!for_grism)\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"intpix_corr_beam: Only grism dispersion solution can be corrected.\\n\");\n\n // determine the correction factor versus wavelength\n ipclambda = get_ipclambda(actbeam, conf_file_path, ipcorr);\n\n print_interp(ipclambda);\n\n // apply the correction to the PET\n apply_corr_pet(ipclambda, PET);\n\n // free the configuration structure\n free_aperture_conf(conf);\n\n // free the memory in the interpolator\n free_interp(ipclambda);\n}\n\n\n/**\n * Function: is_pointlike\n * The function evaluates all criteria to decide whether an object\n * is pointlike or not. In the current implementation an object\n * is considered pointlike if a special OAF is given and the\n * the beam is NOT excluded OR if the spatial extension of the\n * object is smaller than the maximal extension.\n *\n * Parameters:\n * @param actbeam - the beam to examine\n * @param spec_OAF - indicates a special OAF file\n * @param max_ext - the maximal allowed extension\n *\n * Returns:\n * @return point_like - pointer to the opened fits file\n */\nint\nis_pointlike(beam actbeam, int spec_OAF, double max_ext)\n{\n int point_like=0;\n\n int OAF_crit=0;\n int EXT_crit=0;\n\n // check whether a special OAF is given\n // and the beam should NOT be ignored\n if (spec_OAF && !actbeam.ignore)\n OAF_crit=1;\n\n // check whether the maximal extension\n // is given and the object extension\n // is smaller;\n // also check whether non-default values\n // for the object width are set\n if (actbeam.awidth > -1.0 && actbeam.bwidth > -1.0 && max_ext && actbeam.awidth < max_ext && actbeam.bwidth < max_ext)\n EXT_crit=1;\n\n // set to pointlike if at least\n // one of the criteria is set\n if (OAF_crit || EXT_crit)\n point_like=1;\n\n // return the result\n return point_like;\n}\n\n\n/**\n * Function: get_SPC_opened\n * The function opens an existing SPC file and returns the pointer\n * to it.\n * As of now, the mode of opening it is automatically READWRITE.\n * Later on a differentiation using the free parameter \"mode\"\n * might be added to generalize the function.\n *\n * Parameters:\n * @param SPCname - name of the SPC file\n * @param mode - mode to open it (not yet used)\n *\n * Returns:\n * @return SPC_ptr - pointer to the opened fits file\n *\n */\nfitsfile *\nget_SPC_opened(char SPCname[], int mode)\n{\n fitsfile *SPC_ptr;\n int f_status=0;\n\n // Open the OPET file for reading/writing\n fits_open_file (&SPC_ptr, SPCname, READWRITE, &f_status);\n if (f_status)\n {\n ffrprt (stdout, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"aXe_INTPIXCORR: Could not open file: %s\\n\",\n\t\t SPCname);\n }\n\n // return the pointer to the fits file\n return SPC_ptr;\n}\n\n\n/**\n * Function: get_ALL_from_next_in_SPC\n * The function creates and fills a full spectrum structure with\n * the content of a SPC table extension. This is only done when,\n * according to the beam ID, this beam should be corrected.\n * For extensions with higher order beams which are not corrected\n * an emply structure is returned.\n *\n * Parameters:\n * @param SPCn_ptr - pointer to the opened SPC file\n * @param aperID - pointer to aperture identification number\n * @param beamID - pointer to beam identification number\n *\n * Returns:\n * @return SPC - the full spectrum structure\n */\nfull_spectr *\nget_ALL_from_next_in_SPC(fitsfile *SPC_ptr, int *aperID, int *beamID)\n{\n int f_status=0, hdutype;\n\n long tmp;\n //long nrows=0;\n char comment[FLEN_COMMENT];\n\n full_spectr *SPC;\n\n\n fits_movrel_hdu (SPC_ptr, 1, &hdutype, &f_status);\n\n if (f_status)\n {\n *aperID = -1;\n *beamID = -1;\n SPC = NULL;\n return SPC;\n }\n\n\n // read the beam ID number\n fits_read_key_lng (SPC_ptr, \"BEAMID\", &tmp, comment, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"get_ALL_from_next_in_SPC: Error getting index keyword OBJECTID\");\n }\n *beamID = (int)tmp;\n\n // check whether this beam should be correct\n if (*beamID > CORRMAX)\n {\n // set it to NULL and return\n SPC = NULL;\n // fprintf (stdout, \"aXe_PETFF: Skipping beam: %c.\\n\", BEAM(*beamID));\n return SPC;\n }\n\n // the beam shall be corrected and\n // first must be read in\n SPC = (full_spectr *) malloc (sizeof (full_spectr ));\n\n // transfer the beam ID\n SPC->beamID = (int)tmp;\n\n // read the aperture number\n fits_read_key_lng (SPC_ptr, \"OBJECTID\", &tmp, comment, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"get_ALL_from_next_in_SPC: Error getting index keyword OBJECTID\");\n }\n // transfer the aperture ID\n *aperID = (int)tmp;\n SPC->aperID = (int)tmp;\n\n\n // Get the number of rows\n fits_get_num_rows (SPC_ptr, &tmp, &f_status);\n if (f_status) {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"get_ALL_from_next_in_SPC: \"\n\t\t \"Could not determine the number of rows in\"\n\t\t \" correction function table!\");\n }\n SPC->nelems = (int)tmp;\n\n // load the background subtracted object spectrum\n SPC->obj_spec = get_spectrum_from_SPC(SPC_ptr, \"COUNT\", \"ERROR\", SPC->nelems);\n\n // load the total object spectrum\n SPC->fgr_spec = get_spectrum_from_SPC(SPC_ptr, \"TCOUNT\", \"TERROR\", SPC->nelems);\n\n // load the background spectrum\n SPC->bck_spec = get_spectrum_from_SPC(SPC_ptr, \"BCOUNT\", \"BERROR\", SPC->nelems);\n\n // return the filled structure\n return SPC;\n}\n\n\n/**\n * Function: free_full_spectr\n * The function frees the memory allocated in a full\n * spectrum structure.\n *\n * Parameters:\n * @param SPC - the full spectrum structure\n *\n * Returns:\n * @return -\n */\nvoid\nfree_full_spectr(full_spectr *SPC)\n{\n // free the three spectra in the\n // full spectrum structure\n free_spectrum(SPC->obj_spec);\n free_spectrum(SPC->fgr_spec);\n free_spectrum(SPC->bck_spec);\n\n // free the full spectrum\n free(SPC);\n\n // set the structure to NULL\n SPC = NULL;\n}\n\n\n/**\n * Function: get_spectrum_from_SPC\n * The function fills a spectrum structure with data in an SPC extension.\n * There is more data in an SPC extension than can be stored in a\n * spectrum structure. Two parameters in this function specify partly which\n * data should be loaded.\n *\n * Parameters:\n * @param SPC_ptr - pointer to the SPC extension\n * @param count_col - column to load for 'count'\n * @param error_col - column to load for 'error'\n * @param nelems - the number ol elements in the spectrum\n *\n * Returns:\n * @return act_spec - the filled spectrum structure\n */\nspectrum *\nget_spectrum_from_SPC(fitsfile *SPC_ptr, char count_col[],\n\t\t char error_col[], int nelems)\n{\n int index=0;\n\n spectrum *act_spec;\n\n double *count;\n double *lambda;\n double *error;\n double *flux;\n double *ferror;\n double *weight;\n double *contam;\n long *dq;\n\n // allocate the spectrum\n act_spec = allocate_spectrum (nelems);\n\n // transfer the column entries into a vector\n lambda = get_dcolumn_from_SPC_opened(SPC_ptr, \"LAMBDA\", nelems);\n count = get_dcolumn_from_SPC_opened(SPC_ptr, count_col, nelems);\n error = get_dcolumn_from_SPC_opened(SPC_ptr, error_col, nelems);\n flux = get_dcolumn_from_SPC_opened(SPC_ptr, \"FLUX\", nelems);\n ferror = get_dcolumn_from_SPC_opened(SPC_ptr, \"FERROR\", nelems);\n weight = get_dcolumn_from_SPC_opened(SPC_ptr, \"WEIGHT\", nelems);\n contam = get_dcolumn_from_SPC_opened(SPC_ptr, \"CONTAM\", nelems);\n dq = get_lcolumn_from_SPC_opened(SPC_ptr, \"DQ\", nelems);\n\n // transfer the data from the vector into the\n // spectrum structure\n for (index = 0; index < nelems; index++)\n {\n act_spec->spec[index].lambda_mean = lambda[index];\n act_spec->spec[index].count = count[index];\n act_spec->spec[index].error = error[index];\n act_spec->spec[index].flux = flux[index];\n act_spec->spec[index].ferror = ferror[index];\n act_spec->spec[index].weight = weight[index];\n act_spec->spec[index].contam = contam[index];\n act_spec->spec[index].dq = dq[index];\n }\n\n // free the arrays\n free(lambda);\n free(count);\n free(error);\n free(flux);\n free(ferror);\n free(weight);\n free(contam);\n free(dq);\n\n // return the spectrum\n return act_spec;\n}\n\n\n/**\n * Function: get_dcolumn_from_SPC_opened\n * The function reads the values from a double column specified\n * by its name into a array of doubles. The array is returned.\n *\n * Parameters:\n * @param SPC_ptr - pointer to the SPC extension\n * @param count_col - name of the column to load\n * @param nelems - number of elements in the column\n *\n * Returns:\n * @return values - pointer to a filled array\n */\ndouble *\nget_dcolumn_from_SPC_opened(fitsfile *SPC_ptr, char colname[], int nelems)\n{\n int colnum=0;\n int anynul;\n int f_status=0;\n double *values;\n\n // allocate the return array;\n // give an error if allocation fails\n values = (double *) malloc(nelems * sizeof(double));\n if (!values) {\n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t \"Memory allocation failed\");\n }\n\n // get the desired column number;\n // give an error if the column name\n // can not be read\n fits_get_colnum (SPC_ptr, CASEINSEN, colname, &colnum, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"get_dcolumn_from_SPC_opened: \"\n\t\t \"Could not determine column %s in \"\n\t\t \" table!\\n\", colname);\n }\n\n // read all data in the column\n fits_read_col (SPC_ptr, TDOUBLE, colnum, 1, 1, nelems, NULL, values,\n &anynul, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"get_dcolumn_from_SPC_opened: \"\n\t\t \"Could not read column %s\"\n\t\t \" from BINARY table!\",colname);\n }\n\n // return the filled vector\n return values;\n}\n\n\n/**\n * Function: get_lcolumn_from_SPC_opened\n * The function reads the values from a column with long specified\n * by its name into a array of type long. The array is returned.\n *\n * Parameters:\n * @param SPC_ptr - pointer to the SPC extension\n * @param count_col - name of the column to load\n * @param nelems - number of elements in the column\n *\n * Returns:\n * @return values - pointer to a filled array\n */\nlong *\nget_lcolumn_from_SPC_opened(fitsfile *SPC_ptr, char colname[], int nelems)\n{\n int colnum=0;\n int anynul;\n int f_status=0;\n long *values;\n\n // allocate the return array;\n // give an error if allocation fails\n values = (long *) malloc(nelems * sizeof(long));\n if (!values) {\n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t \"Memory allocation failed\");\n }\n\n // get the desired column number;\n // give an error if the column name\n // can not be read\n fits_get_colnum (SPC_ptr, CASEINSEN, colname, &colnum, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"get_dcolumn_from_SPC_opened: \"\n\t\t \"Could not determine column %s in \"\n\t\t \" table!\\n\", colname);\n }\n\n // read all data in the column\n fits_read_col (SPC_ptr, TLONG, colnum, 1, 1, nelems, NULL, values,\n &anynul, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"get_dcolumn_from_SPC_opened: \"\n\t\t \"Could not read column %s\"\n\t\t \" from BINARY table!\",colname);\n }\n\n // return the filled array\n return values;\n}\n\n\n/**\n * Function: create_nlincor\n * The function creates an interpolator for the nonlinearity\n * correction applied to NICMOS data.\n *\n * Parameters:\n *\n * Returns:\n * @return nlincorr - the interpolator created\n */\ninterpolator *\ncreate_nlincor()\n{\n interpolator *nlincorr;\n /*\n double x[14] = {8250.0, 8750.0, 9250.0, 9750.0, 11000.0, 12000.0, 13000.0, 14000.0, 15000.0, 16000.0, 17000.0, 18000.0, 19000.0, 20000.0};\n double y[14] = { .069, .057, .052, .050, .049, .048, .041, .023, .013, .008, .004, .0, .0, .0};\n */\n double *xx;\n double *yy;\n\n xx = (double *) malloc(14 * sizeof(double));\n yy = (double *) malloc(14 * sizeof(double));\n\n xx[0] = 8250.0;\n xx[1] = 8750.0;\n xx[2] = 9250.0;\n xx[3] = 9750.0;\n xx[4] = 11000.0;\n xx[5] = 12000.0;\n xx[6] = 13000.0;\n xx[7] = 14000.0;\n xx[8] = 15000.0;\n xx[9] = 16000.0;\n xx[10] = 17000.0;\n xx[11] = 18000.0;\n xx[12] = 19000.0;\n xx[13] = 20000.0;\n\n yy[0] = .069;\n yy[1] = .057;\n yy[2] = .052;\n yy[3] = .050;\n yy[4] = .049;\n yy[5] = .048;\n yy[6] = .041;\n yy[7] = .023;\n yy[8] = .013;\n yy[9] = .008;\n yy[10] = .004;\n yy[11] = .0;\n yy[12] = .0;\n yy[13] = .0;\n\n // create the interpolator\n nlincorr = create_interp(14, NLINCORR_INTERP_TYPE, xx, yy);\n\n // return the interpolator\n return nlincorr;\n}\n\n/**\n * Function: nlin_corr_beam\n *\n * Parameters:\n * @param nlincorr - the interpolator with the correction factor\n * @param SPC - the full spectrum to correct\n *\n * Returns:\n * @return -\n */\nvoid\nnlin_corr_beam(interpolator *nlincorr, double adcgain, full_spectr *SPC)\n{\n int index=0;\n // int for_grism=1;\n\n double cfactor;\n double cps;\n\n double lambda;\n\n for (index=0; index < SPC->nelems; index++)\n {\n // get the independent spectral values,\n // the wavelenth and the cps value\n lambda = SPC->obj_spec->spec[index].lambda_mean;\n cps = SPC->obj_spec->spec[index].count;\n\n\n // check whether the spectral element\n // is not corrupt\n if (!gsl_isnan (lambda) && lambda)\n\t{\n\t if (cps > 0.0)\n\t // compute the correction factor\n\t cfactor = get_nlin_corr(nlincorr, lambda, cps/adcgain);\n\t else\n\t // make a dummy factor\n\t cfactor = 1.0;\n\t // correct what should be corrected\n\t SPC->fgr_spec->spec[index].count = SPC->fgr_spec->spec[index].count / cfactor;\n\t SPC->fgr_spec->spec[index].error = SPC->fgr_spec->spec[index].error / cfactor;\n\t SPC->fgr_spec->spec[index].flux = SPC->fgr_spec->spec[index].flux / cfactor;\n\t SPC->fgr_spec->spec[index].ferror = SPC->fgr_spec->spec[index].ferror / cfactor;\n\n\t SPC->bck_spec->spec[index].count = SPC->bck_spec->spec[index].count / cfactor;\n\t SPC->bck_spec->spec[index].error = SPC->bck_spec->spec[index].error / cfactor;\n\t SPC->bck_spec->spec[index].flux = SPC->bck_spec->spec[index].flux / cfactor;\n\t SPC->bck_spec->spec[index].ferror = SPC->bck_spec->spec[index].ferror / cfactor;\n\n\t SPC->obj_spec->spec[index].count = SPC->obj_spec->spec[index].count / cfactor;\n\t SPC->obj_spec->spec[index].error = SPC->obj_spec->spec[index].error / cfactor;\n\t SPC->obj_spec->spec[index].flux = SPC->obj_spec->spec[index].flux / cfactor;\n\t SPC->obj_spec->spec[index].ferror = SPC->obj_spec->spec[index].ferror / cfactor;\n\t}\n }\n\n}\n\n/*\n * Function: get_nlin_corr\n *\n * Parameters:\n * @param nlincorr - the interpolator with the parameter\n * @param lamda - the full spectrum to correct\n * @param cps - the count rate\n *\n * Returns:\n * @return cfactor - the correction factor\n */\ndouble\nget_nlin_corr(interpolator *nlincorr, const double lambda, const double cps)\n{\n double cfactor;\n double bbb;\n\n // evaluate the parameter\n bbb = eval_interp(nlincorr, lambda);\n\n // compute the correction factor\n cfactor = 1.0 - 2.0 * bbb + bbb * log10(cps);\n\n // return the correction factor\n return cfactor;\n}\n", "meta": {"hexsha": "d6445280e6b6d347db19d066df931d60a38251a8", "size": 40574, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/ipixcorr_utils.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/ipixcorr_utils.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/ipixcorr_utils.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0983379501, "max_line_length": 152, "alphanum_fraction": 0.6769606152, "num_tokens": 11597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.42017460345092894}} {"text": "/* Modified from SUPOLAR, Copyright (c) Colorado School of Mines, 2011.*/\n/* All rights reserved. */\n\n/* SUPOLAR_PS: $Revision: 1.9 $ ; $Date: Sat, 23 Jul 2016 00:10:26 -0700 */\n\n#include \n#include \n#include \n#include \"su.h\"\n#include \"segy.h\"\n#include \"header.h\"\n\n\n/*********************** self documentation *****************************/\nchar *sdoc[] = {\n\" \",\n\" SUPOLAR_PS - POLarization analysis of three-component data \",\n\" - to provide P and S arrivals \",\n\" - Modification of SUPOLAR \",\n\" \",\n\" supolar_PS nt) err(\"wl=%g too long for trace\", wl);\n if (!strlen(file)) err(\"file= not set and default overridden\");\n\n /* echo some information */\n if (verbose && (theta || phi)) warn(\"computing angles in %s\", angle);\n if (verbose) warn(\"%s window length = %d samples\\n\", win, iwl);\n \n if (rl && theta) warn(\"computing filtered phase\");\n\n /* open temporary file for trace headers */\n headerfp = etmpfile();\n \n /* set filenames and open files */\n fname = malloc( strlen(file)+7 );\n sprintf(fname, \"%s.rl\", file); if (rl) rlfp = efopen(fname, \"w\");\n sprintf(fname, \"%s.theta\", file); if (theta) thetafp = efopen(fname, \"w\");\n sprintf(fname, \"%s.phi\", file); if (phi) phifp = efopen(fname, \"w\");\n sprintf(fname, \"%s.tau\", file); if (tau) taufp = efopen(fname, \"w\");\n sprintf(fname, \"%s.e21\", file); if (ellip) e21fp = efopen(fname, \"w\");\n sprintf(fname, \"%s.e31\", file); if (ellip) e31fp = efopen(fname, \"w\");\n sprintf(fname, \"%s.e32\", file); if (ellip) e32fp = efopen(fname, \"w\");\n sprintf(fname, \"%s.pln\", file); if (pln) plnfp = efopen(fname, \"w\");\n sprintf(fname, \"%s.f1\", file); if (f1) f1fp = efopen(fname, \"w\");\n sprintf(fname, \"%s.l1\", file); if (l1) l1fp = efopen(fname, \"w\");\n sprintf(fname, \"%s.dir\", file); if (dir) dirfp = efopen(fname, \"w\");\n sprintf(fname, \"%s.er\", file); if (amp) erfp = efopen(fname, \"w\");\n sprintf(fname, \"%s.ir\", file); if (amp) irfp = efopen(fname, \"w\");\n sprintf(fname, \"%s.qr\", file); if (amp) qrfp = efopen(fname, \"w\");\n sprintf(fname, \"%s.pfilt\", file); if (rl && theta) pfiltfp = efopen(fname, \"w\");\n sprintf(fname, \"%s.sfilt\", file); if (rl && theta) sfiltfp = efopen(fname, \"w\");\n sprintf(fname, \"%s.nfilt\", file); if (rl && theta) nfiltfp = efopen(fname, \"w\");\n sprintf(fname, \"%s.efilt\", file); if (rl && theta) efiltfp = efopen(fname, \"w\");\n // sprintf(fname, \"%s.pkur\", file); if (rl && theta) pkur = efopen(fname, \"w\");\n // sprintf(fname, \"%s.skur\", file); if (rl && theta) skur = efopen(fname, \"w\");\n free(fname);\n \n /* allocate space for input data and analysis matrices */\n /* index ranges used here: data3c[1..3][0..nt-1], */\n /* a[1..3][1..3], v[1..3][1..3], d[1..3] */\n data3c = ealloc2float(nt,3); data3c-=1;\n a = ealloc2float(3,3); a[0]-=1; a-=1;\n v = ealloc2float(3,3); v[0]-=1; v-=1; \n d = ealloc1float(3); d-=1;\n\n /* calculate time window weights */\n w = ealloc1float(iwl);\n memset((void *) w, 0, iwl*FSIZE);\n calc_window(w, iwl, iwin);\n\n /* allocate and zero out space for output data */\n if (rl) { \n data_rl = ealloc1float(nt); \n memset((void *) data_rl, 0, nt*FSIZE);\n }\n if (theta) {\n data_theta = ealloc1float(nt);\n memset((void *) data_theta, 0, nt*FSIZE);\n }\n if (phi) {\n data_phi = ealloc1float(nt);\n memset((void *) data_phi, 0, nt*FSIZE);\n } \n if (tau) {\n data_tau = ealloc1float(nt);\n memset((void *) data_tau, 0, nt*FSIZE);\n }\n if (ellip) {\n data_e21 = ealloc1float(nt);\n data_e31 = ealloc1float(nt);\n data_e32 = ealloc1float(nt);\n memset((void *) data_e21, 0, nt*FSIZE);\n memset((void *) data_e31, 0, nt*FSIZE);\n memset((void *) data_e32, 0, nt*FSIZE);\n }\n if (pln) {\n data_pln = ealloc1float(nt);\n memset((void *) data_pln, 0, nt*FSIZE);\n }\n if (f1) {\n data_f1 = ealloc1float(nt);\n memset((void *) data_f1, 0, nt*FSIZE);\n }\n if (l1) {\n data_l1 = ealloc1float(nt);\n memset((void *) data_l1, 0, nt*FSIZE);\n }\n if (amp) {\n data_er = ealloc1float(nt);\n data_ir = ealloc1float(nt);\n data_qr = ealloc1float(nt);\n memset((void *) data_er, 0, nt*FSIZE);\n memset((void *) data_ir, 0, nt*FSIZE);\n memset((void *) data_qr, 0, nt*FSIZE);\n }\n if (dir) {\n data3c_dir = ealloc2float(nt,3); data3c_dir-=1;\n for (i=1;i<=3;i++) memset((void *) data3c_dir[i], 0, nt*FSIZE);\n }\n if (rl && theta) {\n data_pfilt = ealloc1float(nt);\n memset((void *) data_pfilt, 0, nt*FSIZE);\n data_sfilt = ealloc1float(nt);\n memset((void *) data_pfilt, 0, nt*FSIZE);\n/* data_3Cfilt = ealloc2float(nt,3);\n for (i=1;i<=3;i++) memset((void *) data_3Cfilt[i], 0, nt*FSIZE); */\n data_zfilt = ealloc1float(nt);\n data_nfilt = ealloc1float(nt);\n data_efilt = ealloc1float(nt);\n memset((void *) data_zfilt, 0, nt*FSIZE);\n memset((void *) data_nfilt, 0, nt*FSIZE);\n memset((void *) data_efilt, 0, nt*FSIZE);\n\n // data_pkur = ealloc1float(nt);\n// data_skur = ealloc1float(nt);\n// memset((void *) data_pkur, 0, nt*FSIZE);\n// memset((void *) data_skur, 0, nt*FSIZE);\n /* Allocate data for kurtosis window arrays */\n// data_kwl = ealloc1float(iwl);\n// memset((void *) data_kwl, 0, kwl*FSIZE); \n } \n\n\n/* ************************ BEGIN CALCULATION ******************************* */ \n\n /* loop over traces */\n icomp=0;\n nstat=0;\n // Need to convert this do while loop into a for loop so as to be easier\n // to parallelize\n warn(\"Trace Start Time: %d %d %d %d %d\", tr.year, tr.day, tr.hour, tr.minute, tr.sec); \n do {\n /* store trace header in temporary file and read data */\n efwrite(&tr, HDRBYTES, 1, headerfp);\n icomp++;\n memcpy((void *)data3c[icomp], (const void *) tr.data, nt*FSIZE);\n \n /* process 3-component dataset */\n if (icomp==3) {\n erewind(headerfp);\n icomp = 0;\n nstat++;\n if (verbose) \n fprintf(stderr,\"%s: analyzing station %d \\r\",argv[0], nstat);\n\n /* start loop over samples */\n\n for (it=iwl/2;it0.0) ? 0.5*PI : -0.5*PI;\n }\n break;\n case 2:\n case 3:\n /* definitions after Jurkevics, 1988 */\n /* interval -pi <= phi <= pi */\n if (v[2][1]) {\n phi = atan2( v[3][1]*VSIGN, v[2][1]*VSIGN);\n }\n else {\n phi = (v[3][1]>0.0) ? 0.5*PI*VSIGN : -0.5*PI*VSIGN;\n }\n \n /* interval 0.0 <= phi <= 2*pi */\n if (phi<0.0 && opt==3) phi += 2.0*PI;\n break;\n } \n return phi;\n}\n#undef VSIGN\n\n/* global polarization parameter tau (Samson, 1973) */\n\nfloat calc_tau(float *d)\n{\n float x1, x2, x3, x4, tau;\n \n if (d[1]) { \n x1 = pow(( 1 - fabs(d[2]/d[1])), 2.);\n x2 = pow(( 1 - fabs(d[3]/d[1])), 2.);\n x3 = pow(( fabs(d[2]/d[1]) - fabs(d[3]/d[1]) ), 2.);\n x4 = pow(( 1 + fabs(d[2]/d[1]) + fabs(d[3]/d[1])), 2.);\n tau = sqrt( (x1+x2+x3) / (2*x4) );\n return tau;\n }\n else\n return 0.0;\n}\n\n/* ellipticities e_ik */\n\nfloat calc_ellip(float *d, int d1, int d2)\n{\n float ellip;\n \n if (d[d2]) {\n ellip = sqrt( fabs(d[d1]/d[d2]) );\n return ellip;\n }\n else\n return 0.0;\n}\n\n/* planarity after Jurkevics, 1988 */\n\nfloat calc_plan(float *d)\n{\n float pln;\n \n if (d[1]+d[2]) {\n pln = 1.0 - 2.0*d[3] / (d[1] + d[2]);\n return pln;\n }\n else\n return 0.0;\n}\n\n/* flatness coefficient f1 after Benhama et. al, 1988 */\n\nfloat calc_f1(float *d)\n{\n float f1,x1,x2;\n \n x1 = 3.0 * calc_ellip(d,3,1);\n x2 = 1.0 + calc_ellip(d,2,1) + calc_ellip(d,3,1);\n f1 = 1.0 - x1 / x2; \n return f1;\n}\n\n/* linearity coefficient l1 */\n\nfloat calc_l1(float *d)\n{\n float l1,x1,x2;\n \n x1 = 3. * ( calc_ellip(d,2,1) + calc_ellip(d,3,1) );\n x2 = 2. * ( 1 + calc_ellip(d,2,1) + calc_ellip(d,3,1));\n l1 = 1. - x1 / x2;\n return l1;\n}\n\n/* direction cosines or directivity functions (3 components) */\n\nvoid calc_dir(float **data3c_dir, float **v, int it)\n{\n int i;\n for (i=1;i<=3;i++) {\n data3c_dir[i][it]=v[i][1];\n }\n}\n\n/* amplitude parameters */\n\n/* eigenresultant */\n\nfloat calc_er(float *d)\n{\n float er;\n er = sqrt(fabs(d[1]));\n return er;\n}\n\n/* instantaneous and quadratic resultant (Meyer, 1988) */\n\nvoid ampparams(float **indata, float *data_ir, float *data_qr, int nt, int iwl)\n{\n int i,it;\n float sqrsum;\n \n for (it=0;it= iwl/2) && (it < nt-iwl/2) ) {\n sqrsum=0.0;\n for (i=it-iwl/2;i<(it+iwl);i++) {\n sqrsum += indata[1][i]*indata[1][i]+ \\\n indata[2][i]*indata[2][i]+indata[3][i]*indata[3][i];\n }\n data_qr[it] = sqrsum / (float) iwl;\n }\n }\n}\n\n/* P, S detection parameters */\n\n/* P-Wave energy filter */\nfloat calc_pfilt(float rl, float theta)\n{\n float pfilt;\n pfilt = rl*cos(theta);\n return pfilt;\n}\n\n/* S-Wave energy filter */\nfloat calc_sfilt(float rl, float theta)\n{\n float sfilt;\n sfilt = rl * (1 - cos(theta));\n return sfilt;\n} \n\n\n/**********************************************************************/\n/* Functions for data output */\n/**********************************************************************/\n\n\n/* write one-component data into file */\n\nvoid fputdata(FILE *fileptr, FILE *headerptr, float *outdata, int nt)\n{ \n efread(&tr, 1, HDRBYTES, headerptr);\n erewind(headerptr);\n \n memcpy((void *)tr.data, (const void *) outdata, nt*FSIZE);\n\n fputtr(fileptr, &tr);\n}\n\n/* write three-component data into file */\n\nvoid fputdata3c(FILE *fileptr, FILE *headerptr, float **outdata3c, int nt)\n{\n int i;\n \n for(i=1;i<=3;i++) {\n efread(&tr, 1, HDRBYTES, headerptr);\n \n memcpy((void *)tr.data, (const void *) outdata3c[i], nt*FSIZE);\n\n fputtr(fileptr, &tr);\n }\n erewind(headerptr);\n}\n\n/* END OF FILE */\n", "meta": {"hexsha": "3865f4f95a338fd2a51c087318adc3e9e9a667bb", "size": 33447, "ext": "c", "lang": "C", "max_stars_repo_path": "supolar_PS.c", "max_stars_repo_name": "captainobvious62/3CPolar", "max_stars_repo_head_hexsha": "25499b24352fe2ee8b1cba3d44f078723093055c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "supolar_PS.c", "max_issues_repo_name": "captainobvious62/3CPolar", "max_issues_repo_head_hexsha": "25499b24352fe2ee8b1cba3d44f078723093055c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "supolar_PS.c", "max_forks_repo_name": "captainobvious62/3CPolar", "max_forks_repo_head_hexsha": "25499b24352fe2ee8b1cba3d44f078723093055c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3709497207, "max_line_length": 106, "alphanum_fraction": 0.4851556193, "num_tokens": 9528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.4199371152134737}} {"text": "#include \n#include \n#include \n#include \"loss.h\"\n\nvoid expit(const double *x, double *out, int x_len) {\n for (int i = 0; i < x_len; i++) {\n if (x[i] > 0) {\n out[i] = 1. / (1. + exp(-x[i]));\n } else {\n out[i] = 1. - 1. / (1. + exp(x[i]));\n }\n }\n}\n\n\nvoid log_logistic(const double *x, double *out, int x_len) {\n for (int i = 0; i < x_len; i++) {\n if (x[i] > 0.0) {\n out[i] = -log(1.0 + exp(-x[i]));\n } else {\n out[i] = x[i] - log(1.0 + exp(x[i]));\n }\n }\n}\n\nvoid logistic(const double *x, double *out, int x_len) {\n for (int i = 0; i < x_len; i++) {\n if (x[i] > 0) {\n out[i] = 1. / (1. + exp(-x[i]));\n } else {\n out[i] = 1. - 1. / (1. + exp(x[i]));\n }\n }\n}\n\ndouble log_sum_exp(const double *x, int x_len) {\n double max_x = x[0], out = 0.0;\n for (int i = 1; i < x_len; i++) {\n if (x[i] > max_x) {\n max_x = x[i];\n }\n }\n for (int i = 0; i < x_len; i++) {\n out += exp(x[i] - max_x);\n }\n return max_x + log(out);\n}\n\nvoid logistic_loss_grad(const double *w,\n const double *x_tr,\n const double *y_tr,\n double *loss_grad,\n double eta,\n int n_samples,\n int n_features) {\n for (int i = 0; i < n_features + 1; i++) {\n if (isnan(w[i])) {\n printf(\"%f\\n\", w[i]);\n printf(\"warning: loss grad error!\\n\");\n break;\n }\n }\n int i, n = n_samples, p = n_features;\n double intercept = w[p], sum_z0 = 0.0;\n loss_grad[0] = 0.0;\n double *yz = malloc(sizeof(double) * n);\n double *z0 = malloc(sizeof(double) * n);\n double *logistic = malloc(sizeof(double) * n);\n for (i = 0; i < n; i++) { /** calculate yz */\n yz[i] = intercept;\n }\n //x_tr^T*w+\n cblas_dgemv(CblasRowMajor, CblasNoTrans, n, p, 1., x_tr, p, w, 1, 1., yz, 1);\n for (i = 0; i < n; i++) {\n yz[i] *= y_tr[i];\n }\n expit(yz, z0, n); // calculate z0 and final intercept\n /** calculate logistic logistic[i] = 1/(1+exp(-y[i]*(xi^T*w+c)))*/\n log_logistic(yz, logistic, n);\n /** calculate loss of data fitting part*/\n for (i = 0; i < n; i++) {\n z0[i] = (z0[i] - 1.) * y_tr[i];\n sum_z0 += z0[i];\n loss_grad[0] -= logistic[i];\n }\n /**calculate loss of regularization part (it does not have intercept)*/\n loss_grad[0] += 0.5 * eta * cblas_ddot(p, w, 1, w, 1);\n /** calculate gradient of coefficients*/\n memcpy(loss_grad + 1, w, sizeof(double) * p);\n /** x^T*z0 + eta*w, where z0[i]=(logistic[i] - 1.)*yi*/\n cblas_dgemv(CblasRowMajor, CblasTrans,\n n, p, 1., x_tr, p, z0, 1, eta, loss_grad + 1, 1);\n /** calculate gradient of intercept part*/\n loss_grad[p + 1] = sum_z0; // intercept part\n free(logistic);\n free(z0);\n free(yz);\n}\n\nvoid logistic_loss_grad_sparse(const double *w,\n const double *x_tr,\n const double *y_tr,\n double *loss_grad,\n double eta,\n int n_samples,\n int n_features) {\n //sub_p is number of nonzeros in w.\n int i, n = n_samples, p = n_features, sub_p = 0;\n double intercept = w[p], sum_z0 = 0.0;\n loss_grad[0] = 0.0;\n double *yz = malloc(sizeof(double) * n);\n double *z0 = malloc(sizeof(double) * n);\n double *logistic = malloc(sizeof(double) * n);\n for (i = 0; i < n; i++) { /** calculate yz */\n yz[i] = intercept;\n }\n double nonzero_w[p];\n int nonzero_w_ind[p];\n for (i = 0; i < p; i++) {\n if (w[i] != 0.0) {\n nonzero_w_ind[sub_p] = i;\n nonzero_w[sub_p] = w[i];\n sub_p++;\n }\n }\n //x_tr^T*w+ to use the sparsity of w\n for (i = 0; i < n; i++) {\n double tmp_val = 0.0;\n for (int j = 0; j < sub_p; j++) {\n tmp_val += x_tr[i * p + nonzero_w_ind[j]] * nonzero_w[j];\n }\n yz[i] = yz[i] + tmp_val;\n }\n for (i = 0; i < n; i++) {\n yz[i] *= y_tr[i];\n }\n expit(yz, z0, n); // calculate z0 and final intercept\n /** calculate logistic logistic[i] = 1/(1+exp(-y[i]*(xi^T*w+c)))*/\n log_logistic(yz, logistic, n);\n /** calculate loss of data fitting part*/\n for (i = 0; i < n; i++) {\n z0[i] = (z0[i] - 1.) * y_tr[i];\n sum_z0 += z0[i];\n loss_grad[0] -= logistic[i];\n }\n /**calculate loss of regularization part (it does not have intercept)*/\n loss_grad[0] += 0.5 * eta * cblas_ddot(p, w, 1, w, 1);\n /** calculate gradient of coefficients*/\n memcpy(loss_grad + 1, w, sizeof(double) * p);\n /** x^T*z0 + eta*w, where z0[i]=(logistic[i] - 1.)*yi*/\n cblas_dgemv(CblasRowMajor, CblasTrans,\n n, p, 1., x_tr, p, z0, 1, eta, loss_grad + 1, 1);\n /** calculate gradient of intercept part*/\n loss_grad[p + 1] = sum_z0; // intercept part\n free(logistic);\n free(z0);\n free(yz);\n}\n\n\nvoid logistic_predict(const double *x_te,\n const double *wt,\n double *pred_prob,\n double *pred_label,\n double threshold,\n int n,\n int p) {\n openblas_set_num_threads(1);\n int i;\n cblas_dgemv(CblasRowMajor, CblasNoTrans,\n n, p, 1., x_te, p, wt, 1, 0., pred_prob, 1);\n for (i = 0; i < n; i++) {\n pred_prob[i] += wt[p]; // intercept\n }\n expit(pred_prob, pred_prob, n);\n for (i = 0; i < n; i++) {\n if (pred_prob[i] >= threshold) {\n pred_label[i] = 1.;\n } else {\n pred_label[i] = -1.;\n }\n }\n}\n\nvoid least_square_loss_grad(const double *w,\n const double *x_tr,\n const double *y_tr,\n double *loss_grad,\n double eta,\n int n_samples,\n int n_features) {\n for (int i = 0; i < n_features + 1; i++) {\n if (isnan(w[i])) {\n printf(\"%f\\n\", w[i]);\n printf(\"warning: loss grad error!\\n\");\n break;\n }\n }\n int i, n = n_samples, p = n_features;\n double *yz = malloc(sizeof(double) * n);\n double *w0 = malloc(sizeof(double) * n);\n cblas_dcopy(n, y_tr, 1, yz, 1); // y_tr --> yz\n cblas_dscal(p + 2, 0.0, loss_grad, 1);\n cblas_daxpy(p, eta, w, 1, loss_grad + 1, 1); // l2_lambda*w --> loss_grad\n //Order,TransA, M, N, alpha, A, lda, x, incX, beta, Y, incY\n // Y<-alpha*AX + beta*Y, where A=MxN, Y=N\n cblas_dgemv(CblasRowMajor, CblasNoTrans,\n n, p, 1., x_tr, p, w, 1, -1., yz, 1); //Xw - y\n for (i = 0; i < n; i++) { w0[i] = w[p]; }\n cblas_daxpy(n, 1., w0, 1, yz, 1);\n loss_grad[0] = cblas_ddot(n, yz, 1, yz, 1) / (2. * n);\n loss_grad[0] += (.5 * eta) * cblas_ddot(p, w, 1, w, 1); //loss\n cblas_dgemv(CblasRowMajor, CblasTrans,\n n, p, 1. / n, x_tr, p, yz, 1, 1., loss_grad + 1, 1);\n for (i = 0; i < n; i++) {\n w0[i] = w[p];\n loss_grad[p + 1] = yz[i];\n }\n loss_grad[p + 1] /= n;\n free(w0), free(yz);\n}\n\nvoid least_square_predict(const double *x_te,\n const double *wt,\n double *pred_prob,\n double *pred_label,\n double threshold,\n int n_samples,\n int p_features) {\n openblas_set_num_threads(1);\n int i, n = n_samples, p = p_features;\n cblas_dgemv(CblasRowMajor, CblasNoTrans,\n n, p, 1., x_te, p, wt, 1, 0., pred_prob, 1);\n for (i = 0; i < n; i++) {\n pred_prob[i] += wt[p]; // intercept\n }\n // this is not useful.\n for (i = 0; i < n; i++) {\n if (pred_prob[i] >= threshold) {\n pred_label[i] = 1.;\n } else {\n pred_label[i] = -1.;\n }\n }\n}", "meta": {"hexsha": "301a032d5bea92309a1f380217799b0ac857abe0", "size": 8136, "ext": "c", "lang": "C", "max_stars_repo_path": "algo_wrapper/loss.c", "max_stars_repo_name": "baojianzhou/sparse-auc", "max_stars_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-13T13:45:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T13:45:14.000Z", "max_issues_repo_path": "algo_wrapper/loss.c", "max_issues_repo_name": "baojianzhou/sparse-auc", "max_issues_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algo_wrapper/loss.c", "max_forks_repo_name": "baojianzhou/sparse-auc", "max_forks_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-08T11:52:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T11:52:16.000Z", "avg_line_length": 33.0731707317, "max_line_length": 81, "alphanum_fraction": 0.4607915438, "num_tokens": 2583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4198689200097166}} {"text": "#include \n#include \n#include \n#include \"matrix_operations.c\"\n#include \"ellipse/parametric_function_roots.c\"\n#include \"polynomial.c\"\n\n\n\n\n\nvoid characteristic_ellipse_matrix(double *X, double *R, double phi, double exponent)\n{\n\n\n // rotation matrix\n double Q[2][2] = {{ 0 }};\n double Qt[2][2] = {{ 0 }};\n Q[0][0] = cos(phi);\n Q[0][1] = sin(phi);\n Q[1][0] = -sin(phi);\n Q[1][1] = cos(phi);\n matrix_transpose(&Qt[0][0], &Q[0][0], 2, 2);\n\n\n // radii matrix\n double O[2][2] = {{ 0 }};\n double diag_vals[2];\n diag_vals[0] = pow(R[0], exponent * -2.0);\n diag_vals[1] = pow(R[1], exponent * -2.0);\n set_diagonal(&O[0][0], diag_vals, 2, 2);\n\n\n // characteristic ellipse matrix\n double X_temp[2][2] = {{ 0 }};\n matrix_multiply(&X_temp[0][0], &O[0][0], &Q[0][0], 2, 2, 2);\n matrix_multiply(X, &Qt[0][0], &X_temp[0][0], 2, 2, 2);\n\n}\n\n\n\n\n\ndouble ellipse_overlap(double *rA, double *radiiA, double phiA, double *rB, double *radiiB, double phiB)\n{\n\n\n // find XA^(-1) and XB^(1/2)\n double XA[2][2] = {{ 0 }};\n double XB[2][2] = {{ 0 }};\n characteristic_ellipse_matrix(&XA[0][0], &radiiA[0], phiA, -1.0);\n characteristic_ellipse_matrix(&XB[0][0], &radiiB[0], phiB, 0.5);\n\n\n // find A_AB\n double A_AB[2][2] = {{ 0 }};\n double A_temp[2][2] = {{ 0 }};\n matrix_multiply(&A_temp[0][0], &XA[0][0], &XB[0][0], 2, 2, 2);\n matrix_multiply(&A_AB[0][0], &XB[0][0], &A_temp[0][0], 2, 2, 2);\n\n // find r_AB\n double rAB[2];\n rAB[0] = rB[0] - rA[0];\n rAB[1] = rB[1] - rA[1];\n\n // find a_AB\n double a_AB[2];\n matrix_multiply(&a_AB[0], &XB[0][0], &rAB[0], 2, 2, 1);\n\n // extract elements of the matrix A_AB and a_AB\n double a11, a12, a21, a22;\n double b1, b2;\n a11 = A_AB[0][0];\n a12 = A_AB[0][1];\n a21 = A_AB[1][0];\n a22 = A_AB[1][1];\n b1 = a_AB[0];\n b2 = a_AB[1];\n\n\n\n\n // find coefficients for the parametric polynomial derivative used to find max\n double h[5];\n double z[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };\n size_t n = 5;\n h[0] = h0(a11, a12, a21, a22, b1, b2);\n h[1] = h1(a11, a12, a21, a22, b1, b2);\n h[2] = h2(a11, a12, a21, a22, b1, b2);\n h[3] = h3(a11, a12, a21, a22, b1, b2);\n h[4] = h4(a11, a12, a21, a22, b1, b2);\n\n\n\n // find roots\n size_t m;\n m = find_roots(&z[0], &h[0], n);\n\n\n\n double F;\n int i;\n\n if (m > 1)\n {\n if (f(0, a11, a12, a21, a22, b1, b2) > f(1, a11, a12, a21, a22, b1, b2))\n {\n\n F = f(0, a11, a12, a21, a22, b1, b2);\n\n }\n else\n {\n\n F = f(1, a11, a12, a21, a22, b1, b2);\n\n }\n\n\n\n for(i=0; i<=m-2; i++)\n {\n\n if (( z[2 * i + 1] == 0 ) & (z[2 * i] > 0) & (z[2 * i] < 1))\n {\n\n F = f(z[2 * i], a11, a12, a21, a22, b1, b2);\n\n }\n\n }\n }\n else\n {\n F = 0.;\n }\n\n return F;\n\n\n\n}\n\n\n\n\ndouble container_square_overlap_potential(double *rA, double *radiiA, double phiA)\n{\n\n double rB[2];\n double radiiB[2];\n double phiB;\n\n double top = 0;\n double bottom = 0;\n double left = 0;\n double right = 0;\n\n // top\n rB[0] = 0.5;\n rB[1] = 2.0;\n radiiB[0] = INFINITY;\n radiiB[1] = 1.0;\n phiB = 0.0;\n top = ellipse_overlap(&rA[0], &radiiA[0], phiA, &rB[0], &radiiB[0], phiB);\n\n\n // bottom\n rB[0] = 0.5;\n rB[1] = -1.0;\n radiiB[0] = INFINITY;\n radiiB[1] = 1.0;\n phiB = 0.0;\n bottom = ellipse_overlap(&rA[0], &radiiA[0], phiA, &rB[0], &radiiB[0], phiB);\n\n\n\n // left\n rB[0] = -1.0;\n rB[1] = 0.5;\n radiiB[0] = 1.0;\n radiiB[1] = INFINITY;\n phiB = 0.0;\n left = ellipse_overlap(&rA[0], &radiiA[0], phiA, &rB[0], &radiiB[0], phiB);\n\n\n\n // right\n rB[0] = 2.0;\n rB[1] = 0.5;\n radiiB[0] = 1.0;\n radiiB[1] = INFINITY;\n phiB = 0.0;\n right = ellipse_overlap(&rA[0], &radiiA[0], phiA, &rB[0], &radiiB[0], phiB);\n\n\n\n\n return fminf(top, fminf(bottom, fminf(left, right)));\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nsize_t rsa_align_square(double *x, double *y,\n size_t npoints, double *radius, double phi, int step_limit,\n unsigned long randSeed)\n{\n\n // Setup GSL random number generator\n const gsl_rng_type * T;\n gsl_rng * r;\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n\n // Set the seed\n // srand ( time(NULL) );\n // unsigned long randSeed = rand();\n gsl_rng_set(r, randSeed);\n\n // arrays for overlap_potential functions\n double rA[2];\n double rB[2];\n double radiiA[2];\n double radiiB[2];\n double F;\n double xn = 0.;\n double yn = 0.;\n\n\n radiiA[0] = radius[0];\n radiiA[1] = radius[1];\n\n // Set the initial position\n double C;\n C = fmaxf(radius[0], radius[1]);\n\n F = 0;\n while (F < 1.)\n {\n\n xn = gsl_rng_uniform (r);\n yn = gsl_rng_uniform (r);\n\n rA[0] = xn;\n rA[1] = yn;\n\n F = container_square_overlap_potential(&rA[0], &radiiA[0], phi);\n\n }\n\n\n\n x[0] = xn;\n y[0] = yn;\n\n size_t valid_pts;\n int k, flag, step;\n\n step = 0;\n valid_pts = 1;\n while ((valid_pts < npoints) & (step < step_limit))\n {\n\n // Generate new ellipse inside the container\n F = 0;\n while (F < 1.)\n {\n\n xn = gsl_rng_uniform (r);\n yn = gsl_rng_uniform (r);\n\n rA[0] = xn;\n rA[1] = yn;\n\n F = container_square_overlap_potential(&rA[0], &radiiA[0], phi);\n\n }\n\n\n // Determine if new ellipse overlaps with existing ellipses\n flag = 1;\n for (k = 0; k < valid_pts; k++)\n {\n\n rA[0] = x[k];\n rA[1] = y[k];\n rB[0] = xn;\n rB[1] = yn;\n radiiA[0] = radius[0];\n radiiA[1] = radius[1];\n radiiB[0] = radius[0];\n radiiB[1] = radius[1];\n\n F = ellipse_overlap(&rA[0], &radiiA[0], phi, &rB[0], &radiiB[0], phi);\n\n if (F < 1.0)\n {\n\n flag = 0;\n break;\n\n }\n }\n if (flag == 1)\n {\n\n x[valid_pts] = xn;\n y[valid_pts] = yn;\n valid_pts += 1;\n\n }\n\n step += 1;\n \n }\n \n\n gsl_rng_free (r);\n\n return valid_pts;\n\n}\n\n\n\n\n\n\n\n\n\n\n\nsize_t rsa_square(double *x, double *y,\n size_t npoints, double *radius, double *phi, int step_limit,\n unsigned long randSeed)\n{\n\n // Setup GSL random number generator\n const gsl_rng_type * T;\n gsl_rng * r;\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n\n // Set the seed\n // srand ( time(NULL) );\n // unsigned long randSeed = rand();\n gsl_rng_set(r, randSeed);\n\n // arrays for overlap_potential functions\n double rA[2];\n double rB[2];\n double radiiA[2];\n double radiiB[2];\n double phiA;\n double phiB;\n double F;\n double xn = 0;\n double yn = 0;\n double phin = 0;\n\n\n radiiA[0] = radius[0];\n radiiA[1] = radius[1];\n\n // Set the initial position\n double C;\n C = fmaxf(radius[0], radius[1]);\n\n F = 0;\n while (F < 1.)\n {\n\n xn = gsl_rng_uniform (r);\n yn = gsl_rng_uniform (r);\n\n rA[0] = xn;\n rA[1] = yn;\n phiA = 2 * M_PI * gsl_rng_uniform (r);\n\n F = container_square_overlap_potential(&rA[0], &radiiA[0], phiA);\n\n }\n\n\n\n x[0] = xn;\n y[0] = yn;\n phi[0] = phiA;\n\n size_t valid_pts;\n int k, flag, step;\n\n step = 0;\n valid_pts = 1;\n while ((valid_pts < npoints) & (step < step_limit))\n {\n\n // Generate new ellipse inside the container\n F = 0;\n while (F < 1.)\n {\n\n xn = gsl_rng_uniform (r);\n yn = gsl_rng_uniform (r);\n phin = 2 * M_PI * gsl_rng_uniform (r);\n\n rA[0] = xn;\n rA[1] = yn;\n phiA = phin;\n\n F = container_square_overlap_potential(&rA[0], &radiiA[0], phiA);\n\n }\n\n\n // Determine if new ellipse overlaps with existing ellipses\n flag = 1;\n for (k = 0; k < valid_pts; k++)\n {\n\n rA[0] = x[k];\n rA[1] = y[k];\n phiA = phi[k];\n\n\n rB[0] = xn;\n rB[1] = yn;\n phiB = phin;\n\n radiiA[0] = radius[0];\n radiiA[1] = radius[1];\n radiiB[0] = radius[0];\n radiiB[1] = radius[1];\n\n F = ellipse_overlap(&rA[0], &radiiA[0], phiA, &rB[0], &radiiB[0], phiB);\n\n if (F < 1.0)\n {\n\n flag = 0;\n break;\n\n }\n }\n if (flag == 1)\n {\n\n x[valid_pts] = xn;\n y[valid_pts] = yn;\n phi[valid_pts] = phin;\n valid_pts += 1;\n\n }\n\n step += 1;\n \n }\n \n\n gsl_rng_free (r);\n\n return valid_pts;\n\n}", "meta": {"hexsha": "6982edd357305a135062fd5b2dfedf111a95eb78", "size": 8770, "ext": "c", "lang": "C", "max_stars_repo_path": "particle_packing/cython/c/ellipse.c", "max_stars_repo_name": "aluchies/particle_packing", "max_stars_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "particle_packing/cython/c/ellipse.c", "max_issues_repo_name": "aluchies/particle_packing", "max_issues_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "particle_packing/cython/c/ellipse.c", "max_forks_repo_name": "aluchies/particle_packing", "max_forks_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2708333333, "max_line_length": 104, "alphanum_fraction": 0.4757126568, "num_tokens": 3150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.4196668270899542}} {"text": "/* interpolation/akima.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman\n */\n#include \n#include \n#include \n#include \n#include \"integ_eval.h\"\n#include \n\ntypedef struct\n{\n double * b;\n double * c;\n double * d;\n double * _m;\n} akima_state_t;\n\n\n/* common creation */\nstatic void *\nakima_alloc (size_t size)\n{\n akima_state_t *state = (akima_state_t *) malloc (sizeof (akima_state_t));\n \n if (state == NULL)\n {\n GSL_ERROR_NULL(\"failed to allocate space for state\", GSL_ENOMEM);\n }\n \n state->b = (double *) malloc (size * sizeof (double));\n \n if (state->b == NULL)\n {\n free (state);\n GSL_ERROR_NULL(\"failed to allocate space for b\", GSL_ENOMEM);\n }\n \n state->c = (double *) malloc (size * sizeof (double));\n \n if (state->c == NULL)\n {\n free (state->b);\n free (state);\n GSL_ERROR_NULL(\"failed to allocate space for c\", GSL_ENOMEM);\n }\n \n state->d = (double *) malloc (size * sizeof (double));\n \n if (state->d == NULL)\n {\n free (state->c);\n free (state->b);\n free (state);\n GSL_ERROR_NULL(\"failed to allocate space for d\", GSL_ENOMEM);\n }\n\n state->_m = (double *) malloc ((size + 4) * sizeof (double));\n\n if (state->_m == NULL)\n {\n free (state->d);\n free (state->c);\n free (state->b);\n free (state);\n GSL_ERROR_NULL(\"failed to allocate space for _m\", GSL_ENOMEM);\n }\n \n return state;\n}\n\n\n/* common calculation */\nstatic void\nakima_calc (const double x_array[], double b[], double c[], double d[], size_t size, double m[])\n{\n size_t i;\n\n for (i = 0; i < (size - 1); i++)\n {\n const double NE = fabs (m[i + 1] - m[i]) + fabs (m[i - 1] - m[i - 2]);\n if (NE == 0.0)\n {\n b[i] = m[i];\n c[i] = 0.0;\n d[i] = 0.0;\n }\n else\n {\n const double h_i = x_array[i + 1] - x_array[i];\n const double NE_next = fabs (m[i + 2] - m[i + 1]) + fabs (m[i] - m[i - 1]);\n const double alpha_i = fabs (m[i - 1] - m[i - 2]) / NE;\n double alpha_ip1;\n double tL_ip1;\n if (NE_next == 0.0)\n {\n tL_ip1 = m[i];\n }\n else\n {\n alpha_ip1 = fabs (m[i] - m[i - 1]) / NE_next;\n tL_ip1 = (1.0 - alpha_ip1) * m[i] + alpha_ip1 * m[i + 1];\n }\n b[i] = (1.0 - alpha_i) * m[i - 1] + alpha_i * m[i];\n c[i] = (3.0 * m[i] - 2.0 * b[i] - tL_ip1) / h_i;\n d[i] = (b[i] + tL_ip1 - 2.0 * m[i]) / (h_i * h_i);\n }\n }\n}\n\n\nstatic int\nakima_init (void * vstate, const double x_array[], const double y_array[],\n size_t size)\n{\n akima_state_t *state = (akima_state_t *) vstate;\n\n double * m = state->_m + 2; /* offset so we can address the -1,-2\n components */\n\n size_t i;\n for (i = 0; i <= size - 2; i++)\n {\n m[i] = (y_array[i + 1] - y_array[i]) / (x_array[i + 1] - x_array[i]);\n }\n \n /* non-periodic boundary conditions */\n m[-2] = 3.0 * m[0] - 2.0 * m[1];\n m[-1] = 2.0 * m[0] - m[1];\n m[size - 1] = 2.0 * m[size - 2] - m[size - 3];\n m[size] = 3.0 * m[size - 2] - 2.0 * m[size - 3];\n \n akima_calc (x_array, state->b, state->c, state->d, size, m);\n \n return GSL_SUCCESS;\n}\n\n\nstatic int\nakima_init_periodic (void * vstate,\n const double x_array[],\n const double y_array[],\n size_t size)\n{\n akima_state_t *state = (akima_state_t *) vstate;\n \n double * m = state->_m + 2; /* offset so we can address the -1,-2\n components */\n\n size_t i;\n for (i = 0; i <= size - 2; i++)\n {\n m[i] = (y_array[i + 1] - y_array[i]) / (x_array[i + 1] - x_array[i]);\n }\n \n /* periodic boundary conditions */\n m[-2] = m[size - 1 - 2];\n m[-1] = m[size - 1 - 1];\n m[size - 1] = m[0];\n m[size] = m[1];\n \n akima_calc (x_array, state->b, state->c, state->d, size, m);\n\n return GSL_SUCCESS;\n}\n\nstatic void\nakima_free (void * vstate)\n{\n akima_state_t *state = (akima_state_t *) vstate;\n\n free (state->b);\n free (state->c);\n free (state->d);\n free (state->_m);\n free (state);\n}\n\n\nstatic\nint\nakima_eval (const void * vstate,\n const double x_array[], const double y_array[], size_t size,\n double x,\n gsl_interp_accel * a,\n double *y)\n{\n const akima_state_t *state = (const akima_state_t *) vstate;\n\n size_t index;\n \n if (a != 0)\n {\n index = gsl_interp_accel_find (a, x_array, size, x);\n }\n else\n {\n index = gsl_interp_bsearch (x_array, x, 0, size - 1);\n }\n \n /* evaluate */\n {\n const double x_lo = x_array[index];\n const double delx = x - x_lo;\n const double b = state->b[index];\n const double c = state->c[index];\n const double d = state->d[index];\n *y = y_array[index] + delx * (b + delx * (c + d * delx));\n return GSL_SUCCESS;\n }\n}\n\n\nstatic int\nakima_eval_deriv (const void * vstate,\n const double x_array[], const double y_array[], size_t size,\n double x,\n gsl_interp_accel * a,\n double *dydx)\n{\n const akima_state_t *state = (const akima_state_t *) vstate;\n\n size_t index;\n\n DISCARD_POINTER(y_array); /* prevent warning about unused parameter */\n \n if (a != 0)\n {\n index = gsl_interp_accel_find (a, x_array, size, x);\n }\n else\n {\n index = gsl_interp_bsearch (x_array, x, 0, size - 1);\n }\n \n /* evaluate */\n {\n double x_lo = x_array[index];\n double delx = x - x_lo;\n double b = state->b[index];\n double c = state->c[index];\n double d = state->d[index];\n *dydx = b + delx * (2.0 * c + 3.0 * d * delx);\n return GSL_SUCCESS;\n }\n}\n\n\nstatic\nint\nakima_eval_deriv2 (const void * vstate,\n const double x_array[], const double y_array[], size_t size,\n double x,\n gsl_interp_accel * a,\n double *y_pp)\n{\n const akima_state_t *state = (const akima_state_t *) vstate;\n\n size_t index;\n\n DISCARD_POINTER(y_array); /* prevent warning about unused parameter */\n\n if (a != 0)\n {\n index = gsl_interp_accel_find (a, x_array, size, x);\n }\n else\n {\n index = gsl_interp_bsearch (x_array, x, 0, size - 1);\n }\n \n /* evaluate */\n {\n const double x_lo = x_array[index];\n const double delx = x - x_lo;\n const double c = state->c[index];\n const double d = state->d[index];\n *y_pp = 2.0 * c + 6.0 * d * delx;\n return GSL_SUCCESS;\n }\n}\n\n\nstatic\nint\nakima_eval_integ (const void * vstate,\n const double x_array[], const double y_array[], size_t size,\n gsl_interp_accel * acc,\n double a, double b,\n double * result)\n{\n const akima_state_t *state = (const akima_state_t *) vstate;\n\n size_t i, index_a, index_b;\n\n if (acc != 0)\n {\n index_a = gsl_interp_accel_find (acc, x_array, size, a);\n index_b = gsl_interp_accel_find (acc, x_array, size, b);\n }\n else\n {\n index_a = gsl_interp_bsearch (x_array, a, 0, size - 1);\n index_b = gsl_interp_bsearch (x_array, b, 0, size - 1);\n }\n \n *result = 0.0;\n\n /* interior intervals */\n \n for(i=index_a; i<=index_b; i++) {\n const double x_hi = x_array[i + 1];\n const double x_lo = x_array[i];\n const double y_lo = y_array[i];\n const double dx = x_hi - x_lo;\n if(dx != 0.0) {\n\n if (i == index_a || i == index_b)\n {\n double x1 = (i == index_a) ? a : x_lo;\n double x2 = (i == index_b) ? b : x_hi;\n *result += integ_eval (y_lo, state->b[i], state->c[i], state->d[i],\n x_lo, x1, x2);\n }\n else\n {\n *result += dx * (y_lo \n + dx*(0.5*state->b[i] \n + dx*(state->c[i]/3.0 \n + 0.25*state->d[i]*dx)));\n }\n }\n else {\n *result = 0.0;\n return GSL_EINVAL;\n }\n }\n \n return GSL_SUCCESS;\n}\n\n\nstatic const gsl_interp_type akima_type = \n{\n \"akima\", \n 5,\n &akima_alloc,\n &akima_init,\n &akima_eval,\n &akima_eval_deriv,\n &akima_eval_deriv2,\n &akima_eval_integ,\n &akima_free\n};\n\nconst gsl_interp_type * gsl_interp_akima = &akima_type;\n\nstatic const gsl_interp_type akima_periodic_type = \n{\n \"akima-periodic\", \n 5,\n &akima_alloc,\n &akima_init_periodic,\n &akima_eval,\n &akima_eval_deriv,\n &akima_eval_deriv2,\n &akima_eval_integ,\n &akima_free\n};\n\nconst gsl_interp_type * gsl_interp_akima_periodic = &akima_periodic_type;\n", "meta": {"hexsha": "4244e0f1af7d96040cfe176e5736bc7763f39998", "size": 9394, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/interpolation/akima.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/akima.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/akima.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.0871794872, "max_line_length": 98, "alphanum_fraction": 0.5457738982, "num_tokens": 2865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4195515564723299}} {"text": "#include \"mpi.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __APPLE__\n\n#include \n#include \n\n#define set_num_threads(x) openblas_set_num_threads(x)\n#define get_num_threads() openblas_get_num_threads()\n#else\n#include \n#include \n#define set_num_threads(x) mkl_set_num_threads(x)\n#define get_num_threads() mkl_get_num_threads()\n#endif\n\ndouble norm_inf_mat_Y11(double *X, int n);\n\nint main(int argc, char **argv) {\n\n char *files[] = {\n //\"1200_m1_t2_hi_c363417000.7.mat.bin\",\n //\"1200_m1_t7_hi_c536234414.4.mat.bin\",\n //\"2340_m2_a1e15_to_c3291.0.mat.bin\",\n //\"5900_m1_t1_to_c3205771604.1.mat.bin\",\n //\"1200_m1_t3_hi_c70487569.2.mat.bin\",\n //\"2340_m1_t1_to_c1446918556.5.mat.bin\",\n //\"2340_m2_a1e5_to_c8.0.mat.bin\",\n //\"5900_m2_a1e15_to_c4198.3.mat.bin\",\n \"494_bus.mtx.bin\",\n //\"bcsstk13.mtx.bin\",\n //\"bcsstk27.mtx.bin\",\n //\"ex9.mtx.bin\",\n //\"msc01050.mtx.bin\",\n //\"bcsstk15.mtx.bin\",\n //\"cage9.mtx.bin\",\n //\"gyro.mtx.bin\",\n \"tomography.mtx.bin\"\n };\n int num_of_files = sizeof(files) / sizeof(char *);\n\n char *file_dir = NULL;\n int option = 0, omp_threads = 1;\n while ((option = getopt(argc, argv, \"f:t:\")) != -1) {\n switch (option) {\n case 'f':\n file_dir = optarg;\n break;\n case 't':\n omp_threads = atoi(optarg);\n break;\n default:\n printf(\"Usage: mpi_mexp -f string -t num_threads \\n\");\n return 0;\n }\n }\n if (file_dir == NULL) {\n printf(\"Usage: mpi_mexp -f string -t num_threads \\n\");\n return 0;\n }\n\n set_num_threads(omp_threads);\n omp_set_num_threads(omp_threads);\n\n int numTasks, rank;\n MPI_Init(&argc, &argv);\n MPI_Comm_size(MPI_COMM_WORLD, &numTasks);\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n int qProcs = (int) sqrt(numTasks);\n if (qProcs - sqrt(numTasks) != 0) {\n if (rank == 0)\n printf(\"np must be a square number\\n\");\n MPI_Finalize();\n return 0;\n }\n\n int q_root = qProcs - 1;\n int world_root = numTasks - 1;\n int n, dims[2] = {qProcs, qProcs}, periods[2] = {0, 0}, reorder = 0, coords[2], rc, i;\n MPI_Comm cartComm;\n MPI_Cart_create(MPI_COMM_WORLD, 2, dims, periods, reorder, &cartComm);\n MPI_Comm_rank(cartComm, &rank);\n MPI_Cart_coords(cartComm, rank, 2, coords);\n\n\n MPI_Comm rowComm, colComm;\n MPI_Comm_split(MPI_COMM_WORLD, coords[0], rank, &rowComm);\n MPI_Comm_split(MPI_COMM_WORLD, coords[1], rank, &colComm);\n\n int row_rank, col_rank;\n MPI_Comm_rank(colComm, &col_rank);\n MPI_Comm_rank(rowComm, &row_rank);\n\n\n char filename[1024];\n while (num_of_files-- > 0) {\n\n memset(filename, 0, strlen(filename));\n strcpy(filename, file_dir);\n strcat(filename, files[num_of_files]);\n\n MPI_Barrier(MPI_COMM_WORLD);\n\n if (rank == 0)\n printf(\"\\n%s\\n\", filename);\n MPI_File matFile;\n rc = MPI_File_open(cartComm, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &matFile);\n if (rc && (rank == 0)) {\n printf(\"Unable to open file %s\\n\", filename);\n fflush(stdout);\n }\n\n MPI_Status status;\n MPI_File_read(matFile, &n, 1, MPI_INT, &status);\n\n int blockSize = 0, lastBlock = 0;\n blockSize = (n + qProcs) / qProcs; /* number of rows in _block_ */\n lastBlock = n + 1 - (qProcs - 1) * blockSize;\n\n if (rank == 0) {\n printf(\"size: %d, %d ,%d\\n\", n, blockSize, lastBlock);\n }\n\n double *LocalA = (double *) malloc(blockSize * blockSize * sizeof(double));\n\n MPI_Datatype readFileType;\n MPI_Type_vector(blockSize, blockSize, n, MPI_DOUBLE, &readFileType);\n MPI_Type_commit(&readFileType);\n MPI_Offset offset = (MPI_Offset) (1 * sizeof(int) +\n sizeof(double) * (blockSize * coords[1] + blockSize * n * coords[0]));\n MPI_File_set_view(matFile, offset, MPI_DOUBLE, readFileType,\n \"native\", MPI_INFO_NULL);\n\n MPI_File_read_at(matFile, 0, LocalA, blockSize * blockSize, MPI_DOUBLE, &status);\n MPI_Type_free(&readFileType);\n if (coords[0] == q_root) {\n memset(LocalA + (lastBlock - 1) * blockSize, 0,\n (blockSize + 1 - lastBlock) * blockSize * sizeof(double));\n }\n if (coords[1] == q_root) {\n int kk = 0;\n for (kk = 0; kk < blockSize; ++kk) {\n memset(LocalA + kk * blockSize + lastBlock - 1, 0, (blockSize + 1 - lastBlock) * sizeof(double));\n }\n }\n\n double loc_d_var;\n double *loc_vec_var = (double *) malloc(blockSize * sizeof(double));\n memset(loc_vec_var, 0, blockSize * sizeof(double));\n offset = (MPI_Offset) (1 * sizeof(int) + sizeof(double) * n * n);\n MPI_File_set_view(matFile, offset, MPI_DOUBLE, MPI_DOUBLE,\n \"native\", MPI_INFO_NULL);\n offset = coords[0] * blockSize;\n MPI_File_read_at_all(matFile, offset, loc_vec_var, coords[0] == qProcs - 1 ? lastBlock : blockSize, MPI_DOUBLE,\n &status);\n\n MPI_File_close(&matFile);\n\n if (coords[1] == qProcs - 1) {\n cblas_dcopy(blockSize, loc_vec_var, 1, LocalA + lastBlock - 1, blockSize);\n }\n\n\n double mpi_start = MPI_Wtime();\n //compute inf norm of matA\n for (i = 0; i < (col_rank == q_root ? lastBlock - 1 : blockSize); ++i) {\n loc_vec_var[i] = cblas_dasum((row_rank == q_root ? lastBlock - 1 : blockSize), LocalA + i * blockSize,\n 1);\n }\n\n if (row_rank == q_root) {\n MPI_Reduce(MPI_IN_PLACE, loc_vec_var, blockSize, MPI_DOUBLE, MPI_SUM, q_root, rowComm);\n } else {\n MPI_Reduce(loc_vec_var, loc_vec_var, blockSize, MPI_DOUBLE, MPI_SUM, q_root, rowComm);\n }\n\n if (row_rank == q_root) {\n loc_d_var = 0;\n for (i = 0; i < (col_rank == q_root ? lastBlock - 1 : blockSize); ++i) {\n if (loc_vec_var[i] > loc_d_var)\n loc_d_var = loc_vec_var[i];\n }\n if (col_rank == q_root) {\n MPI_Reduce(MPI_IN_PLACE, &loc_d_var, 1, MPI_DOUBLE, MPI_MAX, q_root, colComm);\n } else {\n MPI_Reduce(&loc_d_var, &loc_d_var, 1, MPI_DOUBLE, MPI_MAX, q_root, colComm);\n }\n }\n\n MPI_Bcast(&loc_d_var, 1, MPI_DOUBLE, world_root, MPI_COMM_WORLD);\n\n //init Y martix\n for (i = 0; i < (col_rank == q_root ? lastBlock - 1 : blockSize); ++i) {\n cblas_dscal((row_rank == q_root ? lastBlock - 1 : blockSize), -1 / loc_d_var, LocalA + i * blockSize,\n 1);\n }\n if (row_rank == q_root) {\n cblas_dscal((col_rank == q_root ? lastBlock - 1 : blockSize), 1 / loc_d_var, LocalA + lastBlock - 1,\n blockSize);\n }\n if (row_rank == col_rank) {\n for (i = 0; i < (row_rank == q_root ? lastBlock - 1 : blockSize); ++i) {\n LocalA[i * blockSize + i] += 1;\n }\n }\n if (rank == world_root) {\n LocalA[(lastBlock - 1) * (blockSize + 1)] = 1;\n }\n\n //loop\n double tolerance = 1e-8;\n int loopBreak = 0, iteration = 0;\n double *col_mat = (double *) malloc(qProcs * blockSize * blockSize * sizeof(double));\n\n double *row_mat = (double *) malloc(qProcs * blockSize * blockSize * sizeof(double));\n\n while (true) {\n //norm mat\n //compute inf norm of matA\n for (i = 0; i < (col_rank == q_root ? lastBlock - 1 : blockSize); ++i) {\n loc_vec_var[i] = cblas_dasum((row_rank == q_root ? lastBlock - 1 : blockSize),\n LocalA + i * blockSize, 1);\n }\n\n if (row_rank == q_root) {\n MPI_Reduce(MPI_IN_PLACE, loc_vec_var, blockSize, MPI_DOUBLE, MPI_SUM, q_root, rowComm);\n } else {\n MPI_Reduce(loc_vec_var, loc_vec_var, blockSize, MPI_DOUBLE, MPI_SUM, q_root, rowComm);\n }\n\n if (row_rank == q_root) {\n loc_d_var = 0;\n for (i = 0; i < (col_rank == q_root ? lastBlock - 1 : blockSize); ++i) {\n if (loc_vec_var[i] > loc_d_var)\n loc_d_var = loc_vec_var[i];\n }\n if (col_rank == q_root) {\n MPI_Reduce(MPI_IN_PLACE, &loc_d_var, 1, MPI_DOUBLE, MPI_MAX, q_root, colComm);\n } else {\n MPI_Reduce(&loc_d_var, &loc_d_var, 1, MPI_DOUBLE, MPI_MAX, q_root, colComm);\n }\n\n size_t index = cblas_idamax((col_rank == q_root ? lastBlock - 1 : blockSize),\n LocalA + lastBlock - 1,\n blockSize);\n double norm2b = 0;\n MPI_Reduce(&LocalA[index * blockSize + lastBlock - 1], &norm2b, 1, MPI_DOUBLE, MPI_MAX, q_root,\n colComm);\n\n if (col_rank == q_root) {\n loopBreak = (loc_d_var / norm2b < tolerance) ? 1 : 0;\n }\n\n }\n MPI_Bcast(&loopBreak, 1, MPI_INT, world_root, MPI_COMM_WORLD);\n if (loopBreak > 0)\n break;\n\n iteration++;\n\n //gather loc mat\n MPI_Allgather(LocalA, blockSize * blockSize, MPI_DOUBLE, col_mat, blockSize * blockSize, MPI_DOUBLE,\n colComm);\n MPI_Allgather(LocalA, blockSize * blockSize, MPI_DOUBLE, row_mat, blockSize * blockSize, MPI_DOUBLE,\n rowComm);\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, blockSize, blockSize, blockSize,\n 1, row_mat, blockSize, col_mat, blockSize, 0.0, LocalA, blockSize);\n for (i = 1; i < qProcs; ++i) {\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, blockSize, blockSize, blockSize,\n 1, row_mat + i * (blockSize * blockSize), blockSize,\n col_mat + i * (blockSize * blockSize), blockSize, 1, LocalA, blockSize);\n }\n }\n\n free(row_mat);\n free(col_mat);\n free(loc_vec_var);\n\n\n if (rank == world_root) {\n printf(\"NumProc: %d\\n\", numTasks);\n printf(\"mpi_mexp_iter: %d\\t\", iteration);\n printf(\"mpi_mexp_time: %f\\n\", MPI_Wtime() - mpi_start);\n\n }\n\n if (row_rank == q_root) {\n for (i = 0; i < (row_rank == qProcs - 1 ? lastBlock : blockSize); ++i) {\n if (fabs(LocalA[i * blockSize + lastBlock - 1] - 1) > 1e-3) {\n printf(\"MPI_MEXP_ERR %f \\n\", LocalA[i * blockSize + lastBlock - 1]);\n break;\n }\n }\n }\n free(LocalA);\n\n /*\n * MPI_CG\n */\n rc = MPI_File_open(cartComm, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &matFile);\n if (rc && (rank == 0)) {\n printf(\"Unable to open file %s\\n\", filename);\n fflush(stdout);\n }\n\n MPI_File_read(matFile, &n, 1, MPI_INT, &status);\n blockSize = (n + qProcs - 1) / qProcs; /* number of rows in _block_ */\n lastBlock = n - (qProcs - 1) * blockSize;\n\n LocalA = (double *) malloc(blockSize * blockSize * sizeof(double));\n\n MPI_Type_vector(blockSize, blockSize, n, MPI_DOUBLE, &readFileType);\n MPI_Type_commit(&readFileType);\n offset = (MPI_Offset) (1 * sizeof(int) +\n sizeof(double) * (blockSize * coords[1] + blockSize * n * coords[0]));\n MPI_File_set_view(matFile, offset, MPI_DOUBLE, readFileType,\n \"native\", MPI_INFO_NULL);\n\n MPI_File_read_at(matFile, 0, LocalA, blockSize * blockSize, MPI_DOUBLE, &status);\n MPI_Type_free(&readFileType);\n if (coords[0] == qProcs - 1) {\n memset(LocalA + lastBlock * blockSize, 0, (blockSize - lastBlock) * blockSize * sizeof(double));\n }\n if (coords[1] == qProcs - 1) {\n int kk = 0;\n for (kk = 0; kk < blockSize; ++kk) {\n memset(LocalA + kk * blockSize + lastBlock, 0, (blockSize - lastBlock) * sizeof(double));\n }\n }\n\n double *LocalB = (double *) malloc(blockSize * sizeof(double));\n memset(LocalB, 0, blockSize * sizeof(double));\n offset = (MPI_Offset) (1 * sizeof(int) + sizeof(double) * n * n);\n MPI_File_set_view(matFile, offset, MPI_DOUBLE, MPI_DOUBLE,\n \"native\", MPI_INFO_NULL);\n offset = coords[1] * blockSize;\n MPI_File_read_at_all(matFile, offset, LocalB, coords[1] == qProcs - 1 ? lastBlock : blockSize, MPI_DOUBLE,\n &status);\n\n MPI_File_close(&matFile);\n mpi_start = MPI_Wtime();\n\n double alpha, beta, rho_new = 0.0, rho_old = 0.0;\n iteration = 0;\n double *loc_Vr = LocalB; //(double *) malloc(blockSize * sizeof(double));\n double *loc_Vp = (double *) malloc(blockSize * sizeof(double));\n double *loc_Vw = (double *) malloc(blockSize * sizeof(double));\n double *loc_Vx = (double *) malloc(blockSize * sizeof(double));\n\n\n //localr <- localB\n memset(loc_Vx, 0, blockSize * sizeof(double));\n //cblas_dcopy(blockSize, LocalB, 1, loc_Vr, 1);\n double b_norm2 = 0;\n if (col_rank == qProcs - 1) {\n double loc_b_dot = cblas_ddot((row_rank == qProcs - 1 ? lastBlock : blockSize), loc_Vr, 1, loc_Vr, 1);\n MPI_Reduce(&loc_b_dot, &rho_new, 1, MPI_DOUBLE, MPI_SUM, qProcs - 1, rowComm);\n b_norm2 = sqrt(rho_new);\n }\n\n loopBreak = 0;\n while (true) {\n if (rank == world_root) {\n loopBreak = (sqrt(rho_new) / b_norm2 < tolerance) ? 1 : 0;\n }\n MPI_Bcast(&loopBreak, 1, MPI_INT, world_root, MPI_COMM_WORLD);\n if (loopBreak > 0)\n break;\n\n iteration++;\n if (iteration == 1) {\n cblas_dcopy(blockSize, loc_Vr, 1, loc_Vp, 1);\n } else {\n if (rank == world_root) {\n beta = rho_new / rho_old;\n }\n MPI_Bcast(&beta, 1, MPI_DOUBLE, world_root, MPI_COMM_WORLD);\n cblas_dscal((row_rank == qProcs - 1 ? lastBlock : blockSize), beta, loc_Vp, 1);\n cblas_daxpy((row_rank == qProcs - 1 ? lastBlock : blockSize), 1.0, loc_Vr, 1, loc_Vp, 1);\n }\n\n cblas_dgemv(CblasRowMajor, CblasNoTrans, (col_rank == qProcs - 1 ? lastBlock : blockSize),\n (row_rank == qProcs - 1 ? lastBlock : blockSize),\n 1.0, LocalA, blockSize, loc_Vp, 1, 0.0, loc_Vw, 1);\n\n if (col_rank == row_rank) {\n MPI_Reduce(MPI_IN_PLACE, loc_Vw, blockSize, MPI_DOUBLE, MPI_SUM, col_rank, rowComm);\n } else {\n MPI_Reduce(loc_Vw, loc_Vw, blockSize, MPI_DOUBLE, MPI_SUM, col_rank, rowComm);\n }\n\n MPI_Bcast(loc_Vw, (row_rank == qProcs - 1 ? lastBlock : blockSize), MPI_DOUBLE, row_rank, colComm);\n\n if (col_rank == qProcs - 1) {\n double loc_pw_dot = cblas_ddot((row_rank == qProcs - 1 ? lastBlock : blockSize), loc_Vp, 1, loc_Vw,\n 1), glo_pw_dot;\n MPI_Reduce(&loc_pw_dot, &glo_pw_dot, 1, MPI_DOUBLE, MPI_SUM, qProcs - 1, rowComm);\n if (rank == world_root) {\n alpha = rho_new / glo_pw_dot;\n }\n }\n MPI_Bcast(&alpha, 1, MPI_DOUBLE, world_root, MPI_COMM_WORLD);\n\n cblas_daxpy((row_rank == qProcs - 1 ? lastBlock : blockSize), -alpha, loc_Vw, 1, loc_Vr, 1);\n\n if (coords[0] == qProcs - 1) {\n rho_old = rho_new;\n cblas_daxpy((row_rank == qProcs - 1 ? lastBlock : blockSize), alpha, loc_Vp, 1, loc_Vx, 1);\n double loc_r_dot = cblas_ddot(blockSize, loc_Vr, 1, loc_Vr, 1);\n\n MPI_Reduce(&loc_r_dot, &rho_new, 1, MPI_DOUBLE, MPI_SUM, qProcs - 1, rowComm);\n }\n }\n\n\n if (rank == world_root) {\n printf(\"mpi_cg_it: %d\\t\", iteration);\n printf(\"mpi_cg_time: %f\\n\", MPI_Wtime() - mpi_start);\n\n }\n free(LocalA);\n free(loc_Vp);\n free(loc_Vr);\n free(loc_Vw);\n\n if (col_rank == qProcs - 1) {\n for (rc = 0; rc < (row_rank == qProcs - 1 ? lastBlock : blockSize); ++rc) {\n if (fabs(loc_Vx[rc] - 1) > 1e-3) {\n printf(\"MPI_CG_ERR %f \\n\", loc_Vx[rc]);\n break;\n }\n }\n }\n free(loc_Vx);\n }\n\n MPI_Comm_free(&cartComm);\n MPI_Comm_free(&colComm);\n MPI_Comm_free(&rowComm);\n\n MPI_Finalize();\n}\n", "meta": {"hexsha": "de5246fb00d2c3b72dd521166158eb329fe7300d", "size": 17341, "ext": "c", "lang": "C", "max_stars_repo_path": "mpi/mpi_all.c", "max_stars_repo_name": "baishuai/MEXP", "max_stars_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mpi/mpi_all.c", "max_issues_repo_name": "baishuai/MEXP", "max_issues_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mpi/mpi_all.c", "max_forks_repo_name": "baishuai/MEXP", "max_forks_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5355555556, "max_line_length": 119, "alphanum_fraction": 0.5283432328, "num_tokens": 4654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.41954903593997445}} {"text": "/* integration/qmomof.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n\nstatic void\ncompute_moments (double par, double * cheb);\n\nstatic int\ndgtsl (size_t n, double *c, double *d, double *e, double *b);\n\ngsl_integration_qawo_table *\ngsl_integration_qawo_table_alloc (double omega, double L, \n enum gsl_integration_qawo_enum sine,\n size_t n)\n{\n gsl_integration_qawo_table *t;\n double * chebmo;\n\n if (n == 0)\n {\n GSL_ERROR_VAL (\"table length n must be positive integer\",\n GSL_EDOM, 0);\n }\n\n t = (gsl_integration_qawo_table *)\n malloc (sizeof (gsl_integration_qawo_table));\n\n if (t == 0)\n {\n GSL_ERROR_VAL (\"failed to allocate space for qawo_table struct\",\n GSL_ENOMEM, 0);\n }\n\n chebmo = (double *) malloc (25 * n * sizeof (double));\n\n if (chebmo == 0)\n {\n free (t);\n GSL_ERROR_VAL (\"failed to allocate space for chebmo block\",\n GSL_ENOMEM, 0);\n }\n\n t->n = n;\n t->sine = sine;\n t->omega = omega;\n t->L = L;\n t->par = 0.5 * omega * L;\n t->chebmo = chebmo;\n\n /* precompute the moments */\n\n { \n size_t i;\n double scale = 1.0;\n\n for (i = 0 ; i < t->n; i++)\n {\n compute_moments (t->par * scale, t->chebmo + 25*i);\n scale *= 0.5;\n }\n }\n\n return t;\n}\n\nint\ngsl_integration_qawo_table_set (gsl_integration_qawo_table * t,\n double omega, double L,\n enum gsl_integration_qawo_enum sine)\n{\n t->omega = omega;\n t->sine = sine;\n t->L = L;\n t->par = 0.5 * omega * L;\n\n /* recompute the moments */\n\n { \n size_t i;\n double scale = 1.0;\n\n for (i = 0 ; i < t->n; i++)\n {\n compute_moments (t->par * scale, t->chebmo + 25*i);\n scale *= 0.5;\n }\n }\n\n return GSL_SUCCESS;\n}\n\n\nint\ngsl_integration_qawo_table_set_length (gsl_integration_qawo_table * t,\n double L)\n{\n /* return immediately if the length is the same as the old length */\n\n if (L == t->L)\n return GSL_SUCCESS;\n\n /* otherwise reset the table and compute the new parameters */\n\n t->L = L;\n t->par = 0.5 * t->omega * L;\n\n /* recompute the moments */\n\n { \n size_t i;\n double scale = 1.0;\n\n for (i = 0 ; i < t->n; i++)\n {\n compute_moments (t->par * scale, t->chebmo + 25*i);\n scale *= 0.5;\n }\n }\n\n return GSL_SUCCESS;\n}\n\n\nvoid\ngsl_integration_qawo_table_free (gsl_integration_qawo_table * t)\n{\n RETURN_IF_NULL (t);\n free (t->chebmo);\n free (t);\n}\n\nstatic void\ncompute_moments (double par, double *chebmo)\n{\n double v[28], d[25], d1[25], d2[25];\n\n const size_t noeq = 25;\n \n const double par2 = par * par;\n const double par4 = par2 * par2;\n const double par22 = par2 + 2.0;\n\n const double sinpar = sin (par);\n const double cospar = cos (par);\n\n size_t i;\n\n /* compute the chebyschev moments with respect to cosine */\n\n double ac = 8 * cospar;\n double as = 24 * par * sinpar;\n\n v[0] = 2 * sinpar / par;\n v[1] = (8 * cospar + (2 * par2 - 8) * sinpar / par) / par2;\n v[2] = (32 * (par2 - 12) * cospar\n + (2 * ((par2 - 80) * par2 + 192) * sinpar) / par) / par4;\n\n if (fabs (par) <= 24)\n {\n /* compute the moments as the solution of a boundary value\n problem using the asyptotic expansion as an endpoint */\n \n double an2, ass, asap;\n double an = 6;\n size_t k;\n\n for (k = 0; k < noeq - 1; k++)\n {\n an2 = an * an;\n d[k] = -2 * (an2 - 4) * (par22 - 2 * an2);\n d2[k] = (an - 1) * (an - 2) * par2;\n d1[k + 1] = (an + 3) * (an + 4) * par2;\n v[k + 3] = as - (an2 - 4) * ac;\n an = an + 2.0;\n }\n\n an2 = an * an;\n\n d[noeq - 1] = -2 * (an2 - 4) * (par22 - 2 * an2);\n v[noeq + 2] = as - (an2 - 4) * ac;\n v[3] = v[3] - 56 * par2 * v[2];\n\n ass = par * sinpar;\n asap = (((((210 * par2 - 1) * cospar - (105 * par2 - 63) * ass) / an2\n - (1 - 15 * par2) * cospar + 15 * ass) / an2 \n - cospar + 3 * ass) / an2 \n - cospar) / an2;\n v[noeq + 2] = v[noeq + 2] - 2 * asap * par2 * (an - 1) * (an - 2);\n\n dgtsl (noeq, d1, d, d2, v + 3);\n\n }\n else\n {\n /* compute the moments by forward recursion */\n size_t k;\n double an = 4;\n\n for (k = 3; k < 13; k++)\n {\n double an2 = an * an;\n v[k] = ((an2 - 4) * (2 * (par22 - 2 * an2) * v[k - 1] - ac)\n + as - par2 * (an + 1) * (an + 2) * v[k - 2]) \n / (par2 * (an - 1) * (an - 2));\n an = an + 2.0;\n }\n }\n\n\n for (i = 0; i < 13; i++)\n {\n chebmo[2 * i] = v[i];\n }\n\n /* compute the chebyschev moments with respect to sine */\n\n v[0] = 2 * (sinpar - par * cospar) / par2;\n v[1] = (18 - 48 / par2) * sinpar / par2 + (-2 + 48 / par2) * cospar / par;\n\n ac = -24 * par * cospar;\n as = -8 * sinpar;\n\n if (fabs (par) <= 24)\n {\n /* compute the moments as the solution of a boundary value\n problem using the asyptotic expansion as an endpoint */\n\n size_t k;\n double an2, ass, asap;\n double an = 5;\n\n for (k = 0; k < noeq - 1; k++)\n {\n an2 = an * an;\n d[k] = -2 * (an2 - 4) * (par22 - 2 * an2);\n d2[k] = (an - 1) * (an - 2) * par2;\n d1[k + 1] = (an + 3) * (an + 4) * par2;\n v[k + 2] = ac + (an2 - 4) * as;\n an = an + 2.0;\n }\n \n an2 = an * an;\n\n d[noeq - 1] = -2 * (an2 - 4) * (par22 - 2 * an2);\n v[noeq + 1] = ac + (an2 - 4) * as;\n v[2] = v[2] - 42 * par2 * v[1];\n\n ass = par * cospar;\n asap = (((((105 * par2 - 63) * ass - (210 * par2 - 1) * sinpar) / an2\n + (15 * par2 - 1) * sinpar\n - 15 * ass) / an2 - sinpar - 3 * ass) / an2 - sinpar) / an2;\n v[noeq + 1] = v[noeq + 1] - 2 * asap * par2 * (an - 1) * (an - 2);\n\n dgtsl (noeq, d1, d, d2, v + 2);\n\n }\n else\n {\n /* compute the moments by forward recursion */\n size_t k;\n double an = 3;\n for (k = 2; k < 12; k++)\n {\n double an2 = an * an;\n v[k] = ((an2 - 4) * (2 * (par22 - 2 * an2) * v[k - 1] + as)\n + ac - par2 * (an + 1) * (an + 2) * v[k - 2]) \n / (par2 * (an - 1) * (an - 2));\n an = an + 2.0;\n }\n }\n\n for (i = 0; i < 12; i++)\n {\n chebmo[2 * i + 1] = v[i];\n }\n\n}\n\nstatic int\ndgtsl (size_t n, double *c, double *d, double *e, double *b)\n{\n /* solves a tridiagonal matrix A x = b \n \n c[1 .. n - 1] subdiagonal of the matrix A\n d[0 .. n - 1] diagonal of the matrix A\n e[0 .. n - 2] superdiagonal of the matrix A\n\n b[0 .. n - 1] right hand side, replaced by the solution vector x */\n\n size_t k;\n\n c[0] = d[0];\n\n if (n == 0)\n {\n return GSL_SUCCESS;\n }\n\n if (n == 1)\n {\n b[0] = b[0] / d[0] ;\n return GSL_SUCCESS;\n }\n\n d[0] = e[0];\n e[0] = 0;\n e[n - 1] = 0;\n\n for (k = 0; k < n - 1; k++)\n {\n size_t k1 = k + 1;\n\n if (fabs (c[k1]) >= fabs (c[k]))\n {\n {\n double t = c[k1];\n c[k1] = c[k];\n c[k] = t;\n };\n {\n double t = d[k1];\n d[k1] = d[k];\n d[k] = t;\n };\n {\n double t = e[k1];\n e[k1] = e[k];\n e[k] = t;\n };\n {\n double t = b[k1];\n b[k1] = b[k];\n b[k] = t;\n };\n }\n\n if (c[k] == 0)\n {\n return GSL_FAILURE ;\n }\n\n {\n double t = -c[k1] / c[k];\n\n c[k1] = d[k1] + t * d[k];\n d[k1] = e[k1] + t * e[k];\n e[k1] = 0;\n b[k1] = b[k1] + t * b[k];\n }\n\n }\n\n if (c[n - 1] == 0)\n {\n return GSL_FAILURE;\n }\n\n\n b[n - 1] = b[n - 1] / c[n - 1];\n\n b[n - 2] = (b[n - 2] - d[n - 2] * b[n - 1]) / c[n - 2];\n\n for (k = n ; k > 2; k--)\n {\n size_t kb = k - 3;\n b[kb] = (b[kb] - d[kb] * b[kb + 1] - e[kb] * b[kb + 2]) / c[kb];\n }\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "802eaddffd62501e97cb4b79b35b666491a29548", "size": 8993, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/integration/qmomof.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/qmomof.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/qmomof.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 23.0, "max_line_length": 81, "alphanum_fraction": 0.4628044034, "num_tokens": 3189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4194322149429973}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n//#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"21CMMC.h\"\n\nvoid ComputeInitialConditions(struct UserParams user_params, struct CosmoParams cosmo_params, struct InitialConditions boxes) {\n \n /*\n Generates the initial conditions: gaussian random density field (DIM^3) as well as the equal or lower resolution velocity fields, and smoothed density field (HII_DIM^3).\n See INIT_PARAMS.H and ANAL_PARAMS.H to set the appropriate parameters.\n Output is written to ../Boxes\n \n Author: Andrei Mesinger\n Date: 9/29/06\n */\n \n fftwf_plan plan;\n \n unsigned long long ct;\n int n_x, n_y, n_z, i, j, k, ii;\n float k_x, k_y, k_z, k_mag, p, a, b, k_sq;\n double pixel_deltax;\n \n float f_pixel_factor;\n \n gsl_rng * r;\n \n /************ INITIALIZATION **********************/\n \n // Removed all references to threads as 21CMMC is always a single core implementation\n\n printf(\"%d\\n\",cosmo_params.RANDOM_SEED);\n // seed the random number generators\n// r = gsl_rng_alloc(gsl_rng_mt19937);\n// gsl_rng_set(r, cosmo_params.RANDOM_SEED);\n\n/*\n // allocate array for the k-space and real-space boxes\n HIRES_box = (fftwf_complex *) fftwf_malloc(sizeof(fftwf_complex)*user_params.KSPACE_NUM_PIXELS);\n HIRES_box_saved = (fftwf_complex *) fftwf_malloc(sizeof(fftwf_complex)*user_params.KSPACE_NUM_PIXELS);\n \n // now allocate memory for the lower-resolution box\n // use HII_DIM from ANAL_PARAMS\n LOWRES_density = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS);\n LOWRES_vx = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS);\n LOWRES_vy= (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS);\n LOWRES_vz = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS);\n \n if(SECOND_ORDER_LPT_CORRECTIONS){\n LOWRES_vx_2LPT = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS);\n LOWRES_vy_2LPT = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS);\n LOWRES_vz_2LPT = (float *) malloc(sizeof(float)*HII_TOT_NUM_PIXELS);\n }\n \n // find factor of HII pixel size / deltax pixel size\n f_pixel_factor = DIM/(float)HII_DIM;\n*/\n \n /************ END INITIALIZATION ******************/\n \n /************ CREATE K-SPACE GAUSSIAN RANDOM FIELD ***********/\n/*\n for (n_x=0; n_xMIDDLE)\n k_x =(n_x-DIM) * DELTA_K; // wrap around for FFT convention\n else\n k_x = n_x * DELTA_K;\n \n for (n_y=0; n_yMIDDLE)\n k_y =(n_y-DIM) * DELTA_K;\n else\n k_y = n_y * DELTA_K;\n \n // since physical space field is real, only half contains independent modes\n for (n_z=0; n_z<=MIDDLE; n_z++){\n // convert index to numerical value for this component of the k-mode: k = (2*pi/L) * n\n k_z = n_z * DELTA_K;\n \n // now get the power spectrum; remember, only the magnitude of k counts (due to issotropy)\n // this could be used to speed-up later maybe\n k_mag = sqrt(k_x*k_x + k_y*k_y + k_z*k_z);\n p = power_in_k(k_mag);\n \n // ok, now we can draw the values of the real and imaginary part\n // of our k entry from a Gaussian distribution\n a = gsl_ran_ugaussian(r);\n b = gsl_ran_ugaussian(r);\n HIRES_box[C_INDEX(n_x, n_y, n_z)] = sqrt(VOLUME*p/2.0) * (a + b*I);\n }\n }\n }\n*/\n /***** Adjust the complex conjugate relations for a real array *****/\n\n// adj_complex_conj(HIRES_box);\n \n /*** Let's also create a lower-resolution version of the density field ***/\n \n/* memcpy(HIRES_box_saved, HIRES_box, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n \n if (DIM != HII_DIM)\n filter(HIRES_box, 0, L_FACTOR*BOX_LEN/(HII_DIM+0.0));\n // FFT back to real space\n plan = fftwf_plan_dft_c2r_3d(DIM, DIM, DIM, (fftwf_complex *)HIRES_box, (float *)HIRES_box, FFTW_ESTIMATE);\n fftwf_execute(plan);\n // now sample the filtered box\n for (i=0; iMIDDLE)\n k_x =(n_x-DIM) * DELTA_K; // wrap around for FFT convention\n else\n k_x = n_x * DELTA_K;\n \n for (n_y=0; n_yMIDDLE)\n k_y =(n_y-DIM) * DELTA_K;\n else\n k_y = n_y * DELTA_K;\n \n for (n_z=0; n_z<=MIDDLE; n_z++){\n k_z = n_z * DELTA_K;\n \n k_sq = k_x*k_x + k_y*k_y + k_z*k_z;\n \n // now set the velocities\n if ((n_x==0) && (n_y==0) && (n_z==0)){ // DC mode\n HIRES_box[0] = 0;\n }\n else{\n if(ii==0) {\n HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_x*I/k_sq/VOLUME;\n }\n if(ii==1) {\n HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_y*I/k_sq/VOLUME;\n }\n if(ii==2) {\n HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_z*I/k_sq/VOLUME;\n }\n // note the last factor of 1/VOLUME accounts for the scaling in real-space, following the FFT\n }\n }\n }\n }\n \n if (DIM != HII_DIM)\n filter(HIRES_box, 0, L_FACTOR*BOX_LEN/(HII_DIM+0.0));\n \n plan = fftwf_plan_dft_c2r_3d(DIM, DIM, DIM, (fftwf_complex *)HIRES_box, (float *)HIRES_box, FFTW_ESTIMATE);\n fftwf_execute(plan);\n // now sample to lower res\n // now sample the filtered box\n for (i=0; i INDEX\n // 00 -> 0\n // 11 -> 3\n // 22 -> 5\n // 10 -> 1\n // 20 -> 2\n // 21 -> 4\n \n fftwf_complex *phi_1[6];\n \n for(i = 0; i < 3; ++i){\n for(j = 0; j <= i; ++j){\n phi_1[PHI_INDEX(i, j)] = (fftwf_complex *) fftwf_malloc(sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n }\n }\n \n for(i = 0; i < 3; ++i){\n for(j = 0; j <= i; ++j){\n \n // read in the box\n memcpy(HIRES_box, HIRES_box_saved, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n \n // generate the phi_1 boxes in Fourier transform\n for (n_x=0; n_xMIDDLE)\n k_x =(n_x-DIM) * DELTA_K; // wrap around for FFT convention\n else\n k_x = n_x * DELTA_K;\n \n for (n_y=0; n_yMIDDLE)\n k_y =(n_y-DIM) * DELTA_K;\n else\n k_y = n_y * DELTA_K;\n \n for (n_z=0; n_z<=MIDDLE; n_z++){\n k_z = n_z * DELTA_K;\n \n k_sq = k_x*k_x + k_y*k_y + k_z*k_z;\n \n float k[] = {k_x, k_y, k_z};\n // now set the velocities\n if ((n_x==0) && (n_y==0) && (n_z==0)){ // DC mode\n phi_1[PHI_INDEX(i, j)][0] = 0;\n }\n else{\n phi_1[PHI_INDEX(i, j)][C_INDEX(n_x,n_y,n_z)] = -k[i]*k[j]*HIRES_box[C_INDEX(n_x, n_y, n_z)]/k_sq/VOLUME;\n // note the last factor of 1/VOLUME accounts for the scaling in real-space, following the FFT\n }\n }\n }\n }\n // Now we can generate the real phi_1[i,j]\n plan = fftwf_plan_dft_c2r_3d(DIM, DIM, DIM, (fftwf_complex *)phi_1[PHI_INDEX(i, j)], (float *)phi_1[PHI_INDEX(i, j)], FFTW_ESTIMATE);\n fftwf_execute(plan);\n }\n }\n \n // Then we will have the laplacian of phi_2 (eq. D13b)\n // After that we have to return in Fourier space and generate the Fourier transform of phi_2\n int m, l;\n for (i=0; i0) {\n memcpy(HIRES_box, HIRES_box_saved, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n }\n // set velocities/dD/dt\n for (n_x=0; n_xMIDDLE)\n k_x =(n_x-DIM) * DELTA_K; // wrap around for FFT convention\n else\n k_x = n_x * DELTA_K;\n \n for (n_y=0; n_yMIDDLE)\n k_y =(n_y-DIM) * DELTA_K;\n else\n k_y = n_y * DELTA_K;\n \n for (n_z=0; n_z<=MIDDLE; n_z++){\n k_z = n_z * DELTA_K;\n \n k_sq = k_x*k_x + k_y*k_y + k_z*k_z;\n \n // now set the velocities\n if ((n_x==0) && (n_y==0) && (n_z==0)){ // DC mode\n HIRES_box[0] = 0;\n }\n else{\n if(ii==0) {\n HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_x*I/k_sq;\n }\n if(ii==1) {\n HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_y*I/k_sq;\n }\n if(ii==2) {\n HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_z*I/k_sq;\n }\n // note the last factor of 1/VOLUME accounts for the scaling in real-space, following the FFT\n }\n }\n }\n }\n \n if (DIM != HII_DIM)\n filter(HIRES_box, 0, L_FACTOR*BOX_LEN/(HII_DIM+0.0));\n \n plan = fftwf_plan_dft_c2r_3d(DIM, DIM, DIM, (fftwf_complex *)HIRES_box, (float *)HIRES_box, FFTW_ESTIMATE);\n fftwf_execute(plan);\n // now sample to lower res\n // now sample the filtered box\n for (i=0; i\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#define FLOAT_RADIX 2.0\n#define FLOAT_RADIX_SQ (FLOAT_RADIX * FLOAT_RADIX)\n\nint\ngsl_linalg_balance_matrix(gsl_matrix * A, gsl_vector * D)\n{\n const size_t N = A->size1;\n\n if (N != D->size)\n {\n GSL_ERROR (\"vector must match matrix size\", GSL_EBADLEN);\n }\n else\n {\n double row_norm,\n col_norm;\n int not_converged;\n gsl_vector_view v;\n\n /* initialize D to the identity matrix */\n gsl_vector_set_all(D, 1.0);\n\n not_converged = 1;\n\n while (not_converged)\n {\n size_t i, j;\n double g, f, s;\n\n not_converged = 0;\n\n for (i = 0; i < N; ++i)\n {\n row_norm = 0.0;\n col_norm = 0.0;\n\n for (j = 0; j < N; ++j)\n {\n if (j != i)\n {\n col_norm += fabs(gsl_matrix_get(A, j, i));\n row_norm += fabs(gsl_matrix_get(A, i, j));\n }\n }\n\n if ((col_norm == 0.0) || (row_norm == 0.0))\n {\n continue;\n }\n\n g = row_norm / FLOAT_RADIX;\n f = 1.0;\n s = col_norm + row_norm;\n\n /*\n * find the integer power of the machine radix which\n * comes closest to balancing the matrix\n */\n while (col_norm < g)\n {\n f *= FLOAT_RADIX;\n col_norm *= FLOAT_RADIX_SQ;\n }\n\n g = row_norm * FLOAT_RADIX;\n\n while (col_norm > g)\n {\n f /= FLOAT_RADIX;\n col_norm /= FLOAT_RADIX_SQ;\n }\n\n if ((row_norm + col_norm) < 0.95 * s * f)\n {\n not_converged = 1;\n\n g = 1.0 / f;\n\n /*\n * apply similarity transformation D, where\n * D_{ij} = f_i * delta_{ij}\n */\n\n /* multiply by D^{-1} on the left */\n v = gsl_matrix_row(A, i);\n gsl_blas_dscal(g, &v.vector);\n\n /* multiply by D on the right */\n v = gsl_matrix_column(A, i);\n gsl_blas_dscal(f, &v.vector);\n\n /* keep track of transformation */\n gsl_vector_set(D, i, gsl_vector_get(D, i) * f);\n }\n }\n }\n\n return GSL_SUCCESS;\n }\n} /* gsl_linalg_balance_matrix() */\n\n/*\ngsl_linalg_balance_accum()\n Accumulate a balancing transformation into a matrix.\nThis is used during the computation of Schur vectors since the\nSchur vectors computed are the vectors for the balanced matrix.\nWe must at some point accumulate the balancing transformation into\nthe Schur vector matrix to get the vectors for the original matrix.\n\nA -> D A\n\nwhere D is the diagonal matrix\n\nInputs: A - matrix to transform\n D - vector containing diagonal elements of D\n*/\n\nint\ngsl_linalg_balance_accum(gsl_matrix *A, gsl_vector *D)\n{\n const size_t N = A->size1;\n\n if (N != D->size)\n {\n GSL_ERROR (\"vector must match matrix size\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n double s;\n gsl_vector_view r;\n\n for (i = 0; i < N; ++i)\n {\n s = gsl_vector_get(D, i);\n r = gsl_matrix_row(A, i);\n\n gsl_blas_dscal(s, &r.vector);\n }\n\n return GSL_SUCCESS;\n }\n} /* gsl_linalg_balance_accum() */\n", "meta": {"hexsha": "f07b1df375d6ef678ca4910be6e43d653e915a32", "size": 4986, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/linalg/balancemat.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/balancemat.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/balancemat.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 26.6631016043, "max_line_length": 81, "alphanum_fraction": 0.5453269154, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.41830853532674744}} {"text": "/*\n * Kaczmarz down-up sweep on diagonally banded matrix. The essential loop is:\n *\n * for each row i\n * x = x + w*(b(i) - A(i,:)*x)*A(i,:)'\n * end\n *\n * The matrix is given in band storage format, where each row (stored\n * contiguously in memory) of the array R stores a diagonal of the matrix with\n * offset idx(j), such that \n *\n * \t A(i,i+idx(j)) = R(i,j)\n *\n * use (from MATLAB):\n * \t\ty = sweepR_mex(R,idx,x,b,w,dir)\n *\n * \t\tR\t\t\t- matrix of diagonals of matrix A\n *\t\tidx\t\t\t- offsets of diagonals\n *\t\tx\t\t\t- initial guess\n * \t\tb \t\t\t- right hand side (source)\n *\t\tw \t\t\t- relaxation parameter (0 <= w <= 2)\n *\t\tns \t\t - number of RHS\n * \t\tn_threads\t- OPTIONAL argument to control the number of execution\n * \t\tthreads solving CARP blocks in parallel. The number of threads can also\n * \t\tbe defined via an environment variable (OMP_NUM_THREADS), but this\n * \t\toptional argument takes precedence. The default number of threads is\n * \t\tone. Take care if using more than one MATLAB worker per node: each\n * \t\tMATLAB worker will use OMP_NUM_THREADS, so if there are four workers on\n * \t\ta node, there will be 4 x OMP_NUM_THREADS parallel CARP sweeps.\n * compile :\n *\t mex -largeArrayDims sweep_MT_mex.c -DDEFINEUNIX -lmwblas CFLAGS=\"\\$CFLAGS -fopenmp\" LDFLAGS=\"\\$LDFLAGS -fopenmp\"\n *\n * Author: Mathias Louboutin from Art Petrenko sweepR_mex.c\n * Seismic Laboratory for Imaging and Modeling\n * Department of Earth, Ocean, and Atmosperic Sciences\n * The University of British Columbia\n * \n * Date: March, 2015\n \n * You may use this code only under the conditions and terms of the\n * license contained in the file LICENSE provided with this source\n * code. If you do not agree to these terms you may not use this\n * software.\n*/\n\n#include /* for getenv */\n#include /* for size_t type */\n#include /* for memcpy */\n#include /* for threading */\n#include \n\n/* The following section allows this file to compile on Mac OS X 10.8.5. Pass\n * the flag -DARCH_MACI64 to the compiler to activate it. */\n#ifdef ARCH_MACI64\n#include \ntypedef wchar_t char16_t;\n#else /* not ARCH_MACI64 */\n#include \n#endif /* ARCH_MACI64 */\n\n#include \n#include \n#include \n#include \n\nstruct copy_init_guess_data_t \n{\n\tdouble *copy_src_real, *copy_dst_real;\n\tdouble *copy_src_imag, *copy_dst_imag;\n\tlong n_to_copy;\n};\n\nstruct sweep_data_t \n{\n\tlong start_row, end_row, ncol, ny, nx, haloWidth, main_diagonal_offset;\n\tdouble *Rr, *Ri, *yr, *yi, *br, *bi;\n\tlong *idx;\n\tdouble w;\n\tint dir, n_threads, ns;\n};\n\nstruct average_data_t \n{\n\tdouble *copy_src_real, *copy_dst_real;\n\tdouble *copy_src_imag, *copy_dst_imag;\n\tdouble *halo_1_real, *halo_2_real;\n\tdouble *halo_1_imag, *halo_2_imag;\n\tdouble *halo_dst_real, *halo_dst_imag;\n\tlong n_to_copy, n_in_halo;\n};\n\nstruct thread_data_t \n{\n\tstruct copy_init_guess_data_t copy_init_guess_data;\n\tstruct sweep_data_t sweep_data;\n\tstruct average_data_t average_data;\n\tpthread_barrier_t *barrier;\n};\n\nvoid *do_sweep(void *thread_args_void)\n{\n struct sweep_data_t *thread_args;\n\t/* Variables contained in thread_args_void struct */\n\tlong start_row, end_row, ncol, ny, nx;\n\t/* Rr and Ri are pointers to short fat ncol-by-N matrices */\n\tdouble *Rr, *Ri, *yr, *yi, *br, *bi;\n\tlong *idx;\n\tdouble w;\n\tint n_threads,ns;\n\t/* Temporary storage variables */\n\tdouble cr = 0, ci = 0;\n\tlong offset, main_diagonal_offset;\n\t\n\t/* Assign local pointers to data locations in shared memory */\n\tthread_args = (struct sweep_data_t *) thread_args_void;\n\tstart_row \t= thread_args->start_row;\n\tend_row \t= thread_args->end_row;\n\tncol \t\t= thread_args->ncol;\n\tny \t\t\t= thread_args->ny;\n\tnx\t\t\t= thread_args->nx;\n\tmain_diagonal_offset = thread_args->main_diagonal_offset;\n\tRr \t\t\t= thread_args->Rr;\n\tRi \t\t\t= thread_args->Ri;\n\tidx \t\t= thread_args->idx;\n\tyr \t\t\t= thread_args->yr;\n\tyi \t\t\t= thread_args->yi;\n\tbr \t\t\t= thread_args->br;\n\tbi \t\t\t= thread_args->bi;\n\tw \t\t\t= thread_args->w;\n\tn_threads \t= thread_args->n_threads;\n\tns \t\t\t= thread_args->ns;\n\toffset = (start_row == 0 ? 0 : - main_diagonal_offset);\n\t\n\tlong i;\n\tint s;\n\tlong j;\n\tlong k;\n\tlong indj;\n\tlong toto;\n\n\t#pragma omp parallel for schedule(static,1) private(k,indj,i,j,cr,ci) num_threads(n_threads)\n\tfor(s=0 ; sstart_row-1 ;i-- )\n\t\t{\n\n\t\t\tif (0 <= i + main_diagonal_offset && i + main_diagonal_offset < nx){\n\t\t\t\tcr = br[i + main_diagonal_offset+s*nx];\n\t\t\t\tci = bi[i + main_diagonal_offset+nx*s];\n\t\t\t}\n\t\t\telse{\n\t\t\t\terror(1,0,\"Discovery of whether the iterate vector is haloed failed.\");\n\t\t\t}\n\t\t\t/* First loop over non-zero row elements calculates inner product\n\t\t\t * of matrix row and CARP iterate */\n\t\t\tlong diff = i - start_row + offset;\n\t\t\tlong icol=i*ncol;\n\n\t\t\tfor(j=0 ; j= 7){\n\t\tif(1 <= lrint(mxGetScalar(prhs[6]))){\n\t\t\tn_threads = lrint(mxGetScalar(prhs[6]));\n\t\t}\n\t}\n\n\t/* printf(\"Using %d threads \\n\",n_threads);\n\t/* Partition the iterate vector into blocks. Note that the below\n\t * partitioning scheme is slighlty different from that in pCARPCG.m in this\n\t * directory. The partitioning scheme of pCARPCG corresponds to\n\t * distributing a three dimensional array with dimensions given by n\n\t * according to Matlab's codistributor1d.defaultPartition(n(3)), and then\n\t * vectorizing it. The partition scheme of the present file instead uses\n\t * Matlab's codistributor1d.defaultPartion(prod(n)). In other words,\n\t * pCARPCG divides the iterate into blocks along the slow dimension,\n\t * whereas sweepR_mex.c does not take dimensionality into account, only the\n\t * total number of gridpoints. This is done to avoid needing an extra input\n\t * parameter with the the system dimensions. The seg_bounds_hi, _lo and\n\t * _mid arrays contain indices into non-haloed vectors, while the\n\t * seg_bounds_row array contains indices to the rows of the system matrix.\n\t *\n\t\t * yr_seg[i_thread-1] overlap yr_seg[i_thread]\n\t * ------------------------|-----|-----|-------------------------------\n\t * .----------------^ | ^-------------------.\n\t * seg_bounds_lo[i_thread], seg_bounds_mid[i_thread], seg_bounds_hi[i_thread]\n\t */\n\tnumGridPointsPerBlock = N;\n\tseg_bounds_hi = (mwSize *)mxCalloc(2,sizeof(mwSize));\n\tseg_bounds_mid = (mwSize *)mxCalloc(2,sizeof(mwSize));\n\tseg_bounds_lo = (mwSize *)mxCalloc(2,sizeof(mwSize));\n\tseg_bounds_row = (mwSize *)mxCalloc(2,sizeof(mwSize));\n\tif (N == nx){\n\t\tmain_diagonal_offset = 0;\n\t}\n\telse{\n\t\t/* The vector is haloed. We are only able to correctly process matrices\n\t\t * with a non-zero main diagonal and symmetric off-main diagonal offsets. */\n\t\tif (ncol % 2 != 1){\n\t\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:EvenNumberOfDiags\",\n\t\t\t\t\t\"Input iterate vector appears to be haloed but there is an even number of non-zero diagonals in the system matrix.\");\n\t\t}\n\t\tmain_diagonal_offset = idx[ncol/2];\n\t\tmwSize i;\n\t\tfor (i = 1; i <= ncol/2; i++){\n\t\t\tif (idx[ncol/2 + i] - main_diagonal_offset != -(idx[ncol/2 - i] - main_diagonal_offset)){\n\t\t\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:DiagsNotSymmetric\",\n\t\t\t\t\t\t\"Input iterate vector appears to be haloed but the pattern of non-zero diagonals in the system matrix is not symmetric.\");\n\t\t\t}\n\t\t}\n\t}\n\t\n\tseg_bounds_hi[0] = 0;\n\tseg_bounds_mid[0] = 0;\n\tseg_bounds_row[0] = 0;\n\tseg_bounds_lo[0] = 0;\n\tseg_bounds_lo[1] = nx;\n\tseg_bounds_hi[1] = nx;\n\tseg_bounds_mid[1] = nx;\n\tseg_bounds_row[1] = N;\n\t\n\tthread_args_sweep = (struct sweep_data_t **)mxCalloc(1, sizeof(struct sweep_data_t *));\n\n\t/* Set thread arguments */\n\tthread_args_sweep[0] = (struct sweep_data_t *)mxCalloc(1,sizeof(struct sweep_data_t));\n\tthread_args_sweep[0]->start_row \t= seg_bounds_row[0];\n\tthread_args_sweep[0]->end_row \t= seg_bounds_row[1];\n\tthread_args_sweep[0]->ncol \t \t= ncol;\n\tthread_args_sweep[0]->ny \t \t= seg_bounds_hi[1]-seg_bounds_lo[0];\n\tthread_args_sweep[0]->nx\t\t\t= nx;\n\tthread_args_sweep[0]->main_diagonal_offset = main_diagonal_offset;\n\tthread_args_sweep[0]->Rr \t\t= Rr;\n\tthread_args_sweep[0]->Ri \t\t= Ri;\n\tthread_args_sweep[0]->idx \t\t= idx;\n\tthread_args_sweep[0]->yr\t \t= yr;\n\tthread_args_sweep[0]->yi\t \t= yi;\n\tthread_args_sweep[0]->br \t\t= br;\n\tthread_args_sweep[0]->bi \t\t= bi;\n\tthread_args_sweep[0]->w \t\t = w;\n\tthread_args_sweep[0]->n_threads = n_threads;\n\tthread_args_sweep[0]->ns = ns;\n\t/* Set the initial guess directly in the output array too */\n\tmemcpy((void *)yr, (void *)xr, sizeof(double)*nx*ns);\n\tmemcpy((void *)yi, (void *)xi, sizeof(double)*nx*ns);\n\tdo_sweep((void *)thread_args_sweep[0]);\n\n\t/* Free memory if it was allocated within the MEX file. */\n\tif (Ri_alloc){\n\t\tmxFree(Ri);\n\t}\n\tif (xi_alloc){\n\t\tmxFree(xi);\n\t}\n\tif (bi_alloc){\n\t\tmxFree(bi);\n\t}\n\n\tmxFree(idx);\n\tmxFree(thread_args_sweep);\n\n\t/* Don't think I need pthread_exit() here, because pthread_join is called above */\n\treturn;\n}\n", "meta": {"hexsha": "2da869d95b20b21fb67d9af48500141927932b45", "size": 13756, "ext": "c", "lang": "C", "max_stars_repo_path": "tools/deprecated/solvers/Krylov/sweep_MT_mex_old.c", "max_stars_repo_name": "liaman/SLIM-release-apps-public", "max_stars_repo_head_hexsha": "4db4043a38c5a4b7ccfee87be3e43992a38e8054", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-26T02:42:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T13:36:49.000Z", "max_issues_repo_path": "tools/deprecated/solvers/Krylov/sweep_MT_mex_old.c", "max_issues_repo_name": "yuanyuxin0077/SLIM-release-apps-public", "max_issues_repo_head_hexsha": "3fb78e7338b9f1702dfcc0a94748ce5e86562739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/deprecated/solvers/Krylov/sweep_MT_mex_old.c", "max_forks_repo_name": "yuanyuxin0077/SLIM-release-apps-public", "max_forks_repo_head_hexsha": "3fb78e7338b9f1702dfcc0a94748ce5e86562739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-15T02:34:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T08:46:39.000Z", "avg_line_length": 30.774049217, "max_line_length": 128, "alphanum_fraction": 0.6589124746, "num_tokens": 4271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.41823561219340794}} {"text": "#ifndef ALM_I_APG_H\r\n#define ALM_I_APG_H\r\n\r\n\r\n\r\n#include \"Matrix.h\"\r\n#include \"APPROX2.h\"\r\n#include \r\n#include \r\n#include \r\n#include /* printf */\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n//This class solves problem of the form f(x)+g(x) under the constraint Mx=c;\r\n// where f(x)=\\sum_{j=1}^m lambda_f[j] \\phi_j()\r\n//and g(x)=sum_{i=1}^n g_i(x_i). We all assume that each \\phi_j is 1-smooth.\r\n\r\n// Each subproblem solves problem of the form f(x)++1/2beta_s\\|Mx-c\\|^2+g(x) by APG. \r\n// This header file implements ASGARD_DL.\r\n\r\n\r\n\r\n\r\ntemplate\r\nclass ALM_I_APG: public APPROX2\r\n{\r\nprivate:\r\n\r\n std::vector Au;\r\n std::vector Az;\r\n\r\n std::vector Mu;\r\n std::vector Mz;\r\n\r\n\r\n std::vector Mx_s;\r\n std::vector Ax_s;\r\n std::vector lambda_f;\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nprotected:\r\n Matrix data_A;\r\n\r\n Matrix data_M;\r\n\r\n std::vector x_s;\r\n\r\n std::vector lambda_s;\r\n\r\n std::vector M_tlambda_s;\r\n\r\n D beta_s;\r\n\r\n D epsilon_s;\r\n\r\n D m_s;\r\n\r\n D mp_s;\r\n\r\n D m_0;\r\n\r\n L m_1;\r\n\r\n L m_2;\r\n\r\n D c_s;\r\n\r\n D eta;\r\n\r\n D rho;\r\n\r\n D max_Lf_s;\r\n\r\n D max_M_s;\r\n\r\n D Lf;\r\n\r\n D L_m;\r\n\r\n L val_mu_f;\r\n L val_mu_g;\r\n\r\n std::vector dual_alpha1; //dual_alpha1[j]=gradient_of_phi_j()\r\n\r\n std::vector dual_alpha2; //dual_alpha2[j]=(-c_j)\r\n\r\n std::vector baralpha1; //baralpha1=-sum_{j=1}^m_1 lambda_f[j]*dual_alpha1[j]*A_j\r\n\r\n std::vector baralpha2; //baralpha2=-sum_{j=1}^m_2 1/beta_s*dual_alpha2[j]*M_j\r\n\r\n D residual1; //residual1=\\dist(-M^\\top y, \\nabla f(x)+\\partial g(x))\r\n\r\n D residual2; //residual2=\\|Mx-c\\|\r\n\r\n D function_value;\r\n\r\n L print_every_N_ALM_I_APG;\r\n\r\n D running_time_ALM_I_APG;\r\n\r\n L nb_outer_iters;\r\n\r\n std::vector gradient_of_f;\r\n\r\n ofstream samp_ALM_I_APG;\r\npublic:\r\n\r\n\r\n\r\n virtual inline D gradient_of_phi_j(D, L){return D(NULL);}\r\n\r\n virtual inline D value_of_g_i(D, L){return D(NULL);}\r\n virtual inline D value_of_phi_j(D, L){return D(NULL);}\r\n\r\n virtual inline D prox_of_g_i(D,D,D, L){return D(NULL);}\r\n\r\n virtual inline D feasible_dual(std::vector &,std::vector &) {return D(NULL);}\r\n\r\n virtual inline D value_of_phistar_i(D,L) {return D(NULL);}\r\n virtual inline D value_of_g_tilde_star(D, vector &,vector &){return D(NULL);}\r\n\r\n virtual inline void set_matrix_M(){}\r\n\r\n virtual inline void set_matrix_A(){}\r\n\r\n\r\n\r\n virtual inline D distance_to_subgradient_of_g(){return D(NULL);}\r\n //virtual inline D distance_to_subgradient_of_g(std::vector &, std::vector & ){return D(NULL);}\r\n\r\n ALM_I_APG(const char* Matrix_file, D val_lambda_f)\r\n :data_A(), data_M()\r\n {\r\n\r\n }\r\n\r\n ALM_I_APG()\r\n :data_A(), data_M()\r\n {\r\n\r\n }\r\n\r\n\r\n L get_nb_features(){\r\n return data_A.get_d();\r\n }\r\n\r\n\r\n //This function computes \\nabla_i f(gamma u +z)\r\n inline D partial_i_of_f(L i){\r\n D res=0;\r\n for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n {\r\n L j=data_A.col_idx[k];\r\n D tmp=lambda_f[j]*gradient_of_phi_j(this->gamma*Au[j]+Az[j], j);\r\n res+=data_A.A_t[k]*tmp;\r\n }\r\n for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n {\r\n L j=data_M.col_idx[k];\r\n D tmp=(this->gamma*Mu[j]+Mz[j]-data_M.b[j])/beta_s+lambda_s[j];\r\n res+=data_M.A_t[k]*tmp;\r\n }\r\n return res;\r\n }\r\n\r\n //This function computes argmin{x1 t+x2 t^2/2+g_i(x3+t)}\r\n //inline D compute_prox(D x1, D x2, D x3, L i){\r\n //return prox_operA_tor(x1,x2,x3,i);\r\n //}\r\n\r\n\r\n void compute_x(){\r\n for(L i=0;in;i++){\r\n this->x[i]=this->gamma*this->u[i]+this->z[i];\r\n x_s[i]=this->x[i];\r\n }\r\n for(L j=0;jgamma*this->Mu[j]+this->Mz[j];\r\n for(L j=0;jgamma*this->Au[j]+this->Az[j];\r\n }\r\n\r\n inline void compute_primal_value() {\r\n\r\n D res=0;\r\n for(L i=0;in;i++){\r\n this->x[i]=this->gamma*this->u[i]+this->z[i];\r\n res+=value_of_g_i(this->x[i],i);\r\n }\r\n\r\n for(L j=0;jgamma*Au[j]+Az[j],j);\r\n }\r\n for(L j=0;jgamma*Mu[j]+Mz[j]-data_M.b[j]+beta_s*lambda_s[j]);\r\n res+=tmp*tmp/2/beta_s;\r\n }\r\n this->primal_value=res;\r\n }\r\n\r\n inline void compute_dual_value(){\r\n for(L j=0;jgamma*Au[j]+Az[j], j);\r\n }\r\n for(L j=0;jgamma*Mu[j]+Mz[j]-data_M.b[j]+beta_s*lambda_s[j];\r\n }\r\n for(L i=0;in;i++){\r\n baralpha1[i]=0;\r\n for(L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++){\r\n L j=data_A.col_idx[k];\r\n baralpha1[i]-=dual_alpha1[j]*data_A.A_t[k]*lambda_f[j];\r\n }\r\n baralpha2[i]=0;\r\n for(L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++){\r\n L j=data_M.col_idx[k];\r\n baralpha2[i]-=dual_alpha2[j]*data_M.A_t[k]/beta_s;\r\n }\r\n }\r\n D res=0;\r\n D scal=feasible_dual(baralpha1, baralpha2);\r\n for(L j=0;jdual_value=res;\r\n }\r\n\r\n inline void compute_function_value() {\r\n D res=0;\r\n for(L i=0;in;i++){\r\n res+=value_of_g_i(x_s[i],i);\r\n }\r\n for(L j=0;j1e10)\r\n {cout<<\"larger than 1e10:\"<gamma*Au[j]+Az[j], j);\r\n res2+=data_A.A_t[k]*tmp;\r\n cout<<\"Ax[\"<gamma*Au[j]+Az[j]<gamma*Mu[j]+Mz[j]-data_M.b[j])/beta_s+lambda_s[j];\r\n cout<<\"Mu[\"<gamma< Tx(this->n,0);\r\n this->do_single_step_prox(Tx);\r\n D res=0;\r\n for(L i=0;in;i++)\r\n res+=(Tx[i]-this->x[i])*(Tx[i]-this->x[i]);\r\n this->gradient_norm=sqrt(res);\r\n }\r\n\r\n inline void set_v()\r\n {\r\n this->v.resize(this->n,0);\r\n D maxv=0;\r\n D minv=std::numeric_limits::max();\r\n D sumv=0;\r\n D sumvi1=0;\r\n L sumw=0;\r\n L maxw=0;\r\n L minw=this->n;\r\n this->sumofLi=0;\r\n for(L j=0;jn;i++)\r\n {\r\n D vi=0;\r\n D vi1=0;\r\n for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n {\r\n L j=data_A.col_idx[k];\r\n vi+=(1.+(data_A.w_t[j]-1.)*(this->tau-1.)/max(this->n-1.,1.))*data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];\r\n vi1+=data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];\r\n }\r\n for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n {\r\n L j=data_M.col_idx[k];\r\n vi+=(1.+(data_M.w_t[j]-1.)*(this->tau-1.)/max(this->n-1.,1.))*data_M.A_t[k]*data_M.A_t[k]/beta_s;\r\n vi1+=data_M.A_t[k]*data_M.A_t[k]/beta_s;\r\n }\r\n this->v[i]=vi;\r\n sumv+=vi;\r\n sumvi1+=vi1;\r\n if(maxvvi) minv=vi;\r\n }\r\n if(this->tau==this->n){\r\n for(L i=0;in;i++)\r\n this->v[i]=sumvi1;\r\n }\r\n this->sumofLi=sumvi1;\r\n cout<<\" max of v: \"<sumofLi<n/val_tau*20;\r\n\r\n //D tmp7=1-val_tau/this->n*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0));\r\n //cout<<\"tmp7: \"<n+0.)*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0))<n=\"<n<n;i++)\r\n {\r\n D vi=0;\r\n for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n {\r\n L j=data_A.col_idx[k];\r\n Lf+=data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];\r\n vi+=(1.+(data_A.w_t[j]-1.)*(this->tau-1.)/max(this->n-1.,1.))*data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];\r\n }\r\n if(vi>max_Lf_s) max_Lf_s=vi;\r\n D vi2=0;\r\n for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n {\r\n L j=data_M.col_idx[k];\r\n L_m+=data_M.A_t[k]*data_M.A_t[k];\r\n vi2+=(1.+(data_M.w_t[j]-1.)*(this->tau-1.)/max(this->n-1.,1.))*data_M.A_t[k]*data_M.A_t[k];\r\n }\r\n if(vi2>max_M_s) {max_M_s=vi2;cout<1)\r\n {\r\n for(L i=0;in;i++){\r\n for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n {\r\n data_M.A_t[k]*=scal;\r\n }\r\n }\r\n for(L j=0;jproba_vector.resize(this->n,(0.0+this->tau)/this->n);\r\n this->max_p=(0.0+this->tau)/this->n;\r\n }\r\n\r\n\r\n void compute_KKT_residual(){\r\n D res;\r\n for(L i=0; in;i++){\r\n res=0;\r\n for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n {\r\n L j=data_A.col_idx[k];\r\n D tmp=lambda_f[j]*gradient_of_phi_j(Ax_s[j], j);\r\n res+=data_A.A_t[k]*tmp;\r\n }\r\n gradient_of_f[i]=res;\r\n }\r\n residual1=distance_to_subgradient_of_g();\r\n res=0;\r\n for(L j=0;j nablaf(this->n);\r\n D res1=0;\r\n compute_Mty();\r\n for(L i=0;in;i++)\r\n {\r\n nablaf[i]=0;\r\n for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n {\r\n L j=data_M.col_idx[k];\r\n D tmp=lambda_s[j];\r\n nablaf[i]+=data_M.A_t[k]*tmp;\r\n }\r\n res1+=(nablaf[i]-M_tlambda_s[i])*(nablaf[i]-M_tlambda_s[i]);\r\n }\r\n //samp_ALM2<<\" res1 =\"<z[i]+=dz;\r\n for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n {\r\n L j=data_A.col_idx[k];\r\n Az[j]+=dz*data_A.A_t[k];\r\n }\r\n for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n {\r\n L j=data_M.col_idx[k];\r\n Mz[j]+=dz*data_M.A_t[k];\r\n //if(j==2869) cout<<\"gamma=\"<gamma<<\"; \"<x[i]+=dx;\r\n x_s[i]=this->x[i];\r\n L j;\r\n for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n {\r\n j=data_M.col_idx[k];\r\n Mx_s[j]+=dx*data_M.A_t[k];\r\n }\r\n for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n {\r\n j=data_A.col_idx[k];\r\n Ax_s[j]+=dx*data_A.A_t[k];\r\n }\r\n }\r\n\r\n inline void update_u_coordinate( L i, D du){\r\n this->u[i]+=du;\r\n for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n {\r\n L j=data_A.col_idx[k];\r\n Au[j]+=du*data_A.A_t[k];\r\n }\r\n for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n {\r\n L j=data_M.col_idx[k];\r\n Mu[j]+=du*data_M.A_t[k];\r\n }\r\n }\r\n\r\n void compute_Au(){\r\n for(L j=0;ju[kj]*data_A.A[k];\r\n }\r\n }\r\n\r\n void compute_Mu(){\r\n for(L j=0;ju[kj]*data_M.A[k];\r\n }\r\n }\r\n\r\n void compute_Az(){\r\n for(L j=0;jz[kj]*data_A.A[k];\r\n }\r\n }\r\n void compute_Mz(){\r\n for(L j=0;jz[kj]*data_M.A[k];\r\n }\r\n }\r\n\r\n void compute_Au(vector & x0){\r\n for(L j=0;j & x0){\r\n for(L j=0;j & x0){\r\n for(L j=0;j & x0){\r\n for(L j=0;j & x0){\r\n for(L j=0;j & x0){\r\n for(L j=0;jn,0);\r\n for(L i=0;in;i++)\r\n {\r\n for(L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++){\r\n L j=data_M.col_idx[k];\r\n M_tlambda_s[i]+=lambda_s[j]*data_M.A_t[k];\r\n }\r\n }\r\n\r\n }\r\n\r\n void update_y(){\r\n D res=0;\r\n D dl=0;\r\n for(L j=0;j & x0,vector & y0, D val_lambda_f){\r\n cout<<\"start initializing\"<tau=val_tau;\r\n m_1=data_A.get_n();\r\n m_2=data_M.get_n();\r\n cout<<\"m_1=\"<n=data_A.nfeatures;\r\n baralpha1.resize(this->n,0);\r\n baralpha2.resize(this->n,0);\r\n gradient_of_f.resize(this->n,0);\r\n\r\n rescale_Matrix();\r\n\r\n beta_s=beta_0;\r\n //if(max_Lf_s>0)\r\n // beta_s=min(beta_0,max_M_s/max_Lf_s);\r\n\r\n\r\n epsilon_s=epsilon_0;\r\n compute_m0(beta_s,val_eta,val_rho,val_tau);\r\n\r\n eta=val_eta;\r\n rho=val_rho;\r\n\r\n x_s.resize(this->n,0);\r\n lambda_s.resize(m_2,0);\r\n for(L i=0;in;i++)\r\n x_s[i]=x0[i];\r\n\r\n for(L j=0;jn,0);\r\n\r\n compute_cs();\r\n compute_Mty();\r\n\r\n Au.clear();\r\n Au.resize(m_1,0);\r\n Az.clear();\r\n Az.resize(m_1,0);\r\n Ax_s.clear();\r\n Ax_s.resize(m_1,0);\r\n Mu.clear();\r\n Mu.resize(m_2,0);\r\n Mz.clear();\r\n Mz.resize(m_2,0);\r\n Mx_s.clear();\r\n Mx_s.resize(m_2,0);\r\n\r\n compute_Az(x0);\r\n compute_Mz(x0);\r\n compute_Ax(x0);\r\n compute_Mx(x0);\r\n }\r\n\r\n void reset_everything(){\r\n epsilon_s*=rho*rho*eta;\r\n m_s/=eta;\r\n beta_s*=eta;\r\n\r\n compute_cs();\r\n compute_Mty();\r\n\r\n Au.clear();\r\n Au.resize(m_1,0);\r\n Az.clear();\r\n Az.resize(m_1,0);\r\n Mu.clear();\r\n Mu.resize(m_2,0);\r\n Mz.clear();\r\n Mz.resize(m_2,0);\r\n compute_Az(x_s);\r\n compute_Mz(x_s);\r\n }\r\n\r\n\r\n\r\n void APPROX_restart(L K, vector & x0, L val_tau, L eval, L p_N, L max_nb, D eps, string filename){\r\n std::vector tmp_x(this->n);\r\n for(L i=0;in;i++){\r\n tmp_x[i]=x0[i];\r\n }\r\n L k=0;\r\n while(kAPPROX_MU(tmp_x, val_tau, 0, 0, eval, p_N, K, eps, filename,1);\r\n \r\n for(L i=0;in;i++){\r\n tmp_x[i]=this->x[i];\r\n }\r\n cout<<\"restarting...\"<delta & x0,vector & y0, L val_tau, L max_nb_outer, L p_N_1, L p_N_2, D val_lambda_f,string filename1, string filename2, D time){\r\n Initialize(beta_0, epsilon_0, eta, rho,val_tau, x0, y0, val_lambda_f);\r\n\r\n nb_outer_iters=0;\r\n string sampname2=\"results/APPROXMU_\"+filename2;\r\n this->samp.open(sampname2.c_str());\r\n filename1=\"results/ALM2_\"+filename1;\r\n samp_ALM_I_APG.open(filename1.c_str());\r\n running_time_ALM_I_APG=0;\r\n print_every_N_ALM_I_APG=p_N_1;\r\n compute_and_record_res();\r\n D start;\r\n start = std::clock();\r\n std::vector record_x_s(this->n);\r\n std::vector record_x_sp1(this->n);\r\n cout<<\"m0=\"<n*val_tau)<n*val_tau)<<\"; beta_s=\"<APPROX_MU(x_s, val_tau, val_mu_f, val_mu_g, 3, p_N_2, ceil(m_s/this->n*val_tau), epsilon_s, filename2,1);\r\n //APPROX_restart(K, x_s, val_tau, 3, p_N_2, ceil((m_s+mp_s)/this->n*val_tau), epsilon_s, filename2);\r\n compute_x();\r\n update_y();\r\n nb_outer_iters++;\r\n running_time_ALM_I_APG+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;\r\n compute_and_record_res();\r\n start = std::clock();\r\n reset_everything();\r\n running_time_ALM_I_APG+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;\r\n while(nb_outer_itersn*val_tau)<<\"; beta_s=\"<APPROX_MU(x_s, val_tau, val_mu_f, val_mu_g, 3, p_N_2, ceil(m_s/this->n*val_tau), epsilon_s, filename2,1);\r\n for(L i=0;in;i++){\r\n record_x_s[i]=x_s[i];\r\n }\r\n //APPROX_restart(K, x_s, val_tau, 3, p_N_2, ceil((m_s+mp_s)/this->n*val_tau), epsilon_s, filename2);\r\n compute_x();\r\n update_y();\r\n nb_outer_iters++;\r\n running_time_ALM_I_APG+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;\r\n testing();\r\n compute_and_record_res();\r\n start = std::clock();\r\n reset_everything();\r\n running_time_ALM_I_APG+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;\r\n if (running_time_ALM_I_APG> time){\r\n \tbreak;\r\n\t\t }\r\n }\r\n\r\n }\r\n\r\n\r\n\r\n\r\n\r\n\r\n};\r\n\r\n#endif\r\n", "meta": {"hexsha": "d84f1ee1e0f2705d2aaf02942c3bf2d0abe59b07", "size": 22068, "ext": "h", "lang": "C", "max_stars_repo_path": "IPALM/ALM_I_APG.h", "max_stars_repo_name": "lifei16/supplementary_code", "max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IPALM/ALM_I_APG.h", "max_issues_repo_name": "lifei16/supplementary_code", "max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IPALM/ALM_I_APG.h", "max_forks_repo_name": "lifei16/supplementary_code", "max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z", "avg_line_length": 27.5505617978, "max_line_length": 209, "alphanum_fraction": 0.5082472358, "num_tokens": 7171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4177915906520314}} {"text": "/*\n * BRAINS\n * (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling\n * Yan-Rong Li, liyanrong@ihep.ac.cn\n * Thu, Aug 4, 2016\n */\n\n/*!\n * \\file blr_models.c\n * \\brief BLR models\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"brains.h\"\n\n/* cluster around outer disk face, Lopn_cos1 < Lopn_cos2 */\ninline double theta_sample_outer(double gam, double Lopn_cos1, double Lopn_cos2)\n{\n return acos(Lopn_cos1 + (Lopn_cos2-Lopn_cos1) * pow(gsl_rng_uniform(gsl_r), gam));\n}\n\n/* cluster around equatorial plane, Lopn_cos1 < Lopn_cos2 */\ninline double theta_sample_inner(double gam, double Lopn_cos1, double Lopn_cos2)\n{\n /* note that cosine is a decreaing function */\n double opn1 = acos(Lopn_cos1), opn2 = acos(Lopn_cos2);\n return opn2 + (opn1-opn2) * (1.0 - pow(gsl_rng_uniform(gsl_r), 1.0/gam));\n}\n\n/*================================================================\n * model 1\n * Brewer et al. (2011)'s model\n *\n * geometry: radial Gamma distribution\n * dynamics: elliptical orbits\n *================================================================\n */\nvoid gen_cloud_sample_model1(const void *pm, int flag_type, int flag_save)\n{\n int i, j, nc;\n double r, phi, dis, Lopn_cos, u;\n double x, y, z, xb, yb, zb, zb0, vx, vy, vz, vxb, vyb, vzb;\n double inc, F, beta, mu, k, a, s, rin, sig, Rs;\n double Lphi, Lthe, L, E;\n double V, weight, rnd;\n BLRmodel1 *model = (BLRmodel1 *)pm;\n double Emin, Lmax, Vr, Vr2, Vph, mbh, chi, lambda, q;\n \n\n Lopn_cos = cos(model->opn*PI/180.0);\n inc = acos(model->inc);\n beta = model->beta;\n F = model->F;\n mu = exp(model->mu);\n k = model->k;\n \n if(flag_type == 1) // 1D RM, no dynamical parameters\n {\n mbh = 0.0;\n }\n else \n {\n mbh = exp(model->mbh);\n lambda = model->lambda;\n q = model->q;\n }\n\n Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days\n a = 1.0/beta/beta;\n s = mu/a;\n rin = mu*F + Rs;\n sig = (1.0-F)*s;\n\n for(i=0; ircloud_max_set || r 1000)\n {\n printf(\"# Error, too many tries in generating ridial location of clouds.\\n\");\n exit(0);\n }\n rnd = gsl_ran_gamma(gsl_r, a, 1.0);\n// r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu);\n r = rin + sig * rnd;\n nc++;\n }\n phi = 2.0*PI * gsl_rng_uniform(gsl_r);\n\n x = r * cos(phi); \n y = r * sin(phi);\n z = 0.0;\n\n /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z;\n yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z;\n zb = sin(Lthe) * x + cos(Lthe) * z;*/\n\n xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y;\n yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y;\n zb = sin(Lthe) * x;\n\n zb0 = zb;\n if(zb0 < 0.0)\n zb = -zb;\n\n /* counter-rotate around y */\n x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc);\n y = yb;\n z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc);\n\n weight = 0.5 + k*(x/r);\n clouds_weight[i] = weight;\n\n#ifndef SpecAstro\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_type == 1)\n {\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n }\n#else\n switch(flag_type) \n {\n case 1: /* 1D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n break;\n \n case 2: /* 2D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n break;\n\n case 3: /* SA */\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 4: /* 1D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 5: /* 2D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n }\n \n#endif\n \n /* velocity \n * note that a cloud moves in its orbit plane, whose direction\n * is determined by the direction of its angular momentum.\n */\n Emin = - mbh/r;\n //Ecirc = 0.5 * Emin;\n //Lcirc = sqrt(2.0 * r*r * (Ecirc + mbh/r));\n \n for(j=0; j1.0e-2) /* make sure that exp is caculatable. */\n L = Lmax * lambda * log( (exp(1.0/lambda) - 1.0) * gsl_rng_uniform(gsl_r) + 1.0 );\n else\n L = Lmax * (1.0 + lambda * log(gsl_rng_uniform(gsl_r)) );\n \n Vr2 = 2.0 * (E + mbh/r) - L*L/r/r;\n if(Vr2>=0.0)\n {\n u = gsl_rng_uniform(gsl_r);\n Vr = sqrt(Vr2) * (uopn*PI/180.0);\n inc = acos(model->inc);\n beta = model->beta;\n F = model->F;\n mu = exp(model->mu);\n k = model->k;\n\n a = 1.0/beta/beta;\n s = mu/a;\n rin=mu*F;\n sig=(1.0-F)*s;\n \n if(flag_type == 1) //1D RM no dynamical parameters\n {\n mbh = 0.0;\n }\n else \n {\n mbh = exp(model->mbh);\n sigr = model->sigr;\n sigtheta = model->sigtheta * PI;\n }\n Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days\n\n a = 1.0/beta/beta;\n s = mu/a;\n rin = mu*F + Rs;\n sig = (1.0-F)*s;\n\n for(i=0; ircloud_max_set || r 1000)\n {\n printf(\"# Error, too many tries in generating ridial location of clouds.\\n\");\n exit(0);\n }\n rnd = gsl_ran_gamma(gsl_r, a, 1.0);\n// r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu);\n r = rin + sig * rnd;\n nc++;\n }\n phi = 2.0*PI * gsl_rng_uniform(gsl_r);\n\n x = r * cos(phi); \n y = r * sin(phi);\n z = 0.0;\n\n\n /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z;\n yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z;\n zb = sin(Lthe) * x + cos(Lthe) * z;*/\n\n xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y;\n yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y;\n zb = sin(Lthe) * x;\n\n zb0 = zb;\n if(zb0 < 0.0)\n zb = -zb;\n\n /* counter-rotate around y */\n x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc);\n y = yb;\n z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc);\n\n weight = 0.5 + k*(x/r);\n clouds_weight[i] = weight;\n\n#ifndef SpecAstro\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_type == 1)\n {\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n }\n#else\n switch(flag_type) \n {\n case 1: /* 1D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n break;\n \n case 2: /* 2D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n break;\n\n case 3: /* SA */\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 4: /* 1D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 5: /* 2D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n }\n \n#endif\n \n /* velocity \n * note that a cloud moves in its orbit plane, whose direction\n * is determined by the direction of its angular momentum.\n */\n Emin = - mbh/r;\n Ecirc = 0.5 * Emin;\n Lcirc = sqrt(2.0 * r*r * (Ecirc + mbh/r));\n Vcirc = Lcirc/r;\n \n for(j=0; jopn*PI/180.0);\n inc = acos(model->inc);\n alpha = model->alpha;\n F = model->F;\n Rin = exp(model->Rin);\n k = model->k;\n \n if(flag_type == 1)\n {\n mbh = 0.0;\n }\n else \n {\n mbh = exp(model->mbh);\n xi = model->xi;\n q = model->q;\n }\n Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days\n \n if(F*Rin > rcloud_max_set)\n F = rcloud_max_set/Rin;\n\n for(i=0; ircloud_max_set || r 1000)\n {\n printf(\"# Error, too many tries in generating ridial location of clouds.\\n\");\n exit(0);\n }\n if(fabs(1.0-alpha) > 1.0e-4)\n rnd = pow( gsl_rng_uniform(gsl_r) * ( pow(F, 1.0-alpha) - 1.0) + 1.0, 1.0/(1.0-alpha) );\n else\n rnd = exp( gsl_rng_uniform(gsl_r) * log(F) );\n r = Rin * rnd + Rs;\n nc++;\n }\n phi = 2.0*PI * gsl_rng_uniform(gsl_r);\n\n x = r * cos(phi); \n y = r * sin(phi);\n z = 0.0;\n\n\n /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z;\n yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z;\n zb = sin(Lthe) * x + cos(Lthe) * z;*/\n\n xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y;\n yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y;\n zb = sin(Lthe) * x;\n\n zb0 = zb;\n if(zb0 < 0.0)\n zb = -zb;\n\n// counter-rotate around y\n x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc);\n y = yb;\n z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc);\n\n weight = 0.5 + k*(x/r);\n clouds_weight[i] = weight;\n\n#ifndef SpecAstro\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_type == 1)\n {\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n }\n#else\n switch(flag_type) \n {\n case 1: /* 1D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n break;\n \n case 2: /* 2D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n break;\n\n case 3: /* SA */\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 4: /* 1D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 5: /* 2D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n }\n \n#endif\n \n// velocity \n// note that a cloud moves in its orbit plane, whose direction\n// is determined by the direction of its angular momentum.\n Emin = - mbh/r;\n //Ecirc = 0.5 * Emin;\n //Lcirc = sqrt(2.0 * r*r * (Ecirc + mbh/r));\n \n for(j=0; jopn*PI/180.0);\n inc = acos(model->inc);\n alpha = model->alpha;\n F = model->F;\n Rin = exp(model->Rin);\n k = model->k;\n \n if(flag_type == 1) // 1D RM, no dynamical parameters\n {\n mbh = 0.0;\n }\n else \n {\n mbh = exp(model->mbh);\n xi = model->xi;\n q = model->q;\n }\n Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days\n\n if(Rin*F > rcloud_max_set)\n F = rcloud_max_set/Rin;\n\n for(i=0; ircloud_max_set || r 1000)\n {\n printf(\"# Error, too many tries in generating ridial location of clouds.\\n\");\n exit(0);\n }\n if(fabs(1.0-alpha) > 1.0e-4)\n rnd = pow( gsl_rng_uniform(gsl_r) * ( pow(F, 1.0-alpha) - 1.0) + 1.0, 1.0/(1.0-alpha) );\n else\n rnd = exp( gsl_rng_uniform(gsl_r) * log(F) );\n r = Rin * rnd + Rs;\n nc++;\n }\n phi = 2.0*PI * gsl_rng_uniform(gsl_r);\n\n x = r * cos(phi); \n y = r * sin(phi);\n z = 0.0;\n\n\n /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z;\n yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z;\n zb = sin(Lthe) * x + cos(Lthe) * z; */\n \n xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y;\n yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y;\n zb = sin(Lthe) * x;\n\n zb0 = zb;\n if(zb0 < 0.0)\n zb = -zb;\n\n /* counter-rotate around y */\n x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc);\n y = yb;\n z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc);\n\n weight = 0.5 + k*(x/r);\n clouds_weight[i] = weight;\n\n#ifndef SpecAstro\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_type == 1)\n {\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n }\n#else\n switch(flag_type) \n {\n case 1: /* 1D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n break;\n \n case 2: /* 2D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n break;\n\n case 3: /* SA */\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 4: /* 1D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 5: /* 2D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n }\n \n#endif\n \n// velocity \n// note that a cloud moves in its orbit plane, whose direction\n// is determined by the direction of its angular momentum.\n Emin = - mbh/r;\n //Ecirc = 0.5 * Emin;\n //Lcirc = sqrt(2.0 * r*r * (Ecirc + mbh/r));\n \n for(j=0; jopn*PI/180.0); /* cosine of openning angle */\n inc = acos(model->inc); /* inclination angle in rad */\n alpha = model->alpha; \n Fin = model->Fin;\n Fout = exp(model->Fout); \n mu = exp(model->mu); /* mean radius */\n k = model->k; \n gam = model->gam;\n xi = model->xi;\n \n if(flag_type == 1) // 1D RM, no dynamical parameters\n {\n mbh = 0.0;\n }\n else \n {\n mbh = exp(model->mbh);\n fellip = model->fellip;\n fflow = model->fflow;\n sigr_circ = exp(model->sigr_circ);\n sigthe_circ = exp(model->sigthe_circ);\n sigr_rad = exp(model->sigr_rad);\n sigthe_rad = exp(model->sigthe_rad);\n theta_rot = model->theta_rot*PI/180.0;\n sig_turb = exp(model->sig_turb);\n }\n Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days\n\n if(mu*Fout > rcloud_max_set)\n Fout = rcloud_max_set/mu;\n \n frac1 = 1.0/(alpha+1.0) * (1.0 - pow(Fin, alpha+1.0));\n frac2 = 1.0/(alpha-1.0) * (1.0 - pow(Fout, -alpha+1.0));\n ratio = frac1/(frac1 + frac2);\n\n sin_inc_cmp = cos(inc);//sin(PI/2.0 - inc);\n cos_inc_cmp = sin(inc);//cos(PI/2.0 - inc);\n \n for(i=0; ircloud_max_set || r 1000)\n {\n printf(\"# Error, too many tries in generating ridial location of clouds.\\n\");\n exit(0);\n }\n \n rnd_frac = gsl_rng_uniform(gsl_r);\n rnd = gsl_rng_uniform(gsl_r);\n if(rnd_frac < ratio)\n {\n rndr = pow( 1.0 - rnd * (1.0 - pow(Fin, alpha+1.0)), 1.0/(1.0+alpha));\n }\n else\n {\n rndr = pow( 1.0 - rnd * (1.0 - pow(Fout, -alpha+1.0)), 1.0/(1.0-alpha));\n }\n r = rndr*mu + Rs;\n nc++;\n }\n phi = 2.0*PI * gsl_rng_uniform(gsl_r);\n cos_phi = cos(phi);\n sin_phi = sin(phi);\n\n /* Polar coordinates to Cartesian coordinate */\n x = r * cos_phi; \n y = r * sin_phi;\n z = 0.0;\n\n/* right-handed framework\n * first rotate around y axis by an angle of Lthe, then rotate around z axis \n * by an angle of Lphi\n */\n /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z;\n yb =-cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z;\n zb = sin(Lthe) * x + cos(Lthe) * z;*/\n\n xb = cos_Lthe*cos_Lphi * x + sin_Lphi * y;\n yb =-cos_Lthe*sin_Lphi * x + cos_Lphi * y;\n zb = sin_Lthe * x;\n \n zb0 = zb;\n rnd_xi = gsl_rng_uniform(gsl_r);\n if( (rnd_xi < 1.0 - xi) && zb0 < 0.0)\n zb = -zb;\n\n// counter-rotate around y, LOS is x-axis \n x = xb * cos_inc_cmp + zb * sin_inc_cmp;\n y = yb;\n z =-xb * sin_inc_cmp + zb * cos_inc_cmp;\n\n weight = 0.5 + k*(x/r);\n clouds_weight[i] = weight;\n\n#ifndef SpecAstro\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_type == 1)\n {\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n }\n#else\n switch(flag_type) \n {\n case 1: /* 1D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n break;\n \n case 2: /* 2D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n break;\n\n case 3: /* SA */\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 4: /* 1D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 5: /* 2D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n }\n \n#endif\n\n Vkep = sqrt(mbh/r);\n\n for(j=0; j= C_Unit) // make sure that the velocity is smaller than speed of light\n V = 0.9999*C_Unit * (V>0.0?1.0:-1.0);\n\n g = sqrt( (1.0 + V/C_Unit) / (1.0 - V/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects\n V = (g-1.0)*C_Unit;\n\n clouds_vel[i*parset.n_vel_per_cloud + j] = V;\n\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight);\n }\n }\n }\n\n return;\n}\n\n\n/*================================================================\n * model 6\n * Pancoast et al. (2014)'s model\n *\n * geometry: radial Gamma distribution\n * dynamics: ellipitcal orbits and inflow/outflow \n *================================================================\n */\nvoid gen_cloud_sample_model6(const void *pm, int flag_type, int flag_save)\n{\n int i, j, nc;\n double r, phi, cos_phi, sin_phi, dis, Lopn_cos;\n double x, y, z, xb, yb, zb, zb0, vx, vy, vz, vxb, vyb, vzb;\n double V, rhoV, theV, Vr, Vph, Vkep, Rs, g;\n double inc, F, beta, mu, k, gam, xi, a, s, sig, rin;\n double mbh, fellip, fflow, sigr_circ, sigthe_circ, sigr_rad, sigthe_rad, theta_rot, sig_turb;\n double Lphi, Lthe, sin_Lphi, cos_Lphi, sin_Lthe, cos_Lthe, sin_inc_cmp, cos_inc_cmp;\n double weight, rnd, rnd_xi;\n BLRmodel6 *model = (BLRmodel6 *)pm;\n\n Lopn_cos = cos(model->opn*PI/180.0); /* cosine of openning angle */\n inc = acos(model->inc); /* inclination angle in rad */\n beta = model->beta; \n F = model->F;\n mu = exp(model->mu); /* mean radius */\n k = model->k; \n gam = model-> gam;\n xi = model->xi;\n\n if(flag_type == 1) // 1D RM, no mbh parameters\n {\n mbh = 0.0;\n }\n else\n {\n mbh = exp(model->mbh);\n fellip = model->fellip;\n fflow = model->fflow;\n sigr_circ = exp(model->sigr_circ);\n sigthe_circ = exp(model->sigthe_circ);\n sigr_rad = exp(model->sigr_rad);\n sigthe_rad = exp(model->sigthe_rad);\n theta_rot = model->theta_rot*PI/180.0;\n sig_turb = exp(model->sig_turb);\n }\n Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days\n\n a = 1.0/beta/beta;\n s = mu/a;\n rin=mu*F + Rs; // include Scharzschild radius\n sig=(1.0-F)*s;\n \n sin_inc_cmp = cos(inc); //sin(PI/2.0 - inc);\n cos_inc_cmp = sin(inc); //cos(PI/2.0 - inc);\n \n for(i=0; ircloud_max_set || r 1000)\n {\n printf(\"# Error, too many tries in generating ridial location of clouds.\\n\");\n exit(0);\n }\n rnd = gsl_ran_gamma(gsl_r, a, 1.0);\n// r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu);\n r = rin + sig * rnd;\n nc++;\n }\n phi = 2.0*PI * gsl_rng_uniform(gsl_r);\n cos_phi = cos(phi);\n sin_phi = sin(phi);\n\n /* Polar coordinates to Cartesian coordinate */\n x = r * cos_phi; \n y = r * sin_phi;\n z = 0.0;\n\n/* right-handed framework\n * first rotate around y axis by an angle of Lthe, then rotate around z axis \n * by an angle of Lphi\n */\n /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z;\n yb =-cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z;\n zb = sin(Lthe) * x + cos(Lthe) * z; */\n \n xb = cos_Lthe*cos_Lphi * x + sin_Lphi * y;\n yb =-cos_Lthe*sin_Lphi * x + cos_Lphi * y;\n zb = sin_Lthe * x;\n\n zb0 = zb;\n rnd_xi = gsl_rng_uniform(gsl_r);\n if( (rnd_xi < 1.0 - xi) && zb0 < 0.0)\n zb = -zb;\n\n// counter-rotate around y, LOS is x-axis \n /* x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc);\n y = yb;\n z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc); */\n \n x = xb * cos_inc_cmp + zb * sin_inc_cmp;\n y = yb;\n z =-xb * sin_inc_cmp + zb * cos_inc_cmp;\n\n weight = 0.5 + k*(x/r);\n clouds_weight[i] = weight;\n\n#ifndef SpecAstro\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_type == 1) // 1D RM\n {\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n }\n#else\n switch(flag_type) \n {\n case 1: /* 1D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n break;\n \n case 2: /* 2D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n break;\n\n case 3: /* SA */\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 4: /* 1D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 5: /* 2D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n }\n \n#endif\n\n Vkep = sqrt(mbh/r);\n \n for(j=0; j= C_Unit) // make sure that the velocity is smaller than speed of light\n V = 0.9999*C_Unit * (V>0.0?1.0:-1.0);\n\n g = sqrt( (1.0 + V/C_Unit) / (1.0 - V/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects\n V = (g-1.0)*C_Unit;\n\n clouds_vel[i*parset.n_vel_per_cloud + j] = V;\n\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight);\n }\n }\n }\n\n return;\n}\n\n/*================================================================\n * model 7\n * shadowed model\n *\n * geometry: radial Gamma distribution\n * dynamics: elliptical orbits and inflow/outflow as in Pancoast'model\n *================================================================\n */\nvoid gen_cloud_sample_model7(const void *pm, int flag_type, int flag_save)\n{\n int i, j, nc, num_sh;\n double r, phi, dis, Lopn_cos, cos_phi, sin_phi;\n double x, y, z, xb, yb, zb, zb0, vx, vy, vz, vxb, vyb, vzb, Rs, g, sig_turb;\n double V, rhoV, theV, Vr, Vph, Vkep;\n double inc, F, beta, mu, k, gam, xi, a, s, sig, rin;\n double mbh, fellip, fflow, sigr_circ, sigthe_circ, sigr_rad, sigthe_rad, theta_rot;\n double Lphi, Lthe, sin_Lphi, cos_Lphi, sin_Lthe, cos_Lthe, sin_inc_cmp, cos_inc_cmp;\n double weight, rnd, rnd_xi;\n BLRmodel7 *model = (BLRmodel7 *)pm;\n\n Lopn_cos = cos(model->opn*PI/180.0); /* cosine of openning angle */\n inc = acos(model->inc); /* inclination angle in rad */\n beta = model->beta; \n F = model->F;\n mu = exp(model->mu); /* mean radius */\n k = model->k; \n gam = model-> gam;\n xi = model->xi;\n \n if(flag_type == 1) // 1D RM, no dyamical parameters\n {\n mbh = 0.0;\n }\n else \n {\n mbh = exp(model->mbh);\n fellip = model->fellip;\n fflow = model->fflow;\n sigr_circ = exp(model->sigr_circ);\n sigthe_circ = exp(model->sigthe_circ);\n sigr_rad = exp(model->sigr_rad);\n sigthe_rad = exp(model->sigthe_rad);\n theta_rot = model->theta_rot*PI/180.0;\n sig_turb = exp(model->sig_turb);\n }\n Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days\n\n a = 1.0/beta/beta;\n s = mu/a;\n rin=Rs + mu*F;\n sig=(1.0-F)*s;\n \n sin_inc_cmp = cos(inc); //sin(PI/2.0 - inc);\n cos_inc_cmp = sin(inc); //cos(PI/2.0 - inc);\n\n\n num_sh = (int)(parset.n_cloud_per_task * model->fsh);\n\n for(i=0; ircloud_max_set || r 1000)\n {\n printf(\"# Error, too many tries in generating ridial location of clouds.\\n\");\n exit(0);\n }\n rnd = gsl_ran_gamma(gsl_r, a, 1.0);\n// r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu);\n r = rin + sig * rnd;\n nc++;\n }\n phi = 2.0*PI * gsl_rng_uniform(gsl_r);\n cos_phi = cos(phi);\n sin_phi = sin(phi);\n\n /* Polar coordinates to Cartesian coordinate */\n x = r * cos_phi; \n y = r * sin_phi;\n z = 0.0;\n\n/* right-handed framework\n * first rotate around y axis by an angle of Lthe, then rotate around z axis \n * by an angle of Lphi\n */\n /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z;\n yb =-cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z;\n zb = sin(Lthe) * x + cos(Lthe) * z; */\n \n xb = cos_Lthe*cos_Lphi * x + sin_Lphi * y;\n yb =-cos_Lthe*sin_Lphi * x + cos_Lphi * y;\n zb = sin_Lthe * x;\n\n zb0 = zb;\n rnd_xi = gsl_rng_uniform(gsl_r);\n if( (rnd_xi < 1.0 - xi) && zb0 < 0.0)\n zb = -zb;\n\n// counter-rotate around y, LOS is x-axis \n x = xb * cos_inc_cmp + zb * sin_inc_cmp;\n y = yb;\n z =-xb * sin_inc_cmp + zb * cos_inc_cmp;\n\n weight = 0.5 + k*(x/r);\n clouds_weight[i] = weight;\n\n#ifndef SpecAstro\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_type == 1)\n {\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n }\n#else\n switch(flag_type) \n {\n case 1: /* 1D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n break;\n \n case 2: /* 2D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n break;\n\n case 3: /* SA */\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 4: /* 1D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 5: /* 2D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n }\n \n#endif\n\n Vkep = sqrt(mbh/r);\n\n for(j=0; j= C_Unit) // make sure that the velocity is smaller than speed of light\n V = 0.9999*C_Unit * (V>0.0?1.0:-1.0);\n\n g = sqrt( (1.0 + V/C_Unit) / (1.0 - V/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects\n V = (g-1.0)*C_Unit;\n\n clouds_vel[i*parset.n_vel_per_cloud + j] = V;\n\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight);\n }\n }\n }\n\n //second BLR region\n rin = exp(model->mu_un) * model->F_un + Rs;\n a = 1.0/(model->beta_un * model->beta_un);\n sig = exp(model->mu_un) * (1.0-model->F_un)/a;\n double Lopn_cos_un1, Lopn_cos_un2;\n Lopn_cos_un1 = Lopn_cos;\n if(model->opn + model->opn_un < 90.0)\n Lopn_cos_un2 = cos((model->opn + model->opn_un)/180.0*PI);\n else\n Lopn_cos_un2 = 0.0;\n \n if(flag_type != 1) // 1D RM, no dynamical parameters\n {\n fellip = model->fellip_un;\n fflow = model->fflow_un;\n }\n\n\n for(i=num_sh; ircloud_max_set || r 1000)\n {\n printf(\"# Error, too many tries in generating ridial location of clouds.\\n\");\n exit(0);\n }\n rnd = gsl_ran_gamma(gsl_r, a, 1.0);\n// r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu);\n r = rin + sig * rnd;\n nc++;\n }\n phi = 2.0*PI * gsl_rng_uniform(gsl_r);\n cos_phi = cos(phi);\n sin_phi = sin(phi);\n\n /* Polar coordinates to Cartesian coordinate */\n x = r * cos_phi; \n y = r * sin_phi;\n z = 0.0;\n\n/* right-handed framework\n * first rotate around y axis by an angle of Lthe, then rotate around z axis \n * by an angle of Lphi\n */\n /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z;\n yb =-cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z;\n zb = sin(Lthe) * x + cos(Lthe) * z; */\n \n xb = cos_Lthe*cos_Lphi * x + sin_Lphi * y;\n yb =-cos_Lthe*sin_Lphi * x + cos_Lphi * y;\n zb = sin_Lthe * x;\n\n zb0 = zb;\n rnd_xi = gsl_rng_uniform(gsl_r);\n if( (rnd_xi < 1.0 - xi) && zb0 < 0.0)\n zb = -zb;\n\n// counter-rotate around y, LOS is x-axis \n x = xb * cos_inc_cmp + zb * sin_inc_cmp;\n y = yb;\n z =-xb * sin_inc_cmp + zb * cos_inc_cmp;\n\n weight = 0.5 + k*(x/r);\n clouds_weight[i] = weight;\n \n#ifndef SpecAstro\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_type == 1)\n {\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n }\n#else\n switch(flag_type) \n {\n case 1: /* 1D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n break;\n \n case 2: /* 2D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n break;\n\n case 3: /* SA */\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 4: /* 1D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 5: /* 2D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n }\n \n#endif\n\n Vkep = sqrt(mbh/r);\n\n for(j=0; j= C_Unit) // make sure that the velocity is smaller than speed of light\n V = 0.9999*C_Unit * (V>0.0?1.0:-1.0);\n\n g = sqrt( (1.0 + V/C_Unit) / (1.0 - V/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects\n V = (g-1.0)*C_Unit;\n\n clouds_vel[i*parset.n_vel_per_cloud + j] = V;\n\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight);\n }\n }\n }\n\n return;\n}\n\n\n/* \n * model 8, generate cloud sample.\n * a disk wind model.\n */\nvoid gen_cloud_sample_model8(const void *pm, int flag_type, int flag_save)\n{\n int i;\n double theta_min, theta_max, r_min, r_max, Rblr, Rv, mbh, alpha, gamma, xi, lambda, k;\n double rnd, r, r0, theta, phi, xb, yb, zb, x, y, z, l, weight, sin_inc_cmp, cos_inc_cmp, inc;\n double dis, density, vl, vesc, Vr, Vph, vx, vy, vz, vxb, vyb, vzb, V, rnd_xi, zb0, lmax, R;\n double v0=6.0/VelUnit;\n BLRmodel8 *model=(BLRmodel8 *)pm;\n\n theta_min = model->theta_min/180.0 * PI;\n theta_max = model->dtheta_max/180.0*PI + theta_min;\n theta_max = fmin(theta_max, 0.5*PI);\n model->dtheta_max = (theta_max-theta_min)/PI*180;\n\n r_min = exp(model->r_min);\n r_max = model->fr_max * r_min;\n if(r_max > 0.5*rcloud_max_set) r_max = 0.5*rcloud_max_set;\n model->fr_max = r_max/r_min;\n \n gamma = model->gamma;\n alpha = model->alpha;\n lambda = model->lamda;\n \n k = model->k;\n xi = model->xi;\n\n Rv = exp(model->Rv);\n Rblr = exp(model->Rblr);\n if(Rblr < r_max) Rblr = r_max;\n model->Rblr = log(Rblr);\n inc = acos(model->inc);\n \n mbh = exp(model->mbh);\n\n sin_inc_cmp = cos(inc); //sin(PI/2.0 - inc);\n cos_inc_cmp = sin(inc); //cos(PI/2.0 - inc);\n\n for(i=0; iopn*PI/180.0);\n //Lopn = model->opn*PI/180.0;\n inc = acos(model->inc);\n beta = model->beta;\n F = model->F;\n mu = exp(model->mu);\n \n if(flag_type == 1) // 1D RM, no dynmaical parameters\n {\n mbh = 0.0;\n }\n else \n {\n mbh = exp(model->mbh);\n }\n Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days\n\n a = 1.0/beta/beta;\n s = mu/a;\n rin = mu*F + Rs;\n sig = (1.0-F)*s;\n\n sin_inc_cmp = cos(inc); //sin(PI/2.0 - inc);\n cos_inc_cmp = sin(inc); //cos(PI/2.0 - inc);\n \n for(i=0; ircloud_max_set || r 1000)\n {\n printf(\"# Error, too many tries in generating ridial location of clouds.\\n\");\n exit(0);\n }\n rnd = gsl_ran_gamma(gsl_r, a, 1.0);\n// r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu);\n r = rin + sig * rnd;\n nc++;\n }\n phi = 2.0*PI * gsl_rng_uniform(gsl_r);\n\n x = r * cos(phi); \n y = r * sin(phi);\n z = 0.0;\n\n /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z;\n yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z;\n zb = sin(Lthe) * x + cos(Lthe) * z;*/\n\n xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y;\n yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y;\n zb = sin(Lthe) * x;\n\n /* counter-rotate around y */\n //x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc);\n //y = yb;\n //z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc);\n x = xb * cos_inc_cmp + zb * sin_inc_cmp;\n y = yb;\n z =-xb * sin_inc_cmp + zb * cos_inc_cmp;\n\n weight = 1.0;\n clouds_weight[i] = weight;\n\n#ifndef SpecAstro\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_type == 1)\n {\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n }\n#else\n switch(flag_type) \n {\n case 1: /* 1D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\n\", x, y, z);\n }\n continue;\n break;\n \n case 2: /* 2D RM */\n dis = r - x;\n clouds_tau[i] = dis;\n break;\n\n case 3: /* SA */\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 4: /* 1D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n \n case 5: /* 2D RM + SA */\n dis = r - x;\n clouds_tau[i] = dis;\n\n clouds_alpha[i] = y;\n clouds_beta[i] = z;\n break;\n }\n \n#endif\n \n /* velocity \n * note that a cloud moves in its orbit plane, whose direction\n * is determined by the direction of its angular momentum.\n */\n Vkep = sqrt(mbh/r);\n \n for(j=0; j= C_Unit) // make sure that the velocity is smaller than speed of light\n V = 0.9999*C_Unit * (V>0.0?1.0:-1.0);\n\n g = (1.0 + V/C_Unit) / sqrt( (1.0 - V*V/C_Unit/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects\n V = (g-1.0)*C_Unit;\n \n clouds_vel[i*parset.n_vel_per_cloud + j] = V;\n\n if(flag_save && thistask==roottask)\n {\n if(i%(icr_cloud_save) == 0)\n fprintf(fcloud_out, \"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight);\n }\n }\n }\n\n return;\n}\n\nvoid restart_action_1d(int iflag)\n{\n /* at present, nothing needs to do */\n /*\n FILE *fp;\n char str[200];\n\n sprintf(str, \"%s/data/clouds_%04d.txt\", parset.file_dir, thistask);\n\n if(iflag == 0) // write\n fp = fopen(str, \"wb\");\n else // read\n fp = fopen(str, \"rb\");\n\n if(fp == NULL)\n {\n printf(\"# Cannot open file %s.\\n\", str);\n }\n\n if(iflag == 0)\n {\n printf(\"# Writing restart at task %d.\\n\", thistask);\n }\n else\n {\n printf(\"# Reading restart at task %d.\\n\", thistask);\n }\n fclose(fp);*/\n return;\n}\n\nvoid restart_action_2d(int iflag)\n{\n restart_action_1d(iflag);\n}\n\n#ifdef SpecAstro\nvoid restart_action_sa(int iflag)\n{\n restart_action_1d(iflag);\n}\n#endif", "meta": {"hexsha": "df162f205c21e3ab2255d189ef1ad2400d86c98e", "size": 58593, "ext": "c", "lang": "C", "max_stars_repo_path": "src/blr_models.c", "max_stars_repo_name": "LiyrAstroph/BRAINS", "max_stars_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-11-16T13:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T07:46:45.000Z", "max_issues_repo_path": "src/blr_models.c", "max_issues_repo_name": "LiyrAstroph/BRAINS", "max_issues_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/blr_models.c", "max_forks_repo_name": "LiyrAstroph/BRAINS", "max_forks_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-12T13:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-22T12:54:58.000Z", "avg_line_length": 26.560743427, "max_line_length": 134, "alphanum_fraction": 0.5269230113, "num_tokens": 20925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.4176245012171996}} {"text": "/***************************************************************************\n File : MyParser.h\n Project : QtiPlot\n --------------------------------------------------------------------\n Copyright : (C) 2006 by Ion Vasilief\n Email (use @ for *) : ion_vasilief*yahoo.fr\n Description : Parser class based on muParser\n\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, *\n * Boston, MA 02110-1301 USA *\n * *\n ***************************************************************************/\n#ifndef MYPARSER_H\n#define MYPARSER_H\n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace mu;\n\n/*!\\brief Mathematical parser class based on muParser.\n *\n * \\section future Future Plans\n * Eliminate in favour of Script/ScriptingEnv.\n * This will allow you to use e.g. Python's global variables and functions everywhere.\n * Before this happens, a cleaner and more generic solution for accessing the current ScriptingEnv\n * should be implemented (maybe by making it a property of Project; see ApplicationWindow).\n */\nclass MyParser : public Parser\n{\npublic:\n\tMyParser();\n\n\tstatic QStringList functionsList();\n\tstatic QString explainFunction(int index);\n\n\tstatic double bessel_J0(double x)\n\t\t{\n\t\treturn gsl_sf_bessel_J0 (x);\n\t\t}\n\n\tstatic double bessel_J1(double x)\n\t\t{\n\t\treturn gsl_sf_bessel_J1 (x);\n\t\t}\n\n\tstatic double bessel_Jn(double x, double n)\n\t\t{\n\t\treturn gsl_sf_bessel_Jn ((int)n, x);\n\t\t}\n\n\tstatic double bessel_Y0(double x)\n\t\t{\n\t\treturn gsl_sf_bessel_Y0 (x);\n\t\t}\n\n\tstatic double bessel_Y1(double x)\n\t\t{\n\t\treturn gsl_sf_bessel_Y1 (x);\n\t\t}\n\tstatic double bessel_Yn(double x, double n)\n\t\t{\n\t\treturn gsl_sf_bessel_Yn ((int)n, x);\n\t\t}\n\tstatic double beta(double a, double b)\n\t\t{\n\t\treturn gsl_sf_beta (a, b);\n\t\t}\n\tstatic double erf(double x)\n\t\t{\n\t\treturn gsl_sf_erf (x);\n\t\t}\n\tstatic double erfc(double x)\n\t\t{\n\t\treturn gsl_sf_erfc (x);\n\t\t}\n\tstatic double erfz(double x)\n\t\t{\n\t\treturn gsl_sf_erf_Z (x);\n\t\t}\n\tstatic double erfq(double x)\n\t\t{\n\t\treturn gsl_sf_erf_Q (x);\n\t\t}\n\tstatic double gamma(double x)\n\t\t{\n\t\treturn gsl_sf_gamma (x);\n\t\t}\n\tstatic double gammaln(double x)\n\t\t{\n\t\treturn gsl_sf_lngamma (x);\n\t\t}\n\tstatic double hazard(double x)\n\t\t{\n\t\treturn gsl_sf_hazard (x);\n\t\t}\n};\n\n#endif\n", "meta": {"hexsha": "b12e59975144b344bbfde40575818061c21924e4", "size": 3621, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/qtiplot/qtiplot/src/MyParser.h", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "thirdparty/qtiplot/qtiplot/src/MyParser.h", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "thirdparty/qtiplot/qtiplot/src/MyParser.h", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 30.175, "max_line_length": 98, "alphanum_fraction": 0.5280309307, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.41672787305889625}} {"text": "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n#include \n#include \n\n#include \n\n#ifdef __INTEL_COMPILER\n#include \n#else\n#include \n#define kmp_set_blocktime(k) \n#endif\n\nstatic inline int min (int a, int b) { return a < b ? a : b; }\nstatic inline int max (int a, int b) { return a < b ? b : a; }\n\nstatic inline int square(int x) { return x*x; }\n\nstatic void max_filter_1d(const float *vals, float *out_vals, int32_t *I, \n int s, int step, int n, float a, float b) {\n int i;\n for (i = 0; i < n; i++) {\n float max_val = -INFINITY;\n int argmax = 0;\n int first = max(0, i-s);\n int last = min(n-1, i+s);\n int j;\n for (j = first; j <= last; j++) {\n float val = *(vals + j*step) - a*square(i-j) - b*(i-j);\n if (val > max_val) {\n max_val = val;\n argmax = j;\n }\n }\n *(out_vals + i*step) = max_val;\n *(I + i*step) = argmax;\n }\n}\n\nPyObject * deformation_cost (PyArrayObject * pydata, float ax, float bx, float ay, float by, int s) {\n npy_intp * dims = PyArray_DIMS(pydata);\n npy_intp * stride = PyArray_STRIDES(pydata);\n\n if (PyArray_NDIM(pydata) != 2) {\n PyErr_SetString(PyExc_TypeError, \"data must be 2 dimensional.\");\n return NULL;\n }\n\n if (PyArray_DESCR(pydata)->type_num != NPY_FLOAT) {\n PyErr_SetString(PyExc_TypeError, \"data must be single precision floating point.\");\n return NULL;\n }\n\n if (stride[0] != dims[1]*sizeof(float)) {\n PyErr_SetString(PyExc_TypeError, \"Stride[0] must be sizeof(float).\");\n return NULL;\n }\n\n if (stride[1] != sizeof(float)) {\n PyErr_SetString(PyExc_TypeError, \"Stride[1] must be Dims[0]*sizeof(float).\");\n return NULL;\n }\n \n PyArrayObject * pydeformed = (PyArrayObject*)PyArray_SimpleNew((npy_intp)2, dims, NPY_FLOAT);\n PyArrayObject * pyIx = (PyArrayObject*)PyArray_SimpleNew((npy_intp)2, dims, NPY_INT32);\n PyArrayObject * pyIy = (PyArrayObject*)PyArray_SimpleNew((npy_intp)2, dims, NPY_INT32);\n\n float *tmpM = (float *)calloc(dims[0]*dims[1], sizeof(float));\n int32_t *tmpIx = (int32_t*)calloc(dims[0]*dims[1], sizeof(int32_t));\n int32_t *tmpIy = (int32_t*)calloc(dims[0]*dims[1], sizeof(int32_t));\n\n int x, y;\n\n for (y = 0; y < dims[0]; y++)\n max_filter_1d((float*)PyArray_GETPTR2(pydata, y, 0), tmpM+y*dims[1], tmpIx+y*dims[1], s, 1, dims[1], ax, bx);\n\n for (x = 0; x < dims[1]; x++)\n max_filter_1d(tmpM+x, (float*)PyArray_GETPTR2(pydeformed, 0, x), tmpIy+x, s, dims[1], dims[0], ay, by);\n\n for (x = 0; x < dims[1]; ++x) {\n for (y = 0; y < dims[0]; ++y) {\n *(int32_t*)PyArray_GETPTR2(pyIy, y, x) = tmpIy[y*dims[1]+x];\n *(int32_t*)PyArray_GETPTR2(pyIx, y, x) = tmpIx[tmpIy[y*dims[1]+x]*dims[1]+x];\n }\n }\n\n free(tmpM);\n free(tmpIx);\n free(tmpIy);\n\n return Py_BuildValue(\"NNN\", pydeformed, pyIx, pyIy);\n}\n\nPyObject * filter_image (PyArrayObject * pyfeatures, PyArrayObject * pyfilter, float bias, int width, int height) {\n npy_intp * features_dims = PyArray_DIMS(pyfeatures);\n npy_intp * filter_dims = PyArray_DIMS(pyfilter);\n int a, b, l;\n PyArrayObject * pyfiltered = NULL;\n npy_intp * features_stride = PyArray_STRIDES(pyfeatures);\n npy_intp * filtered_stride = NULL;\n npy_intp filtered_dims[2] = {0, 0};\n int tight_width;\n int tight_height;\n\n if (PyArray_NDIM(pyfeatures) != 3) {\n PyErr_SetString(PyExc_TypeError, \"Features must be 3 dimensional.\");\n return NULL;\n }\n\n if (PyArray_NDIM(pyfilter) != 3) {\n PyErr_SetString(PyExc_TypeError, \"Filter must be 3 dimensional.\");\n return NULL;\n }\n\n if (PyArray_DESCR(pyfeatures)->type_num != NPY_FLOAT) {\n PyErr_SetString(PyExc_TypeError, \"Features must be single precision floating point.\");\n return NULL;\n }\n\n if (PyArray_DESCR(pyfilter)->type_num != NPY_FLOAT) {\n PyErr_SetString(PyExc_TypeError, \"Filter must be a single precision floating point.\");\n return NULL;\n }\n\n if (features_dims[2] != 32) {\n PyErr_SetString(PyExc_TypeError, \"features' feature dimsionality should be 32.\");\n return NULL;\n }\n\n if (filter_dims[2] != 32) {\n PyErr_SetString(PyExc_TypeError, \"filters' feature dimensionality should be 32.\");\n return NULL;\n }\n\n tight_height = features_dims[0]-filter_dims[0]+1;\n tight_width = features_dims[1]-filter_dims[1]+1;\n\n filtered_dims[0] = height ? height : tight_height;\n filtered_dims[1] = width ? width : tight_width;\n\n if (filtered_dims[0] < 1 || filtered_dims[1] < 1) {\n PyErr_SetString(PyExc_TypeError, \"Input features are too small for filter.\");\n return NULL;\n }\n\n #pragma omp critical\n pyfiltered = (PyArrayObject*)PyArray_SimpleNew((npy_intp)2, filtered_dims, NPY_FLOAT);\n\n filtered_stride = PyArray_STRIDES(pyfiltered);\n\n /* zero out array */\n for (a = 0; a < tight_height; ++a) {\n for (b = 0; b < tight_width; ++b) {\n *(float*)PyArray_GETPTR2(pyfiltered, a, b) = -bias;\n }\n }\n\n /* iterate over filter which should be tiny compared to the image */\n int i;\n int stride_src = features_stride[1]/sizeof(float);\n int stride_dst = filtered_stride[1]/sizeof(float);\n for (i = 0; i < filter_dims[0]; ++i) {\n int j;\n for (j = 0; j < filter_dims[1]; ++j) {\n int k;\n for (k = 0; k < tight_height; ++k) {\n float * out = (float*)PyArray_GETPTR2(pyfiltered, k, 0);\n /* for each layer */\n for (l = 0; l < 32; ++l) {\n float weight = *(float*)PyArray_GETPTR3(pyfilter, i, j, l);\n float * in = (float*)PyArray_GETPTR3(pyfeatures, i+k, j, l);\n cblas_saxpy(tight_width, weight, in, stride_src, out, stride_dst);\n }\n }\n }\n }\n\n for (a = tight_height; a < filtered_dims[0]; ++a) {\n for (b = 0; b < filtered_dims[1]; ++b) {\n *(float*)PyArray_GETPTR2(pyfiltered, a, b) = -INFINITY;\n }\n }\n\n for (a = 0; a < tight_height; ++a) {\n for (b = tight_width; b < filtered_dims[1]; ++b) {\n *(float*)PyArray_GETPTR2(pyfiltered, a, b) = -INFINITY;\n }\n }\n\n return Py_BuildValue(\"N\", pyfiltered);\n}\n\nstatic PyObject * DeformationCost(PyObject * self, PyObject * args)\n{\n PyArrayObject * pydata;\n float ax = 0.0f, bx = 0.0f, ay = 0.0f, by = 0.0f;\n int s = 0;\n if (!PyArg_ParseTuple(args, \"O!ffffi\", &PyArray_Type, &pydata, &ax, &bx, &ay, &by, &s)) \n return NULL;\n return deformation_cost(pydata, ax, bx, ay, by, s);\n}\n\nstatic PyObject * FilterImage(PyObject * self, PyObject * args)\n{\n PyArrayObject * pyfeatures;\n PyArrayObject * pyfilter;\n float bias = 0.0f;\n int width = 0;\n int height = 0;\n if (!PyArg_ParseTuple(args, \"O!O!|fii\", &PyArray_Type, &pyfeatures, &PyArray_Type, &pyfilter, &bias, &width, &height)) \n return NULL;\n return filter_image(pyfeatures, pyfilter, bias, width, height);\n}\n\nstatic PyObject * FilterImages(PyObject * self, PyObject * args)\n{\n PyObject * pyfeatures_list;\n PyObject * pydims_list = NULL;\n PyArrayObject * pyfilter;\n float bias = 0.0f;\n int numfilters;\n int numdims = 0;\n int i;\n PyObject ** objs = NULL;\n PyObject ** results = NULL;\n PyObject * pyresults_list;\n if (!PyArg_ParseTuple(args, \"O!O!|fO!\", &PyList_Type, &pyfeatures_list, &PyArray_Type, &pyfilter, &bias, &PyList_Type, &pydims_list)) \n return NULL;\n\n numfilters = PyList_Size(pyfeatures_list);\n \n if (pydims_list) {\n numdims = PyList_Size(pydims_list);\n }\n\n if (numdims && numdims != numfilters) {\n PyErr_SetString(PyExc_TypeError, \"If pad dims are specified, then it must be the same length as the features list.\");\n return NULL;\n }\n\n objs = (PyObject**)calloc(numfilters, sizeof(PyObject*));\n int* widths = (int*)calloc(numfilters, sizeof(int));\n int* heights = (int*)calloc(numfilters, sizeof(int));\n results = (PyObject**)calloc(numfilters, sizeof(PyObject*));\n\n for (i = 0; i < numfilters; ++i) {\n objs[i] = PyList_GetItem(pyfeatures_list, i);\n if (!PyArray_Check(objs[i])) {\n free(objs);\n free(widths);\n free(heights);\n free(results);\n PyErr_SetString(PyExc_TypeError, \"Must contain a list of numpy arrays.\");\n return NULL;\n }\n\n if (pydims_list) {\n PyObject * dims = PyList_GetItem(pydims_list, i);\n if (!PyTuple_Check(dims) || 2 != PyTuple_Size(dims)) {\n free(objs);\n free(widths);\n free(heights);\n free(results);\n PyErr_SetString(PyExc_TypeError, \"Must contain a list of tuples.\");\n return NULL;\n }\n\n heights[i] = PyInt_AsLong(PyTuple_GetItem(dims, 0));\n widths[i] = PyInt_AsLong(PyTuple_GetItem(dims, 1));\n } else {\n widths[i] = 0;\n heights[i] = 0;\n }\n }\n\n kmp_set_blocktime(0);\n #pragma omp parallel for schedule(dynamic) \n for (i = 0; i < numfilters; ++i) { \n PyArrayObject * pyfeatures = (PyArrayObject*)objs[i];\n results[i] = filter_image(pyfeatures, pyfilter, bias, widths[i], heights[i]);\n }\n\n free(objs);\n free(widths);\n free(heights);\n\n pyresults_list = PyList_New(numfilters);\n\n for (i = 0; i < numfilters; ++i) {\n PyList_SetItem(pyresults_list, i, results[i]);\n }\n\n free(results);\n\n return Py_BuildValue(\"N\", pyresults_list); \n}\n\n#if PY_MAJOR_VERSION >= 3\nstatic struct PyModuleDef moduledef = {\n PyModuleDef_HEAD_INIT,\n \"_detection\",\n \"Native convolution detection routine.\",\n -1,\n NULL,\n NULL,\n NULL,\n NULL,\n NULL\n};\n#endif\n\n#if PY_MAJOR_VERSION < 3\nstatic PyMethodDef _detection_methods[] = {\n {\"FilterImage\", FilterImage, METH_VARARGS, \"Compute a 2D cross correlation between a filter and image features. Optionally add bias term.\"},\n {\"FilterImages\", FilterImages, METH_VARARGS, \"Compute a 2D cross correlation between a filter and several image features in parallel. Optionally add bias term.\"},\n {\"DeformationCost\", DeformationCost, METH_VARARGS, \"Compute a fast bounded distance transform for the deformation cost.\"},\n {NULL}\n};\n#endif\n\n#if PY_MAJOR_VERSION >= 3\nPyMODINIT_FUNC\nPyInit__detection(void)\n#else\nPyMODINIT_FUNC\ninit_detection(void)\n#endif\n{\n import_array();\n\n#if PY_MAJOR_VERSION >= 3\n PyObject *m = PyModule_Create(&moduledef);\n#else\n Py_InitModule3(\"_detection\", _detection_methods, \"Native convolution detection routine.\");\n#endif\n\n#if PY_MAJOR_VERSION >= 3\n return m;\n#endif\n}\n", "meta": {"hexsha": "a73ea5929985acf1ef27d050a9c23487f5fe89d4", "size": 10724, "ext": "c", "lang": "C", "max_stars_repo_path": "src/pydro/_detection.c", "max_stars_repo_name": "caomw/pydro", "max_stars_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T23:41:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-24T01:25:25.000Z", "max_issues_repo_path": "src/pydro/_detection.c", "max_issues_repo_name": "caomw/pydro", "max_issues_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-06T07:54:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-06T07:54:15.000Z", "max_forks_repo_path": "src/pydro/_detection.c", "max_forks_repo_name": "kmatzen/pydro", "max_forks_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-08-20T14:21:54.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-30T07:30:11.000Z", "avg_line_length": 31.4486803519, "max_line_length": 167, "alphanum_fraction": 0.6133905259, "num_tokens": 3144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4165956693713733}} {"text": "#ifndef _MU_NSQ_\n#define _MU_NSQ_\n\n#include \n#include \n#include \n#include \n#include \"exCross.h\"\n\nnamespace musquids {\nusing nusquids::nuSQUIDS;\nusing nusquids::marray;\n/// \\brief This class implements muon energy loss into nuSQuIDS.\nclass muSQUIDS: public nuSQUIDS {\n private:\n std::vector inv_lambda;\n marray dScalardE;\n /// The following variables are to evaluate the derivative of the scalar flux\n std::shared_ptr scalar_spline;\n std::shared_ptr scalar_spline_acc;\n std::vector tmp_scalar_state;\n protected:\n /// \\brief Here we will calculate the muon flux derivative\n void AddToPreDerive(double x){\n for(size_t si=0; si10Gev\n double RadDensH=4.405e5; // gr/cm^2\n // current_density in gr/cm^3\n // coeffcients in MeV/cm^2\n return (((-1.9-0.08*log(Emuon/params.muon_mass))-(Emuon/params.MeV)/RadDensH)*current_density)*(params.MeV/params.cm);\n }\n double Fmue(double Emuon, double Enu) const {\n // Fits to muon decay spectrum including spin\n double z = Enu/Emuon;\n 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;\n }\n double Fmumu(double Emuon, double Enu) const {\n // Fits to muon decay spectrum including spin\n double z = Enu/Emuon;\n return (-0.24794224*pow(z,4.)+4.51300659*pow(z,3.)-6.2556965*z*z-0.03647084*z+2.02480429)/Emuon;\n }\n double lambda(double Emuon) const {\n return Emuon*params.muon_lifetime/params.muon_mass;\n }\n protected:\n // These scalar functions will manage the muon decay and energy loss\n double GammaScalar(unsigned int ei,unsigned int index_scalar) const {\n double muon_decay_term=inv_lambda[ei];\n return nuSQUIDS::GammaScalar(ei,index_scalar) + muon_decay_term;\n }\n double InteractionsScalar(unsigned int ei,unsigned int index_scalar) const {\n double muon_energy_loss_terms=EnergyLoss(E_range[ei])*dScalardE[index_scalar][ei];\n return nuSQUIDS::InteractionsScalar(ei,index_scalar) + muon_energy_loss_terms;\n }\n // This rho function will add the neutrinos from muon decay\n squids::SU_vector InteractionsRho(unsigned int ei,unsigned int index_rho) const {\n squids::SU_vector from_muon_decay_terms(nsun);\n double muon_decay_to_muon_integral = 0.;\n double muon_decay_to_e_integral = 0.;\n unsigned int other_index_rho = (index_rho == 0) ? 1 : 0;\n for(unsigned int em = ei+1; em < ne; em++){ // loop in the tau neutrino energies\n muon_decay_to_muon_integral += state[em].scalar[index_rho]*Fmumu(E_range[em],E_range[ei])*inv_lambda[em]*delE[em-1];\n muon_decay_to_e_integral += state[em].scalar[other_index_rho]*Fmue(E_range[em],E_range[ei])*inv_lambda[em]*delE[em-1];\n }\n from_muon_decay_terms += evol_b1_proj[index_rho][1][ei]*muon_decay_to_muon_integral;\n from_muon_decay_terms += evol_b1_proj[index_rho][0][ei]*muon_decay_to_e_integral;\n return nuSQUIDS::InteractionsRho(ei,index_rho) + from_muon_decay_terms;\n }\n public:\n muSQUIDS(){}\n muSQUIDS(marray E_range,\n int numneu=3, nusquids::NeutrinoType NT=nusquids::both,bool iinteraction=true):\n nuSQUIDS(E_range,numneu,NT,iinteraction,std::make_shared()),\n scalar_spline(gsl_spline_alloc(gsl_interp_cspline,E_range.size()),[](gsl_spline* t){ gsl_spline_free(t);}),\n scalar_spline_acc(gsl_interp_accel_alloc(),[](gsl_interp_accel* t){ gsl_interp_accel_free(t);})\n {\n // resetting squids nodes to the right scalar size\n ini(ne,numneu,nrhos,2,Get_t());\n // initializing the muon decay lenght\n inv_lambda.resize(ne);\n for(unsigned int ei=0; ei{nscalars,ne});\n std::fill(dScalardE.begin(),dScalardE.end(),0);\n // initializing the scalar temporary state\n tmp_scalar_state.resize(ne);\n std::fill(tmp_scalar_state.begin(),tmp_scalar_state.end(),0);\n }\n\n void Set_initial_state(const marray& muon_flux,const marray& neutrino_state,nusquids::Basis basis)\n {\n nuSQUIDS::Set_initial_state(neutrino_state,basis);\n\n for(unsigned int ie = 0; ie < ne; ie++){\n for(unsigned int ir = 0; ir < nscalars; ir++){\n state[ie].scalar[ir] = muon_flux[ie][ir];\n }\n }\n }\n\n double GetMuonFlux(unsigned int ie, unsigned int irho){\n return state[ie].scalar[irho];\n }\n};\n\n} // close musquids namespace\n\n#endif\n", "meta": {"hexsha": "5dc2a6de9462507d4c273b1a535198508fab685e", "size": 5391, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/muSQuIDS.h", "max_stars_repo_name": "arguelles/muSQuIDS", "max_stars_repo_head_hexsha": "9b154d29618c275ee6ea78810ab1f6576cfd8fe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/muSQuIDS.h", "max_issues_repo_name": "arguelles/muSQuIDS", "max_issues_repo_head_hexsha": "9b154d29618c275ee6ea78810ab1f6576cfd8fe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/muSQuIDS.h", "max_forks_repo_name": "arguelles/muSQuIDS", "max_forks_repo_head_hexsha": "9b154d29618c275ee6ea78810ab1f6576cfd8fe6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4758064516, "max_line_length": 126, "alphanum_fraction": 0.6911519199, "num_tokens": 1582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.4159944067768866}} {"text": "#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \"gsl_utils.h\"\n\n#define ROUND(x) (int)(((x) >= 0) ? ((x) + 0.5) : ((x) - 0.5))\n\n\nvoid dfs(VFloat** Dfs,gsl_matrix_float* pinvX,gsl_matrix_float* X,gsl_matrix_float* con,int numlags) \n{\n int numcon = 1;\n int n = X->size2;\n /* these vals represent the matlab interval 2:n */\n int k1 = 1;\n int k2 = n-1;\n int i;\n \n \n /* X^T */\n gsl_matrix_float* transX = gsl_matrix_float_alloc(X->size2, X->size1);\n gsl_matrix_float_transpose_memcpy(transX,X);\n \n gsl_vector_float* CorX2 = gsl_vector_float_alloc(numcon);\n gsl_vector_float_set_zero(CorX2);\n \n /* cpinvX=contrast^T*pinvX */\n gsl_matrix_float* cpinvX = fmat_x_mat(con, pinvX, NULL);\n \n /* CovX0=cpinvX*cpinvX' */\n gsl_matrix_float* CovX0 = fmat_x_matT(cpinvX,cpinvX,NULL);\n \n if(numlags == 1) {\n /* CovX1=cpinvX(:,k1)*cpinvX(:,k1-1)' */\n gsl_matrix_float_view sub1 = \n gsl_matrix_float_submatrix(cpinvX,0,k1,cpinvX->size1,k2);\n gsl_matrix_float_view sub2 = \n gsl_matrix_float_submatrix(cpinvX,0,k1-1,cpinvX->size1,k2); \n gsl_matrix_float* CovX1 = fmat_x_matT(&sub1.matrix, &sub2.matrix, NULL);\n \n gsl_vector_float_view CovX1diag = gsl_matrix_float_diagonal(CovX1);\n gsl_vector_float_view CovX0diag = gsl_matrix_float_diagonal(CovX0);\n \n gsl_vector_float_div (&CovX1diag.vector, &CovX0diag.vector);\n gsl_vector_float_mul (&CovX1diag.vector, &CovX1diag.vector);\n\n gsl_vector_float_memcpy (CorX2, &CovX1diag.vector);\n }\n else {\n int lag;\n gsl_matrix_float_view sub1, sub2;\n gsl_matrix_float* CovX1 = gsl_matrix_float_alloc(cpinvX->size1,cpinvX->size1);\n for(lag=0;lagsize1,k2-lag);\n sub2 = gsl_matrix_float_submatrix(cpinvX,0,lag+1,cpinvX->size1,k2-lag);\n fmat_x_matT(&sub1.matrix, &sub2.matrix,CovX1);\n \n gsl_vector_float_view CovX1diag = gsl_matrix_float_diagonal(CovX1);\n gsl_vector_float_view CovX0diag = gsl_matrix_float_diagonal(CovX0);\n\n gsl_vector_float_div (&CovX1diag.vector, &CovX0diag.vector);\n gsl_vector_float_mul (&CovX1diag.vector, &CovX1diag.vector);\n\n gsl_vector_float_add(CorX2,&CovX1diag.vector);\n }\n gsl_matrix_float_free(CovX1);\n }\n\n float dfresid = n-rank(transX);\n float dfmin = dfresid;\n\n for (i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * This module computes the eigenvalues of a real nonsymmetric\n * matrix, using the double shift Francis method.\n *\n * See the references in francis.c.\n *\n * This module gets the matrix ready by balancing it and\n * reducing it to Hessenberg form before passing it to the\n * francis module.\n */\n\n/*\ngsl_eigen_nonsymm_alloc()\n\nAllocate a workspace for solving the nonsymmetric eigenvalue problem.\nThe size of this workspace is O(2n)\n\nInputs: n - size of matrix\n\nReturn: pointer to workspace\n*/\n\ngsl_eigen_nonsymm_workspace *\ngsl_eigen_nonsymm_alloc(const size_t n)\n{\n gsl_eigen_nonsymm_workspace *w;\n\n if (n == 0)\n {\n GSL_ERROR_NULL (\"matrix dimension must be positive integer\",\n GSL_EINVAL);\n }\n\n w = (gsl_eigen_nonsymm_workspace *)\n malloc (sizeof (gsl_eigen_nonsymm_workspace));\n\n if (w == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workspace\", GSL_ENOMEM);\n }\n\n w->size = n;\n w->Z = NULL;\n w->do_balance = 0;\n\n w->diag = gsl_vector_alloc(n);\n\n if (w->diag == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for balancing vector\", GSL_ENOMEM);\n }\n\n w->tau = gsl_vector_alloc(n);\n\n if (w->tau == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for hessenberg coefficients\", GSL_ENOMEM);\n }\n\n w->francis_workspace_p = gsl_eigen_francis_alloc();\n\n if (w->francis_workspace_p == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for francis workspace\", GSL_ENOMEM);\n }\n\n return (w);\n} /* gsl_eigen_nonsymm_alloc() */\n\n/*\ngsl_eigen_nonsymm_free()\n Free workspace w\n*/\n\nvoid\ngsl_eigen_nonsymm_free (gsl_eigen_nonsymm_workspace * w)\n{\n gsl_vector_free(w->tau);\n\n gsl_vector_free(w->diag);\n\n gsl_eigen_francis_free(w->francis_workspace_p);\n\n free(w);\n} /* gsl_eigen_nonsymm_free() */\n\n/*\ngsl_eigen_nonsymm_params()\n Set some parameters which define how we solve the eigenvalue\nproblem.\n\nInputs: compute_t - 1 if we want to compute T, 0 if not\n balance - 1 if we want to balance the matrix, 0 if not\n w - nonsymm workspace\n*/\n\nvoid\ngsl_eigen_nonsymm_params (const int compute_t, const int balance,\n gsl_eigen_nonsymm_workspace *w)\n{\n gsl_eigen_francis_T(compute_t, w->francis_workspace_p);\n w->do_balance = balance;\n} /* gsl_eigen_nonsymm_params() */\n\n/*\ngsl_eigen_nonsymm()\n\nSolve the nonsymmetric eigenvalue problem\n\nA x = \\lambda x\n\nfor the eigenvalues \\lambda using the Francis method.\n\nHere we compute the real Schur form\n\nT = Z^t A Z\n\nwith the diagonal blocks of T giving us the eigenvalues.\nZ is a matrix of Schur vectors which is not computed by\nthis algorithm. See gsl_eigen_nonsymm_Z().\n\nInputs: A - general real matrix\n eval - where to store eigenvalues\n w - workspace\n\nReturn: success or error\n\nNotes: If T is computed, it is stored in A on output. Otherwise\n the diagonal of A contains the 1-by-1 and 2-by-2 eigenvalue\n blocks.\n*/\n\nint\ngsl_eigen_nonsymm (gsl_matrix * A, gsl_vector_complex * eval,\n gsl_eigen_nonsymm_workspace * w)\n{\n const size_t N = A->size1;\n\n /* check matrix and vector sizes */\n\n if (N != A->size2)\n {\n GSL_ERROR (\"matrix must be square to compute eigenvalues\", GSL_ENOTSQR);\n }\n else if (eval->size != N)\n {\n GSL_ERROR (\"eigenvalue vector must match matrix size\", GSL_EBADLEN);\n }\n else\n {\n int s;\n\n if (w->do_balance)\n {\n /* balance the matrix */\n gsl_linalg_balance_matrix(A, w->diag);\n }\n\n /* compute the Hessenberg reduction of A */\n gsl_linalg_hessenberg(A, w->tau);\n\n if (w->Z)\n {\n /*\n * initialize the matrix Z to U, which is the matrix used\n * to construct the Hessenberg reduction.\n */\n\n /* compute U and store it in Z */\n gsl_linalg_hessenberg_unpack(A, w->tau, w->Z);\n\n /* find the eigenvalues and Schur vectors */\n s = gsl_eigen_francis_Z(A, eval, w->Z, w->francis_workspace_p);\n\n if (w->do_balance)\n {\n /*\n * The Schur vectors in Z are the vectors for the balanced\n * matrix. We now must undo the balancing to get the\n * vectors for the original matrix A.\n */\n gsl_linalg_balance_accum(w->Z, w->diag);\n }\n }\n else\n {\n /* find the eigenvalues only */\n s = gsl_eigen_francis(A, eval, w->francis_workspace_p);\n }\n\n w->n_evals = w->francis_workspace_p->n_evals;\n\n return s;\n }\n} /* gsl_eigen_nonsymm() */\n\n/*\ngsl_eigen_nonsymm_Z()\n\nSolve the nonsymmetric eigenvalue problem\n\nA x = \\lambda x\n\nfor the eigenvalues \\lambda.\n\nHere we compute the real Schur form\n\nT = Z^t A Z\n\nwith the diagonal blocks of T giving us the eigenvalues.\nZ is the matrix of Schur vectors.\n\nInputs: A - general real matrix\n eval - where to store eigenvalues\n Z - where to store Schur vectors\n w - workspace\n\nReturn: success or error\n\nNotes: If T is computed, it is stored in A on output. Otherwise\n the diagonal of A contains the 1-by-1 and 2-by-2 eigenvalue\n blocks.\n*/\n\nint\ngsl_eigen_nonsymm_Z (gsl_matrix * A, gsl_vector_complex * eval,\n gsl_matrix * Z, gsl_eigen_nonsymm_workspace * w)\n{\n /* check matrix and vector sizes */\n\n if (A->size1 != A->size2)\n {\n GSL_ERROR (\"matrix must be square to compute eigenvalues\", GSL_ENOTSQR);\n }\n else if (eval->size != A->size1)\n {\n GSL_ERROR (\"eigenvalue vector must match matrix size\", GSL_EBADLEN);\n }\n else if ((Z->size1 != Z->size2) || (Z->size1 != A->size1))\n {\n GSL_ERROR (\"Z matrix has wrong dimensions\", GSL_EBADLEN);\n }\n else\n {\n int s;\n\n w->Z = Z;\n\n s = gsl_eigen_nonsymm(A, eval, w);\n\n w->Z = NULL;\n\n return s;\n }\n} /* gsl_eigen_nonsymm_Z() */\n", "meta": {"hexsha": "de9088a4588bf1caae3de3267af914d51bf6a8dd", "size": 6940, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/eigen/nonsymm.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/eigen/nonsymm.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/eigen/nonsymm.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 24.2657342657, "max_line_length": 90, "alphanum_fraction": 0.6479827089, "num_tokens": 1868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4157156554123718}} {"text": "/*\n * halo.h\n *\n * Created on: Oct 23, 2012\n * Author: cgiocoli\n *\n * This class implement the non-linear power spectrum using the Halo Model\n */\n\n#ifndef POWERCDMHM_H_\n#define POWERCDMHM_H_\n#include \n#include \n#include \n#include \n\n#ifdef ENABLE_GSL\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n/** \n * \\brief Class for calculating the non-linear power spectrum using ****** Halo Model.\n * To use this class you must enable GSL.\n */\nclass POWERCDMHM{\n public:\n POWERCDMHM(COSMOLOGY *co, double redshift, double minHalomass, double sigma=0.25,int cmRelation=0,double slope=-0.1);\n \n double nonlinpowerCDMHM(double k);\n double nonlinpowerCDMHM1Halo(double k);\n double nonlinpowerCDMHM2Halo(double k);\n double nonlinKAPPApowerCDMHM(double l, double zs);\n double nonlinKAPPApowerCDMHM1Halo(double l, double zs);\n double nonlinKAPPApowerCDMHM2Halo(double l, double zs);\n double linKAPPApowerCDMHM(double l, double zs);\n double nonlinfitKAPPApowerCDMHM(double l, double zs);\n virtual ~POWERCDMHM ();\n \n protected:\n gsl_function intPk1,intPk2;\n double Pklin,Pk1,Pk2;\n double Pk20;\n double weight (double z1, double z2);\n double weight (double z0);\n\n struct weightfnc{\n std::vector ai;\n std::vector wi;\n };\n weightfnc wgf; // weight function\n void Initweight(double zs);\n private:\n float *xf,*wf;\n};\n#endif\n\n\n#endif /* POWERCDMHM_H_ */\n\n\n\n\n", "meta": {"hexsha": "55e5c7b2e9ffbefc5b243dd837cd16fdcebdddab", "size": 1549, "ext": "h", "lang": "C", "max_stars_repo_path": "include/powerCDMHM.h", "max_stars_repo_name": "glenco/CosmoLib", "max_stars_repo_head_hexsha": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/powerCDMHM.h", "max_issues_repo_name": "glenco/CosmoLib", "max_issues_repo_head_hexsha": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-09-29T10:22:17.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-29T10:27:21.000Z", "max_forks_repo_path": "include/powerCDMHM.h", "max_forks_repo_name": "glenco/CosmoLib", "max_forks_repo_head_hexsha": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7794117647, "max_line_length": 119, "alphanum_fraction": 0.7165913493, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4154891387487168}} {"text": "/*\n * neuro.c\n *\n * Created on: Oct 9, 2019\n * Author: alexey\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"neuro.h\"\n\ntypedef struct _neuro_skeleton {\n\tint input_l;\n\tint output_l;\n\tint hidden_l;\n\tint number_of_hidden;\n\tdouble alpha;\n\tgsl_matrix *input_m;\n\tgsl_matrix *output_m;\n\tgsl_matrix **hidden_m;\n\tgsl_matrix **dropuot;\n\tgsl_matrix **layers;\n\tgsl_matrix **layers_delta;\n\tgsl_matrix *temp;\n\tgsl_matrix *train;\n\tgsl_matrix *error;\n\tint layers_numb;\n\tactivation activ;\n\tactivation *activ_l;\n} neuro_skeleton;\n\nconst gsl_rng_type * T;\ngsl_rng * r;\n\nextern unsigned long int gsl_rng_default_seed;\n\n#define CLEAN_BLOB() bayrepo_clean_neuro((void *) blob); \\\n\t\treturn NULL\n#define CLEAN_IF_NULL(x) if (!blob->x) { \\\n\t\tCLEAN_BLOB(); \\\n\t}\n\n#define ISDEBUGINFO_BEG() if (getenv(\"MATRIXD\") && !strcmp(getenv(\"MATRIXD\"),\"1\")) {\n#define ISDEBUGINFO_END() }\n#define DEBUGINFO(A, B, C) ISDEBUGINFO_BEG()\\\n\t\tbayrepo_print_matrix(A, B, C); \\\n\t\tISDEBUGINFO_END()\n\n#define MAX_LAYER_NAME_LEN 1024\n#define MAX_BUFFER_LEN 4096\n\nstatic void bayrepo_print_matrix(gsl_matrix *a, const char *matrix_name,\n\t\tint index_matrix) {\n\tint index, jndex;\n\tif (index_matrix >= 0) {\n\t\tprintf(\"Matrix %s[%d]:\\n\", matrix_name, index_matrix);\n\t} else {\n\t\tprintf(\"Matrix %s:\\n\", matrix_name);\n\t}\n\tfor (index = 0; index < a->size1; index++) {\n\t\tprintf(\"==\");\n\t\tfor (jndex = 0; jndex < a->size2; jndex++) {\n\t\t\tprintf(\"%.3f \", gsl_matrix_get(a, index, jndex));\n\t\t}\n\t\tprintf(\"==\\n\");\n\t}\n}\n\nstatic void bayrepo_layers_clean(void *blob) {\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tif (data->layers) {\n\t\t\tint index = 0;\n\t\t\tfor (index = 0; index < data->layers_numb; index++) {\n\t\t\t\tif (data->layers[index])\n\t\t\t\t\tgsl_matrix_free(data->layers[index]);\n\t\t\t}\n\t\t\tfree(data->layers);\n\t\t\tdata->layers = NULL;\n\t\t}\n\t\tif (data->layers_delta) {\n\t\t\tint index = 0;\n\t\t\tfor (index = 0; index < data->layers_numb; index++) {\n\t\t\t\tif (data->layers_delta[index])\n\t\t\t\t\tgsl_matrix_free(data->layers_delta[index]);\n\t\t\t}\n\t\t\tdata->layers_numb = 0;\n\t\t\tfree(data->layers_delta);\n\t\t\tdata->layers_delta = NULL;\n\t\t}\n\t\tdata->layers_numb = 0;\n\t}\n}\n\nvoid bayrepo_clean_neuro(void *blob) {\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tif (data->input_m) {\n\t\t\tgsl_matrix_free(data->input_m);\n\t\t\tdata->input_m = NULL;\n\t\t}\n\t\tif (data->output_m) {\n\t\t\tgsl_matrix_free(data->output_m);\n\t\t\tdata->output_m = NULL;\n\t\t}\n\t\tif (data->train) {\n\t\t\tgsl_matrix_free(data->train);\n\t\t\tdata->train = NULL;\n\t\t}\n\t\tif (data->temp) {\n\t\t\tgsl_matrix_free(data->temp);\n\t\t\tdata->temp = NULL;\n\t\t}\n\t\tif (data->error) {\n\t\t\tgsl_matrix_free(data->error);\n\t\t\tdata->error = NULL;\n\t\t}\n\t\tif (data->activ_l) {\n\t\t\tfree(data->activ_l);\n\t\t\tdata->activ_l = NULL;\n\t\t}\n\t\tif (data->number_of_hidden > 0 && data->hidden_m) {\n\t\t\tint i;\n\t\t\tfor (i = 0; i < data->number_of_hidden; i++) {\n\t\t\t\tif (data->hidden_m[i]) {\n\t\t\t\t\tgsl_matrix_free(data->hidden_m[i]);\n\t\t\t\t\tdata->hidden_m[i] = NULL;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfree(data->hidden_m);\n\t\t}\n\t\tif (data->number_of_hidden > 0 && data->dropuot) {\n\t\t\tint i;\n\t\t\tfor (i = 0; i < data->number_of_hidden; i++) {\n\t\t\t\tif (data->dropuot[i]) {\n\t\t\t\t\tgsl_matrix_free(data->dropuot[i]);\n\t\t\t\t\tdata->dropuot[i] = NULL;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfree(data->dropuot);\n\t\t}\n\t\tbayrepo_layers_clean(blob);\n\t\tfree(data);\n\t}\n\tif (r) {\n\t\tgsl_rng_free(r);\n\t\tr = NULL;\n\t}\n}\n\nvoid bayrepo_set_layer_activ(void * blob, int layer_number, activation activ) {\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tif (data->number_of_hidden) {\n\t\t\tif (layer_number <= data->number_of_hidden) {\n\t\t\t\tdata->activ_l[layer_number] = activ;\n\t\t\t}\n\t\t} else {\n\t\t\tif (!layer_number) {\n\t\t\t\tdata->activ_l[0] = activ;\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic int bayrepo_random_matrix(gsl_matrix *a, int m, int n, int is_negative) {\n\tint index, jndex;\n\n\tif (!r)\n\t\treturn -1;\n\n\tfor (index = 0; index < m; index++) {\n\t\tfor (jndex = 0; jndex < n; jndex++) {\n\t\t\tgsl_matrix_set(a, index, jndex,\n\t\t\t\t\tgsl_rng_uniform(r) - (is_negative ? 0.5 : 0.0));\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid *bayrepo_init_neuro(int input, int output, int hidden, int hidden_num,\n\t\tdouble alpha, activation activ) {\n\tint index;\n\n\tgsl_rng_default_seed = time(NULL);\n\n\tT = gsl_rng_knuthran2;\n\tr = gsl_rng_alloc(T);\n\n\tif (hidden_num < 0) {\n\t\thidden_num = 0;\n\t}\n\tneuro_skeleton *blob = calloc(1, sizeof(neuro_skeleton));\n\tif (!blob)\n\t\treturn NULL;\n\tblob->input_m = gsl_matrix_alloc(1, input);\n\tCLEAN_IF_NULL(input_m);\n\tblob->train = gsl_matrix_alloc(1, output);\n\tCLEAN_IF_NULL(train);\n\tblob->error = gsl_matrix_alloc(1, output);\n\tCLEAN_IF_NULL(error);\n\n\tif (hidden_num) {\n\t\tblob->output_m = gsl_matrix_alloc(hidden, output);\n\t\tCLEAN_IF_NULL(output_m);\n\t\tblob->hidden_m = (gsl_matrix **) calloc(hidden_num,\n\t\t\t\tsizeof(gsl_matrix *));\n\t\tCLEAN_IF_NULL(hidden_m);\n\t\tblob->dropuot = (gsl_matrix **) calloc(hidden_num,\n\t\t\t\tsizeof(gsl_matrix *));\n\t\tCLEAN_IF_NULL(dropuot);\n\t\tfor (index = 1; index < hidden_num; index++) {\n\t\t\tblob->hidden_m[index] = gsl_matrix_alloc(hidden, hidden);\n\t\t\tCLEAN_IF_NULL(hidden_m[index]);\n\t\t\tblob->dropuot[index] = gsl_matrix_alloc(1, hidden);\n\t\t\tCLEAN_IF_NULL(dropuot[index]);\n\t\t}\n\t\tblob->hidden_m[0] = gsl_matrix_alloc(input, hidden);\n\t\tCLEAN_IF_NULL(hidden_m[0]);\n\t\tblob->dropuot[0] = gsl_matrix_alloc(1, hidden);\n\t\tCLEAN_IF_NULL(dropuot[0]);\n\t\tblob->temp = gsl_matrix_alloc(1, hidden);\n\t\tCLEAN_IF_NULL(temp);\n\t} else {\n\t\tblob->output_m = gsl_matrix_alloc(input, output);\n\t\tCLEAN_IF_NULL(output_m);\n\t}\n\tblob->alpha = alpha;\n\tblob->input_l = input;\n\tblob->output_l = output;\n\tblob->hidden_l = hidden;\n\tblob->number_of_hidden = hidden_num;\n\n\tgsl_matrix_set_zero(blob->input_m);\n\tgsl_matrix_set_zero(blob->train);\n\tif (hidden_num) {\n\t\tif (bayrepo_random_matrix(blob->output_m, hidden, output,\n\t\t\t\t(activ == RELU ? 0 : 1)) < 0) {\n\t\t\tCLEAN_BLOB()\n;\t\t}\n\t\tfor (index = 1; index < hidden_num; index++) {\n\t\t\tif (bayrepo_random_matrix(blob->hidden_m[index], hidden, hidden, (activ==RELU?0:1))<0) {\n\t\t\t\tCLEAN_BLOB();\n\t\t\t}\n\t\t}\n\t\tif (bayrepo_random_matrix(blob->hidden_m[0], input, hidden, (activ==RELU?0:1))<0) {\n\t\t\tCLEAN_BLOB();\n\t\t}\n\t} else {\n\t\tif (bayrepo_random_matrix(blob->output_m, input, output, (activ==RELU?0:1))<0) {\n\t\t\tCLEAN_BLOB();\n\t\t}\n\t}\n\n\tint lyr_nmb = 1 + blob->number_of_hidden ? (blob->number_of_hidden + 1) : 0;\n\n\tblob->layers = (gsl_matrix **) calloc(lyr_nmb, sizeof(gsl_matrix *));\n\tCLEAN_IF_NULL(layers);\n\n\tif (hidden_num) {\n\t\tfor (index = 1; index < hidden_num; index++) {\n\t\t\tblob->layers[index] = gsl_matrix_alloc(1, hidden);\n\t\t\tCLEAN_IF_NULL(layers[index]);\n\t\t}\n\t\tblob->layers[0] = gsl_matrix_alloc(1, hidden);\n\t\tCLEAN_IF_NULL(layers[0]);\n\t\tblob->layers[lyr_nmb - 1] = gsl_matrix_alloc(1, output);\n\t\tCLEAN_IF_NULL(layers[lyr_nmb-1]);\n\t} else {\n\t\tblob->layers[0] = gsl_matrix_alloc(1, output);\n\t\tCLEAN_IF_NULL(layers[0]);\n\t}\n\n\tblob->layers_numb = lyr_nmb;\n\tblob->layers_delta = (gsl_matrix **) calloc(lyr_nmb, sizeof(gsl_matrix *));\n\tCLEAN_IF_NULL(layers_delta);\n\n\tif (hidden_num) {\n\t\tfor (index = 1; index < hidden_num; index++) {\n\t\t\tblob->layers_delta[index] = gsl_matrix_alloc(1, hidden);\n\t\t\tCLEAN_IF_NULL(layers_delta[index]);\n\t\t}\n\t\tblob->layers_delta[0] = gsl_matrix_alloc(1, hidden);\n\t\tCLEAN_IF_NULL(layers_delta[0]);\n\t\tblob->layers_delta[lyr_nmb - 1] = gsl_matrix_alloc(1, output);\n\t\tCLEAN_IF_NULL(layers_delta[lyr_nmb-1]);\n\t} else {\n\t\tblob->layers_delta[0] = gsl_matrix_alloc(1, output);\n\t\tCLEAN_IF_NULL(layers_delta[0]);\n\t}\n\tblob->activ = activ;\n\tblob->activ_l = calloc(blob->number_of_hidden + 1, sizeof(activation));\n\tCLEAN_IF_NULL(activ_l);\n\tfor (index = 0; index < (blob->number_of_hidden + 1); index++) {\n\t\tif (index == blob->number_of_hidden) {\n\t\t\tblob->activ_l[index] = NOACTIV;\n\t\t} else {\n\t\t\tblob->activ_l[index] = DEFLT;\n\t\t}\n\t}\n\n\treturn (void *) blob;\n}\n\nstatic void bayrepo_fill_dropout(gsl_matrix *a, int m, int n) {\n\tint index, jndex;\n\tif (!r) {\n\t\tfor (index = 0; index < m; index++) {\n\t\t\tfor (jndex = 0; jndex < n; jndex++) {\n\t\t\t\tgsl_matrix_set(a, index, jndex, 1.0);\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\n\tfor (index = 0; index < m; index++) {\n\t\tfor (jndex = 0; jndex < n; jndex++) {\n\t\t\tgsl_matrix_set(a, index, jndex, gsl_rng_uniform_int(r, 2) * 1.0);\n\t\t}\n\t}\n\n\treturn;\n}\n\nvoid bayrepo_fill_input(void *blob, int position, double scaled_value) {\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tif (position < data->input_l) {\n\t\t\tgsl_matrix_set(data->input_m, 0, position, scaled_value);\n\t\t}\n\t}\n}\n\nvoid bayrepo_fill_train(void *blob, int position, double scaled_value) {\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tif (position < data->output_l) {\n\t\t\tgsl_matrix_set(data->train, 0, position, scaled_value);\n\t\t}\n\t}\n}\n\nvoid bayrepo_fill_hidden(void *blob, int index, int position_x, int position_y,\n\t\tdouble scaled_value) {\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tgsl_matrix_set(data->hidden_m[index], position_x, position_y,\n\t\t\t\tscaled_value);\n\t}\n}\n\nvoid bayrepo_fill_outm(void *blob, int position_x, int position_y,\n\t\tdouble scaled_value) {\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tgsl_matrix_set(data->output_m, position_x, position_y, scaled_value);\n\t}\n}\n\nstatic void bayrepo_zero_layers(void *blob) {\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tint index;\n\t\tfor (index = 0; index < data->layers_numb; index++) {\n\t\t\tgsl_matrix_set_zero(data->layers[index]);\n\t\t}\n\t}\n}\n\nstatic double bayrepo_activation_func(double elem, neuro_skeleton *data,\n\t\tint lyn) {\n\tactivation act = data->activ;\n\tif ((lyn < (data->number_of_hidden + 1)) && (data->activ_l[lyn] != DEFLT)) {\n\t\tact = data->activ_l[lyn];\n\t}\n\tswitch (act) {\n\tcase RELU:\n\t\treturn elem > 0.0 ? elem : 0.0;\n\tcase TANH:\n\t\treturn tanh(elem);\n\tcase SIGMOID:\n\t\treturn 1.0 / (1.0 + exp(-elem));\n\tdefault:\n\t\treturn elem;\n\t}\n}\n\nactivation bayrepo_get_layer_func(void *blob, int lyn) {\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tif ((lyn < (data->number_of_hidden + 1))\n\t\t\t\t&& (data->activ_l[lyn] != DEFLT)) {\n\t\t\treturn data->activ_l[lyn];\n\t\t}\n\t}\n\treturn NOACTIV;\n}\n\nactivation bayrepo_get_sublayer_func(void *blob, int lyn) {\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tif (lyn < (data->number_of_hidden + 1)) {\n\t\t\treturn data->activ_l[lyn];\n\t\t}\n\t}\n\treturn NOACTIV;\n}\n\nstatic double bayrepo_activation_deriv(double elem, neuro_skeleton *data,\n\t\tint lyn) {\n\tactivation act = data->activ;\n\tif ((lyn < (data->number_of_hidden + 1)) && (data->activ_l[lyn] != DEFLT)) {\n\t\tact = data->activ_l[lyn];\n\t}\n\tswitch (act) {\n\tcase RELU:\n\t\treturn elem > 0.0 ? 1.0 : 0.0;\n\tcase TANH:\n\t\treturn 1.0 - (elem * elem);\n\tcase SIGMOID:\n\t\treturn elem * (1.0 - elem);\n\tdefault:\n\t\treturn elem;\n\t}\n}\n\nstatic void bayrepo_matix_customize(gsl_matrix *a, int size,\n\t\tneuro_skeleton *data, int lyn) {\n\tint index;\n\tfor (index = 0; index < size; index++) {\n\t\tgsl_matrix_set(a, 0, index,\n\t\t\t\tbayrepo_activation_func(gsl_matrix_get(a, 0, index), data,\n\t\t\t\t\t\tlyn));\n\t}\n}\n\nstatic void bayrepo_matix_deriv(gsl_matrix *a, int size, neuro_skeleton *data,\n\t\tint lyn) {\n\tint index;\n\tfor (index = 0; index < size; index++) {\n\t\tgsl_matrix_set(a, 0, index,\n\t\t\t\tbayrepo_activation_deriv(gsl_matrix_get(a, 0, index), data,\n\t\t\t\t\t\tlyn));\n\t}\n}\n\nstatic void bayrepo_query_internal(void *blob, int dropout) {\n\tint index;\n\tif (blob) {\n\t\tISDEBUGINFO_BEG()\n\t\t\tprintf(\"=====================Query=========================\\n\");\n\t\tISDEBUGINFO_END()\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tbayrepo_zero_layers(blob);\n\n\t\tif (data->number_of_hidden) {\n\t\t\tif (dropout == 1) {\n\t\t\t\tfor (index = 0; index < data->number_of_hidden; index++) {\n\t\t\t\t\tbayrepo_fill_dropout(data->dropuot[index], 1,\n\t\t\t\t\t\t\tdata->hidden_l);\n\t\t\t\t}\n\t\t\t}\n\t\t\tint cnt = 0;\n\t\t\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, data->input_m,\n\t\t\t\t\tdata->hidden_m[0], 0.0, data->layers[0]);\n\t\t\tbayrepo_matix_customize(data->layers[0], data->hidden_l, data, 0);\n\t\t\tif (dropout == 1) {\n\t\t\t\tgsl_matrix_mul_elements(data->layers[0], data->dropuot[0]);\n\t\t\t\tgsl_matrix_scale(data->layers[0], 2.0);\n\t\t\t}\n\t\t\tcnt++;\n\t\t\tfor (index = 1; index < data->number_of_hidden; index++) {\n\t\t\t\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0,\n\t\t\t\t\t\tdata->layers[index - 1], data->hidden_m[index], 0.0,\n\t\t\t\t\t\tdata->layers[index]);\n\t\t\t\tbayrepo_matix_customize(data->layers[index], data->hidden_l,\n\t\t\t\t\t\tdata, index);\n\t\t\t\tif (dropout == 1) {\n\t\t\t\t\tgsl_matrix_mul_elements(data->layers[index],\n\t\t\t\t\t\t\tdata->dropuot[index]);\n\t\t\t\t\tgsl_matrix_scale(data->layers[index], 2.0);\n\t\t\t\t}\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0,\n\t\t\t\t\tdata->layers[cnt - 1], data->output_m, 0.0,\n\t\t\t\t\tdata->layers[cnt]);\n\t\t\tbayrepo_matix_customize(data->layers[cnt], data->output_l, data,\n\t\t\t\t\tcnt);\n\n\t\t} else {\n\t\t\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, data->input_m,\n\t\t\t\t\tdata->output_m, 0.0, data->layers[0]);\n\t\t\tbayrepo_matix_customize(data->layers[0], data->output_l, data, 0);\n\t\t}\n\n\t\tDEBUGINFO(data->input_m, \"INPUTM\", -1);\n\t\tif (data->number_of_hidden) {\n\t\t\tfor (index = 0; index < data->number_of_hidden; index++) {\n\t\t\t\tDEBUGINFO(data->hidden_m[index], \"HIDDEN\", index);\n\t\t\t}\n\t\t}\n\t\tDEBUGINFO(data->output_m, \"OUTPUTM\", -1);\n\t\tfor (index = 0; index < data->layers_numb; index++) {\n\t\t\tDEBUGINFO(data->layers[index], \"LAYER\", index);\n\t\t}\n\t}\n}\n\nvoid bayrepo_query(void *blob) {\n\tbayrepo_query_internal(blob, 0);\n}\n\ndouble bayrepo_get_result(void *blob, int position) {\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tif (data->layers && position < data->output_l) {\n\t\t\treturn gsl_matrix_get(data->layers[data->layers_numb - 1], 0,\n\t\t\t\t\tposition);\n\t\t}\n\t}\n\treturn -10000.0;\n}\n\ndouble bayrepo_get_sum(gsl_matrix *a) {\n\tdouble result = 0.0;\n\tint index, jndex = 0;\n\tfor (index = 0; index < a->size1; index++) {\n\t\tfor (jndex = 0; jndex < a->size2; jndex++) {\n\t\t\tresult += gsl_matrix_get(a, index, jndex);\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid bayrepo_train(void *blob, int epoch, int use_dropout) {\n\tint index;\n\tif (blob) {\n\t\twhile (epoch--) {\n\t\t\tISDEBUGINFO_BEG()\n\t\t\t\tprintf(\n\t\t\t\t\t\t\"=====================Epoch %d=========================\\n\",\n\t\t\t\t\t\tepoch);\n\t\t\tISDEBUGINFO_END()\n\t\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\t\tbayrepo_query_internal(blob, use_dropout);\n\t\t\tgsl_matrix_memcpy(data->layers_delta[data->layers_numb - 1],\n\t\t\t\t\tdata->layers[data->layers_numb - 1]);\n\t\t\tISDEBUGINFO_BEG()\n\t\t\t\tgsl_matrix_memcpy(data->error,\n\t\t\t\t\t\tdata->layers[data->layers_numb - 1]);\n\t\t\tISDEBUGINFO_END();\n\t\t\tgsl_matrix_sub(data->layers_delta[data->layers_numb - 1],\n\t\t\t\t\tdata->train);\n\t\t\tISDEBUGINFO_BEG()\n\t\t\t\tgsl_matrix_sub(data->error, data->train);\n\t\t\t\tgsl_matrix_mul_elements(data->error, data->error);\n\t\t\t\tprintf(\"=======>Error=%f\\n\", bayrepo_get_sum(data->error));\n\t\t\tISDEBUGINFO_END();\n\t\t\tif (data->number_of_hidden) {\n\t\t\t\tint index;\n\t\t\t\tfor (index = (data->layers_numb - 2); index >= 0; index--) {\n\t\t\t\t\tgsl_matrix_set_zero(data->temp);\n\t\t\t\t\tgsl_matrix_memcpy(data->temp, data->layers[index]);\n\t\t\t\t\tbayrepo_matix_deriv(data->temp, data->hidden_l, data,\n\t\t\t\t\t\t\tindex);\n\t\t\t\t\tif (index == (data->layers_numb - 2)) {\n\t\t\t\t\t\tgsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0,\n\t\t\t\t\t\t\t\tdata->layers_delta[index + 1], data->output_m,\n\t\t\t\t\t\t\t\t0.0, data->layers_delta[index]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0,\n\t\t\t\t\t\t\t\tdata->layers_delta[index + 1],\n\t\t\t\t\t\t\t\tdata->hidden_m[index + 1], 0.0,\n\t\t\t\t\t\t\t\tdata->layers_delta[index]);\n\t\t\t\t\t}\n\t\t\t\t\tgsl_matrix_mul_elements(data->layers_delta[index],\n\t\t\t\t\t\t\tdata->temp);\n\t\t\t\t}\n\n\t\t\t\tif (use_dropout) {\n\t\t\t\t\tfor (index = 0; index < data->number_of_hidden; index++) {\n\t\t\t\t\t\tgsl_matrix_mul_elements(data->layers_delta[index],\n\t\t\t\t\t\t\t\tdata->dropuot[index]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (index = (data->layers_numb - 1); index >= 0; index--) {\n\t\t\t\t\tif (index == (data->layers_numb - 1)) {\n\t\t\t\t\t\tgsl_blas_dgemm(CblasTrans, CblasNoTrans, -data->alpha,\n\t\t\t\t\t\t\t\tdata->layers[index - 1],\n\t\t\t\t\t\t\t\tdata->layers_delta[index], 1.0, data->output_m);\n\t\t\t\t\t} else if (index == 0) {\n\t\t\t\t\t\tgsl_blas_dgemm(CblasTrans, CblasNoTrans, -data->alpha,\n\t\t\t\t\t\t\t\tdata->input_m, data->layers_delta[index], 1.0,\n\t\t\t\t\t\t\t\tdata->hidden_m[0]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgsl_blas_dgemm(CblasTrans, CblasNoTrans, -data->alpha,\n\t\t\t\t\t\t\t\tdata->layers[index - 1],\n\t\t\t\t\t\t\t\tdata->layers_delta[index], 1.0,\n\t\t\t\t\t\t\t\tdata->hidden_m[index]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgsl_blas_dgemm(CblasTrans, CblasNoTrans, -data->alpha,\n\t\t\t\t\t\tdata->input_m, data->layers_delta[0], 1.0,\n\t\t\t\t\t\tdata->output_m);\n\t\t\t}\n\t\t\tfor (index = 0; index < data->layers_numb; index++) {\n\t\t\t\tDEBUGINFO(data->layers_delta[index], \"LAYER_DELTA\", index);\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic void byrepo_png_write_data(png_structp png_ptr, png_bytep data,\n\t\tpng_size_t length) {\n\n\tbayrepo_mem_encode* p = (bayrepo_mem_encode*) png_get_io_ptr(png_ptr);\n\tsize_t nsize = p->size + length;\n\n\tif (p->buffer)\n\t\tp->buffer = realloc(p->buffer, nsize);\n\telse\n\t\tp->buffer = malloc(nsize);\n\n\tif (!p->buffer)\n\t\tpng_error(png_ptr, \"Write Error\");\n\n\tmemcpy(p->buffer + p->size, data, length);\n\tp->size += length;\n}\n\nstatic void bayrepo_png_flush(png_structp png_ptr) {\n}\n\nint bayrepo_write_matrix(void *blob, FILE *fp, int width, int height,\n\t\tbayrepo_mem_encode *buffer) {\n\tint code = 0;\n\tif (buffer) {\n\t\tbuffer->buffer = NULL;\n\t\tbuffer->size = 0;\n\t}\n\tpng_structp png_ptr = NULL;\n\tpng_infop info_ptr = NULL;\n\tpng_bytep row = NULL;\n\tif ((blob == NULL) || (fp == NULL)) {\n\t\treturn -1;\n\t}\n\n\tpng_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n\tif (png_ptr == NULL) {\n\t\tcode = -3;\n\t\tgoto finalise;\n\t}\n\n\tinfo_ptr = png_create_info_struct(png_ptr);\n\tif (info_ptr == NULL) {\n\t\tcode = -4;\n\t\tgoto finalise;\n\t}\n\n\tif (setjmp(png_jmpbuf(png_ptr))) {\n\t\tcode = -5;\n\t\tgoto finalise;\n\t}\n\n\tif (buffer) {\n\t\tpng_set_write_fn(png_ptr, buffer, byrepo_png_write_data,\n\t\t\t\tbayrepo_png_flush);\n\t} else {\n\t\tpng_init_io(png_ptr, fp);\n\t}\n\n\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\n\tint picSize = (height + 3) + (height + 3) * data->number_of_hidden;\n\n\tpng_set_IHDR(png_ptr, info_ptr, width, picSize, 8, PNG_COLOR_TYPE_GRAY,\n\tPNG_INTERLACE_NONE,\n\tPNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);\n\n\tpng_write_info(png_ptr, info_ptr);\n\n\trow = (png_bytep) malloc(3 * width * sizeof(png_byte));\n\tif (!row) {\n\t\tcode = -5;\n\t\tgoto finalise;\n\t}\n\n\tint index = 0;\n\tfor (index = 0; index < data->number_of_hidden + 1; index++) {\n\t\tgsl_matrix * m = NULL;\n\t\tif (data->number_of_hidden) {\n\t\t\tm = (index == data->number_of_hidden) ?\n\t\t\t\t\tdata->output_m : data->hidden_m[index];\n\t\t} else {\n\t\t\tm = data->output_m;\n\t\t}\n\n\t\tdouble rangeMax = gsl_matrix_max(m);\n\t\tdouble rangeMin = gsl_matrix_min(m);\n\n\t\tif (((width / m->size1) == 0) || ((height / m->size2) == 0)) {\n\t\t\treturn -2;\n\t\t}\n\n\t\tint sizeX = width / m->size1;\n\t\tint sizeY = height / m->size2;\n\n\t\tint x, y;\n\t\tfor (y = 0; y < height; y++) {\n\t\t\tfor (x = 0; x < width; x++) {\n\t\t\t\tint curX = x / sizeX;\n\t\t\t\tint curY = y / sizeY;\n\t\t\t\tif ((curX >= m->size1) || (curY >= m->size2)) {\n\t\t\t\t\trow[x] = (png_byte) 255;\n\t\t\t\t} else {\n\t\t\t\t\tpng_byte res_color = (png_byte) ((gsl_matrix_get(m, curX,\n\t\t\t\t\t\t\tcurY) - rangeMin) / (rangeMax - rangeMin) * 255.0);\n\t\t\t\t\tif (res_color > 255.0)\n\t\t\t\t\t\tres_color = 255.0;\n\t\t\t\t\trow[x] = (png_byte) (255.0 - res_color);\n\t\t\t\t}\n\t\t\t}\n\t\t\tpng_write_row(png_ptr, row);\n\t\t}\n\t\tfor (y = 0; y < 3; y++) {\n\t\t\tfor (x = 0; x < width; x++) {\n\t\t\t\tif (y != 1) {\n\t\t\t\t\trow[x] = (png_byte) 255;\n\t\t\t\t} else {\n\t\t\t\t\trow[x] = (png_byte) 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tpng_write_row(png_ptr, row);\n\t\t}\n\t}\n\n\tpng_write_end(png_ptr, NULL);\n\n\tfinalise: if (info_ptr != NULL)\n\t\tpng_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);\n\tif (png_ptr != NULL)\n\t\tpng_destroy_write_struct(&png_ptr, (png_infopp) NULL);\n\tif (row != NULL)\n\t\tfree(row);\n\treturn code;\n\n}\n\nvoid bayrepo_print_matrix_custom(void *blob, bayrepo_decorator *decor) {\n\tchar layer_name[MAX_LAYER_NAME_LEN];\n\tif (blob) {\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tint index = 0;\n\t\tfor (index = 0; index < (data->number_of_hidden + 1); index++) {\n\t\t\tgsl_matrix * m = NULL;\n\t\t\tif (data->number_of_hidden) {\n\t\t\t\tm = (index == data->number_of_hidden) ?\n\t\t\t\t\t\tdata->output_m : data->hidden_m[index];\n\t\t\t\tif (index == data->number_of_hidden) {\n\t\t\t\t\tsnprintf(layer_name, MAX_LAYER_NAME_LEN, \"Output layer\");\n\t\t\t\t} else {\n\t\t\t\t\tsnprintf(layer_name, MAX_LAYER_NAME_LEN, \"Hidden layer %d\",\n\t\t\t\t\t\t\tindex);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tm = data->output_m;\n\t\t\t\tsnprintf(layer_name, MAX_LAYER_NAME_LEN, \"Output layer\");\n\t\t\t}\n\t\t\tint posX, posY;\n\t\t\tif (decor->table_header)\n\t\t\t\tdecor->table_header(decor->user_data, layer_name, m->size1);\n\t\t\tfor (posX = 0; posX < m->size2; posX++) {\n\t\t\t\tif (decor->pre_column)\n\t\t\t\t\tdecor->pre_column(decor->user_data);\n\t\t\t\tfor (posY = 0; posY < m->size1; posY++) {\n\t\t\t\t\tif (decor->print_func)\n\t\t\t\t\t\tdecor->print_func(decor->user_data,\n\t\t\t\t\t\t\t\tgsl_matrix_get(m, posY, posX));\n\t\t\t\t}\n\t\t\t\tif (decor->post_column)\n\t\t\t\t\tdecor->post_column(decor->user_data);\n\t\t\t}\n\t\t\tif (decor->table_footer)\n\t\t\t\tdecor->table_footer(decor->user_data);\n\t\t}\n\t}\n}\n\nint input_l;\nint output_l;\nint hidden_l;\nint number_of_hidden;\ndouble alpha;\ngsl_matrix *input_m;\ngsl_matrix *output_m;\ngsl_matrix **hidden_m;\ngsl_matrix **dropuot;\ngsl_matrix **layers;\ngsl_matrix **layers_delta;\ngsl_matrix *temp;\ngsl_matrix *train;\ngsl_matrix *error;\nint layers_numb;\nactivation activ;\nactivation *activ_l;\n\n/*\n * Save format\n *\n * [int input_l]\\n\n * [int output_l]\\n\n * [int hidden_l]\\n\n * [int number_of_hidden]\\n\n * [double alpha]\\n\n * [int activ]\\n\n * [ACTBEG]\\n\n * [int layer_number]:[int activ]\\n\n * [ACTEND]\\n\n * [HIDDEN_BEG]\\n\n * [int X]:[int Y]:[double value]\\n\n * [HIDDEN_END]\n * [OUTPUT_BEG]\\n\n * [int X]:[int Y]:[double value]\\n\n * [OUTPUT_END]\\n\n */\n\nstatic char *bayrepo_reallocate_buffer(char *buffer, char *newdata, int *len,\n\t\tint newlen) {\n\tbuffer = (char *) realloc(buffer, *len + newlen);\n\tif (!buffer) {\n\t\treturn NULL;\n\t}\n\tmemcpy(buffer + *len, newdata, newlen);\n\t*len = *len + newlen;\n\treturn buffer;\n}\n\nint bayrepo_save_to_buffer(void *blob, char **buffer) {\n\tchar buff[MAX_LAYER_NAME_LEN];\n\tint index;\n\tif (blob) {\n\t\tint len = 0;\n\t\tchar *ptr = NULL;\n\t\tneuro_skeleton *data = (neuro_skeleton *) blob;\n\t\tsnprintf(buff, MAX_LAYER_NAME_LEN, \"%d\\n\", data->input_l);\n\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff));\n\t\tsnprintf(buff, MAX_LAYER_NAME_LEN, \"%d\\n\", data->output_l);\n\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff));\n\t\tsnprintf(buff, MAX_LAYER_NAME_LEN, \"%d\\n\", data->hidden_l);\n\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff));\n\t\tsnprintf(buff, MAX_LAYER_NAME_LEN, \"%d\\n\", data->number_of_hidden);\n\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff));\n\t\tsnprintf(buff, MAX_LAYER_NAME_LEN, \"%f\\n\", data->alpha);\n\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff));\n\t\tsnprintf(buff, MAX_LAYER_NAME_LEN, \"%d\\n\", (int) data->activ);\n\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff));\n\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) \"[ACTBEG]\\n\", &len,\n\t\t\t\tstrlen(\"[ACTBEG]\\n\"));\n\t\tfor (index = 0; index < (data->number_of_hidden + 1); index++) {\n\t\t\tsnprintf(buff, MAX_LAYER_NAME_LEN, \"%d:%d\\n\", index,\n\t\t\t\t\t(int) data->activ_l[index]);\n\t\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len,\n\t\t\t\t\tstrlen(buff));\n\t\t}\n\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) \"[ACTEND]\\n\", &len,\n\t\t\t\tstrlen(\"[ACTEND]\\n\"));\n\t\tfor (index = 0; index < data->number_of_hidden; index++) {\n\t\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) \"[HIDDEN_BEG]\\n\",\n\t\t\t\t\t&len, strlen(\"[HIDDEN_BEG]\\n\"));\n\t\t\tint x, y;\n\t\t\tfor (x = 0; x < data->hidden_m[index]->size1; x++) {\n\t\t\t\tfor (y = 0; y < data->hidden_m[index]->size2; y++) {\n\t\t\t\t\tsnprintf(buff, MAX_LAYER_NAME_LEN, \"%d:%d:%f\\n\", x, y,\n\t\t\t\t\t\t\tgsl_matrix_get(data->hidden_m[index], x, y));\n\t\t\t\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len,\n\t\t\t\t\t\t\tstrlen(buff));\n\t\t\t\t}\n\t\t\t}\n\t\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) \"[HIDDEN_END]\\n\",\n\t\t\t\t\t&len, strlen(\"[HIDDEN_END]\\n\"));\n\t\t}\n\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) \"[OUTPUT_BEG]\\n\", &len,\n\t\t\t\tstrlen(\"[OUTPUT_BEG]\\n\"));\n\t\tint x, y;\n\t\tfor (x = 0; x < data->output_m->size1; x++) {\n\t\t\tfor (y = 0; y < data->output_m->size2; y++) {\n\t\t\t\tsnprintf(buff, MAX_LAYER_NAME_LEN, \"%d:%d:%f\\n\", x, y,\n\t\t\t\t\t\tgsl_matrix_get(data->output_m, x, y));\n\t\t\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len,\n\t\t\t\t\t\tstrlen(buff));\n\t\t\t}\n\t\t}\n\t\tptr = bayrepo_reallocate_buffer(ptr, (char *) \"[OUTPUT_END]\\n\", &len,\n\t\t\t\tstrlen(\"[OUTPUT_END]\\n\"));\n\t\t*buffer = ptr;\n\t\treturn len;\n\t}\n\treturn 0;\n}\n\nvoid *bayrepo_restore_buffer(char *buffer, int buffer_len) {\n\tFILE *fp = fmemopen((void*) buffer, buffer_len, \"r\");\n\tint input_l = 0;\n\tint output_l = 0;\n\tint hidden_l = 0;\n\tint numb_of_hidden = 0;\n\tactivation act = RELU;\n\tint act_beg = 0;\n\tdouble alpha = 0.0;\n\tvoid *blob = NULL;\n\tint is_hidden = 0;\n\tint hidden_index = 0;\n\tint is_out = 0;\n\tif (fp) {\n\t\tchar result_buf[MAX_BUFFER_LEN];\n\t\tint counter = 0;\n\n\t\twhile (!feof(fp)) {\n\t\t\tif (fgets(result_buf, MAX_BUFFER_LEN, fp)) {\n\t\t\t\tswitch (counter) {\n\t\t\t\tcase 0: {\n\t\t\t\t\tresult_buf[strlen(result_buf) - 1] = 0;\n\t\t\t\t\tinput_l = atoi(result_buf);\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1: {\n\t\t\t\t\tresult_buf[strlen(result_buf) - 1] = 0;\n\t\t\t\t\toutput_l = atoi(result_buf);\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2: {\n\t\t\t\t\tresult_buf[strlen(result_buf) - 1] = 0;\n\t\t\t\t\thidden_l = atoi(result_buf);\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3: {\n\t\t\t\t\tresult_buf[strlen(result_buf) - 1] = 0;\n\t\t\t\t\tnumb_of_hidden = atoi(result_buf);\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4: {\n\t\t\t\t\tchar *tptr;\n\t\t\t\t\tresult_buf[strlen(result_buf) - 1] = 0;\n\t\t\t\t\talpha = strtod(result_buf, &tptr);\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5: {\n\t\t\t\t\tresult_buf[strlen(result_buf) - 1] = 0;\n\t\t\t\t\tact = (activation) atoi(result_buf);\n\t\t\t\t\tif (input_l > 0 && output_l > 0 && hidden_l >= 0\n\t\t\t\t\t\t\t&& numb_of_hidden >= 0 && alpha > 0.0) {\n\t\t\t\t\t\tblob = bayrepo_init_neuro(input_l, output_l, hidden_l,\n\t\t\t\t\t\t\t\tnumb_of_hidden, alpha, act);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: {\n\t\t\t\t\tif (!blob)\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\tif (strstr(result_buf, \"[ACTBEG]\")) {\n\t\t\t\t\t\tact_beg = 1;\n\t\t\t\t\t} else if (strstr(result_buf, \"[ACTEND]\")) {\n\t\t\t\t\t\tact_beg = 0;\n\t\t\t\t\t} else if (act_beg) {\n\t\t\t\t\t\tresult_buf[strlen(result_buf) - 1] = 0;\n\t\t\t\t\t\tchar *ptr = strchr(result_buf, ':');\n\t\t\t\t\t\tif (ptr) {\n\t\t\t\t\t\t\t*ptr = 0;\n\t\t\t\t\t\t\tptr++;\n\t\t\t\t\t\t\tint ly = atoi(result_buf);\n\t\t\t\t\t\t\tint ac = atoi(ptr);\n\t\t\t\t\t\t\tbayrepo_set_layer_activ(blob, ly, (activation) ac);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (strstr(result_buf, \"[HIDDEN_BEG]\")) {\n\t\t\t\t\t\tis_hidden = 1;\n\t\t\t\t\t} else if (strstr(result_buf, \"[HIDDEN_END]\")) {\n\t\t\t\t\t\thidden_index++;\n\t\t\t\t\t\tis_hidden = 0;\n\t\t\t\t\t} else if (is_hidden) {\n\t\t\t\t\t\tresult_buf[strlen(result_buf) - 1] = 0;\n\t\t\t\t\t\tchar *ptr1 = strchr(result_buf, ':');\n\t\t\t\t\t\tif (ptr1) {\n\t\t\t\t\t\t\t*ptr1 = 0;\n\t\t\t\t\t\t\tptr1++;\n\t\t\t\t\t\t\tchar *ptr2 = strchr(ptr1, ':');\n\t\t\t\t\t\t\tif (ptr2) {\n\t\t\t\t\t\t\t\t*ptr2 = 0;\n\t\t\t\t\t\t\t\tptr2++;\n\t\t\t\t\t\t\t\tchar *tptr = NULL;\n\t\t\t\t\t\t\t\tint x = atoi(result_buf);\n\t\t\t\t\t\t\t\tint y = atoi(ptr1);\n\t\t\t\t\t\t\t\tdouble vl = strtod(ptr2, &tptr);\n\t\t\t\t\t\t\t\tbayrepo_fill_hidden(blob, hidden_index, x, y,\n\t\t\t\t\t\t\t\t\t\tvl);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (strstr(result_buf, \"[OUTPUT_BEG]\")) {\n\t\t\t\t\t\tis_out = 1;\n\t\t\t\t\t} else if (strstr(result_buf, \"[OUTPUT_END]\")) {\n\t\t\t\t\t\thidden_index++;\n\t\t\t\t\t\tis_out = 0;\n\t\t\t\t\t} else if (is_out) {\n\t\t\t\t\t\tresult_buf[strlen(result_buf) - 1] = 0;\n\t\t\t\t\t\tchar *ptr1 = strchr(result_buf, ':');\n\t\t\t\t\t\tif (ptr1) {\n\t\t\t\t\t\t\t*ptr1 = 0;\n\t\t\t\t\t\t\tptr1++;\n\t\t\t\t\t\t\tchar *ptr2 = strchr(ptr1, ':');\n\t\t\t\t\t\t\tif (ptr2) {\n\t\t\t\t\t\t\t\t*ptr2 = 0;\n\t\t\t\t\t\t\t\tptr2++;\n\t\t\t\t\t\t\t\tchar *tptr = NULL;\n\t\t\t\t\t\t\t\tint x = atoi(result_buf);\n\t\t\t\t\t\t\t\tint y = atoi(ptr1);\n\t\t\t\t\t\t\t\tdouble vl = strtod(ptr2, &tptr);\n\t\t\t\t\t\t\t\tbayrepo_fill_outm(blob, x, y, vl);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcounter++;\n\t\t}\n\t\treturn blob;\n\n\t}\n\treturn NULL;\n}\n", "meta": {"hexsha": "fec902798f3eae9a53f68cb90d2ed110e4dafd07", "size": 27767, "ext": "c", "lang": "C", "max_stars_repo_path": "neuro.c", "max_stars_repo_name": "bayrepo/bayrepo_neuro", "max_stars_repo_head_hexsha": "3888190198e356a3be4fb2b71175630b34d8f963", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T14:42:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T14:42:04.000Z", "max_issues_repo_path": "neuro.c", "max_issues_repo_name": "bayrepo/bayrepo_neuro", "max_issues_repo_head_hexsha": "3888190198e356a3be4fb2b71175630b34d8f963", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neuro.c", "max_forks_repo_name": "bayrepo/bayrepo_neuro", "max_forks_repo_head_hexsha": "3888190198e356a3be4fb2b71175630b34d8f963", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6222435283, "max_line_length": 91, "alphanum_fraction": 0.6297403393, "num_tokens": 8984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.41548913874871674}} {"text": "/*\n * Copyright 2020 Makani Technologies LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// The GSL extra library provides linear algebra functions using a\n// similar interface to the rest of the GSL library.\n\n#ifndef COMMON_C_MATH_GSL_LINALG_EXTRA_H_\n#define COMMON_C_MATH_GSL_LINALG_EXTRA_H_\n\n#include \n\n#include \n#include \n#include \n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nint32_t GslTriangularSolve(CBLAS_SIDE_t side, CBLAS_UPLO_t uplo,\n CBLAS_TRANSPOSE_t transpose, const gsl_matrix *T,\n const gsl_matrix *B, gsl_matrix *X);\nvoid GslTrapezoidalToTriangular(const gsl_matrix *R, gsl_matrix *T,\n gsl_vector *tau);\nvoid GslTrapezoidalToTriangularZTMat(const gsl_matrix *T, const gsl_vector *tau,\n const gsl_matrix *X, gsl_matrix *Zt_X);\nint32_t GslMatrixDivide(CBLAS_SIDE_t side, const gsl_matrix *A,\n const gsl_matrix *B, gsl_matrix *X);\n\n#ifdef __cplusplus\n} // extern \"C\"\n#endif\n\n#endif // COMMON_C_MATH_GSL_LINALG_EXTRA_H_\n", "meta": {"hexsha": "fc8daaa0809ace0890f2c007630324f9b2535eba", "size": 1662, "ext": "h", "lang": "C", "max_stars_repo_path": "common/c_math/gsl_linalg_extra.h", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "common/c_math/gsl_linalg_extra.h", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "common/c_math/gsl_linalg_extra.h", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 34.625, "max_line_length": 80, "alphanum_fraction": 0.7057761733, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.41509262099119204}} {"text": "/* rng/ranlux.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n\n/* This is a lagged fibonacci generator with skipping developed by Luescher.\n The sequence is a series of 24-bit integers, x_n, \n\n x_n = d_n + b_n\n\n where d_n = x_{n-10} - x_{n-24} - c_{n-1}, b_n = 0 if d_n >= 0 and\n b_n = 2^24 if d_n < 0, c_n = 0 if d_n >= 0 and c_n = 1 if d_n < 0,\n where after 24 samples a group of p integers are \"skipped\", to\n reduce correlations. By default p = 199, but can be increased to\n 365.\n\n The period of the generator is around 10^171. \n\n From: M. Luescher, \"A portable high-quality random number generator\n for lattice field theory calculations\", Computer Physics\n Communications, 79 (1994) 100-110.\n\n Available on the net as hep-lat/9309020 at http://xxx.lanl.gov/\n\n See also,\n\n F. James, \"RANLUX: A Fortran implementation of the high-quality\n pseudo-random number generator of Luscher\", Computer Physics\n Communications, 79 (1994) 111-114\n\n Kenneth G. Hamilton, F. James, \"Acceleration of RANLUX\", Computer\n Physics Communications, 101 (1997) 241-248\n\n Kenneth G. Hamilton, \"Assembler RANLUX for PCs\", Computer Physics\n Communications, 101 (1997) 249-253 */\n\nstatic inline unsigned long int ranlux_get (void *vstate);\nstatic double ranlux_get_double (void *vstate);\nstatic void ranlux_set_lux (void *state, unsigned long int s, unsigned int luxury);\nstatic void ranlux_set (void *state, unsigned long int s);\nstatic void ranlux389_set (void *state, unsigned long int s);\n\nstatic const unsigned long int mask_lo = 0x00ffffffUL;\t/* 2^24 - 1 */\nstatic const unsigned long int mask_hi = ~0x00ffffffUL;\nstatic const unsigned long int two24 = 16777216;\t/* 2^24 */\n\ntypedef struct\n {\n unsigned int i;\n unsigned int j;\n unsigned int n;\n unsigned int skip;\n unsigned int carry;\n unsigned long int u[24];\n }\nranlux_state_t;\n\nstatic inline unsigned long int increment_state (ranlux_state_t * state);\n\nstatic inline unsigned long int\nincrement_state (ranlux_state_t * state)\n{\n unsigned int i = state->i;\n unsigned int j = state->j;\n long int delta = state->u[j] - state->u[i] - state->carry;\n\n if (delta & mask_hi)\n {\n state->carry = 1;\n delta &= mask_lo;\n }\n else\n {\n state->carry = 0;\n }\n\n state->u[i] = delta;\n\n if (i == 0)\n {\n i = 23;\n }\n else\n {\n i--;\n }\n\n state->i = i;\n\n if (j == 0)\n {\n j = 23;\n }\n else\n {\n j--;\n }\n\n state->j = j;\n\n return delta;\n}\n\nstatic inline unsigned long int\nranlux_get (void *vstate)\n{\n ranlux_state_t *state = (ranlux_state_t *) vstate;\n const unsigned int skip = state->skip;\n unsigned long int r = increment_state (state);\n\n state->n++;\n\n if (state->n == 24)\n {\n unsigned int i;\n state->n = 0;\n for (i = 0; i < skip; i++)\n\tincrement_state (state);\n }\n\n return r;\n}\n\nstatic double\nranlux_get_double (void *vstate)\n{\n return ranlux_get (vstate) / 16777216.0;\n}\n\nstatic void\nranlux_set_lux (void *vstate, unsigned long int s, unsigned int luxury)\n{\n ranlux_state_t *state = (ranlux_state_t *) vstate;\n int i;\n\n long int seed;\n\n if (s == 0)\n s = 314159265;\t/* default seed is 314159265 */\n\n seed = s;\n\n /* This is the initialization algorithm of F. James, widely in use\n for RANLUX. */\n\n for (i = 0; i < 24; i++)\n {\n unsigned long int k = seed / 53668;\n seed = 40014 * (seed - k * 53668) - k * 12211;\n if (seed < 0)\n\t{\n\t seed += 2147483563;\n\t}\n state->u[i] = seed % two24;\n }\n\n state->i = 23;\n state->j = 9;\n state->n = 0;\n state->skip = luxury - 24;\n\n if (state->u[23] & mask_hi)\n {\n state->carry = 1;\n }\n else\n {\n state->carry = 0;\n }\n}\n\nstatic void\nranlux_set (void *vstate, unsigned long int s)\n{\n ranlux_set_lux (vstate, s, 223);\n}\n\nstatic void\nranlux389_set (void *vstate, unsigned long int s)\n{\n ranlux_set_lux (vstate, s, 389);\n}\n\n\nstatic const gsl_rng_type ranlux_type =\n{\"ranlux\",\t\t\t/* name */\n 0x00ffffffUL,\t\t\t/* RAND_MAX */\n 0,\t\t\t\t/* RAND_MIN */\n sizeof (ranlux_state_t),\n &ranlux_set,\n &ranlux_get,\n &ranlux_get_double};\n\nstatic const gsl_rng_type ranlux389_type =\n{\"ranlux389\",\t\t\t/* name */\n 0x00ffffffUL,\t\t\t/* RAND_MAX */\n 0,\t\t\t\t/* RAND_MIN */\n sizeof (ranlux_state_t),\n &ranlux389_set,\n &ranlux_get,\n &ranlux_get_double};\n\nconst gsl_rng_type *gsl_rng_ranlux = &ranlux_type;\nconst gsl_rng_type *gsl_rng_ranlux389 = &ranlux389_type;\n", "meta": {"hexsha": "8628579ae543427c73cf0df526bf9ab15a391b79", "size": 5213, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/ranlux.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/rng/ranlux.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/rng/ranlux.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 23.3766816143, "max_line_length": 83, "alphanum_fraction": 0.6558603491, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.41483873972348245}} {"text": "/* blas/gsl_blas.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/*\n * Author: G. Jungman\n */\n#ifndef __GSL_BLAS_H__\n#define __GSL_BLAS_H__\n\n#if !defined( GSL_FUN )\n# if !defined( GSL_DLL )\n# define GSL_FUN extern\n# elif defined( BUILD_GSL_DLL )\n# define GSL_FUN extern __declspec(dllexport)\n# else\n# define GSL_FUN extern __declspec(dllimport)\n# endif\n#endif\n\n#include \n#include \n\n#include \n\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n\n/* ========================================================================\n * Level 1\n * ========================================================================\n */\n\nGSL_FUN int gsl_blas_sdsdot (float alpha,\n const gsl_vector_float * X,\n const gsl_vector_float * Y,\n float * result\n );\n\nGSL_FUN int gsl_blas_dsdot (const gsl_vector_float * X,\n const gsl_vector_float * Y,\n double * result\n );\n\nGSL_FUN int gsl_blas_sdot (const gsl_vector_float * X,\n const gsl_vector_float * Y,\n float * result\n );\n\nGSL_FUN int gsl_blas_ddot (const gsl_vector * X,\n const gsl_vector * Y,\n double * result\n );\n\n\nGSL_FUN int gsl_blas_cdotu (const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_complex_float * dotu);\n\nGSL_FUN int gsl_blas_cdotc (const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_complex_float * dotc);\n\nGSL_FUN int gsl_blas_zdotu (const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_complex * dotu);\n\nGSL_FUN int gsl_blas_zdotc (const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_complex * dotc);\n\n\nGSL_FUN float gsl_blas_snrm2 (const gsl_vector_float * X);\nGSL_FUN float gsl_blas_sasum (const gsl_vector_float * X);\nGSL_FUN double gsl_blas_dnrm2 (const gsl_vector * X);\nGSL_FUN double gsl_blas_dasum (const gsl_vector * X);\nGSL_FUN float gsl_blas_scnrm2 (const gsl_vector_complex_float * X);\nGSL_FUN float gsl_blas_scasum (const gsl_vector_complex_float * X);\nGSL_FUN double gsl_blas_dznrm2 (const gsl_vector_complex * X);\nGSL_FUN double gsl_blas_dzasum (const gsl_vector_complex * X);\n\n\nGSL_FUN CBLAS_INDEX_t gsl_blas_isamax (const gsl_vector_float * X);\nGSL_FUN CBLAS_INDEX_t gsl_blas_idamax (const gsl_vector * X);\nGSL_FUN CBLAS_INDEX_t gsl_blas_icamax (const gsl_vector_complex_float * X);\nGSL_FUN CBLAS_INDEX_t gsl_blas_izamax (const gsl_vector_complex * X);\n\n\nGSL_FUN int gsl_blas_sswap (gsl_vector_float * X,\n gsl_vector_float * Y);\n\nGSL_FUN int gsl_blas_scopy (const gsl_vector_float * X,\n gsl_vector_float * Y);\n\nGSL_FUN int gsl_blas_saxpy (float alpha,\n const gsl_vector_float * X,\n gsl_vector_float * Y);\n\nGSL_FUN int gsl_blas_dswap (gsl_vector * X,\n gsl_vector * Y);\n\nGSL_FUN int gsl_blas_dcopy (const gsl_vector * X,\n gsl_vector * Y);\n\nGSL_FUN int gsl_blas_daxpy (double alpha,\n const gsl_vector * X,\n gsl_vector * Y);\n\nGSL_FUN int gsl_blas_cswap (gsl_vector_complex_float * X,\n gsl_vector_complex_float * Y);\n\nGSL_FUN int gsl_blas_ccopy (const gsl_vector_complex_float * X,\n gsl_vector_complex_float * Y);\n\nGSL_FUN int gsl_blas_caxpy (const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n gsl_vector_complex_float * Y);\n\nGSL_FUN int gsl_blas_zswap (gsl_vector_complex * X,\n gsl_vector_complex * Y);\n\nGSL_FUN int gsl_blas_zcopy (const gsl_vector_complex * X,\n gsl_vector_complex * Y);\n\nGSL_FUN int gsl_blas_zaxpy (const gsl_complex alpha,\n const gsl_vector_complex * X,\n gsl_vector_complex * Y);\n\n\nGSL_FUN int gsl_blas_srotg (float a[], float b[], float c[], float s[]);\n\nGSL_FUN int gsl_blas_srotmg (float d1[], float d2[], float b1[], float b2, float P[]);\n\nGSL_FUN int gsl_blas_srot (gsl_vector_float * X,\n gsl_vector_float * Y,\n float c, float s);\n\nGSL_FUN int gsl_blas_srotm (gsl_vector_float * X,\n gsl_vector_float * Y,\n const float P[]);\n\nGSL_FUN int gsl_blas_drotg (double a[], double b[], double c[], double s[]);\n\nGSL_FUN int gsl_blas_drotmg (double d1[], double d2[], double b1[],\n double b2, double P[]);\n\nGSL_FUN int gsl_blas_drot (gsl_vector * X,\n gsl_vector * Y,\n const double c, const double s);\n\nGSL_FUN int gsl_blas_drotm (gsl_vector * X,\n gsl_vector * Y,\n const double P[]);\n\n\nGSL_FUN void gsl_blas_sscal (float alpha, gsl_vector_float * X);\nGSL_FUN void gsl_blas_dscal (double alpha, gsl_vector * X);\nGSL_FUN void gsl_blas_cscal (const gsl_complex_float alpha, gsl_vector_complex_float * X);\nGSL_FUN void gsl_blas_zscal (const gsl_complex alpha, gsl_vector_complex * X);\nGSL_FUN void gsl_blas_csscal (float alpha, gsl_vector_complex_float * X);\nGSL_FUN void gsl_blas_zdscal (double alpha, gsl_vector_complex * X);\n\n\n/* ===========================================================================\n * Level 2\n * ===========================================================================\n */\n\n/*\n * Routines with standard 4 prefixes (S, D, C, Z)\n */\nGSL_FUN int gsl_blas_sgemv (CBLAS_TRANSPOSE_t TransA,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_vector_float * X,\n float beta,\n gsl_vector_float * Y);\n\nGSL_FUN int gsl_blas_strmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_float * A,\n gsl_vector_float * X);\n\nGSL_FUN int gsl_blas_strsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_float * A,\n gsl_vector_float * X);\n\nGSL_FUN int gsl_blas_dgemv (CBLAS_TRANSPOSE_t TransA,\n double alpha,\n const gsl_matrix * A,\n const gsl_vector * X,\n double beta,\n gsl_vector * Y);\n\nGSL_FUN int gsl_blas_dtrmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix * A,\n gsl_vector * X);\n\nGSL_FUN int gsl_blas_dtrsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix * A,\n gsl_vector * X);\n\nGSL_FUN int gsl_blas_cgemv (CBLAS_TRANSPOSE_t TransA,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_vector_complex_float * X,\n const gsl_complex_float beta,\n gsl_vector_complex_float * Y);\n\nGSL_FUN int gsl_blas_ctrmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex_float * A,\n gsl_vector_complex_float * X);\n\nGSL_FUN int gsl_blas_ctrsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex_float * A,\n gsl_vector_complex_float * X);\n\nGSL_FUN int gsl_blas_zgemv (CBLAS_TRANSPOSE_t TransA,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_vector_complex * X,\n const gsl_complex beta,\n gsl_vector_complex * Y);\n\nGSL_FUN int gsl_blas_ztrmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex * A,\n gsl_vector_complex * X);\n\nGSL_FUN int gsl_blas_ztrsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex * A,\n gsl_vector_complex *X);\n\n/*\n * Routines with S and D prefixes only\n */\nGSL_FUN int gsl_blas_ssymv (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_vector_float * X,\n float beta,\n gsl_vector_float * Y);\n\nGSL_FUN int gsl_blas_sger (float alpha,\n const gsl_vector_float * X,\n const gsl_vector_float * Y,\n gsl_matrix_float * A);\n\nGSL_FUN int gsl_blas_ssyr (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_vector_float * X,\n gsl_matrix_float * A);\n\nGSL_FUN int gsl_blas_ssyr2 (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_vector_float * X,\n const gsl_vector_float * Y,\n gsl_matrix_float * A);\n\nGSL_FUN int gsl_blas_dsymv (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_matrix * A,\n const gsl_vector * X,\n double beta,\n gsl_vector * Y);\nGSL_FUN int gsl_blas_dger (double alpha,\n const gsl_vector * X,\n const gsl_vector * Y,\n gsl_matrix * A);\n\nGSL_FUN int gsl_blas_dsyr (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_vector * X,\n gsl_matrix * A);\n\nGSL_FUN int gsl_blas_dsyr2 (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_vector * X,\n const gsl_vector * Y,\n gsl_matrix * A);\n\n/*\n * Routines with C and Z prefixes only\n */\n\nGSL_FUN int gsl_blas_chemv (CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_vector_complex_float * X,\n const gsl_complex_float beta,\n gsl_vector_complex_float * Y);\n\nGSL_FUN int gsl_blas_cgeru (const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_matrix_complex_float * A);\n\nGSL_FUN int gsl_blas_cgerc (const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_matrix_complex_float * A);\n\nGSL_FUN int gsl_blas_cher (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_vector_complex_float * X,\n gsl_matrix_complex_float * A);\n\nGSL_FUN int gsl_blas_cher2 (CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_matrix_complex_float * A);\n\nGSL_FUN int gsl_blas_zhemv (CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_vector_complex * X,\n const gsl_complex beta,\n gsl_vector_complex * Y);\n\nGSL_FUN int gsl_blas_zgeru (const gsl_complex alpha,\n const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_matrix_complex * A);\n\nGSL_FUN int gsl_blas_zgerc (const gsl_complex alpha,\n const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_matrix_complex * A);\n\nGSL_FUN int gsl_blas_zher (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_vector_complex * X,\n gsl_matrix_complex * A);\n\nGSL_FUN int gsl_blas_zher2 (CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_matrix_complex * A);\n\n/*\n * ===========================================================================\n * Prototypes for level 3 BLAS\n * ===========================================================================\n */\n\n/*\n * Routines with standard 4 prefixes (S, D, C, Z)\n */\nGSL_FUN int gsl_blas_sgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_matrix_float * B,\n float beta,\n gsl_matrix_float * C);\n\nGSL_FUN int gsl_blas_ssymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_matrix_float * B,\n float beta,\n gsl_matrix_float * C);\n\nGSL_FUN int gsl_blas_ssyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans,\n float alpha,\n const gsl_matrix_float * A,\n float beta,\n gsl_matrix_float * C);\n\nGSL_FUN int gsl_blas_ssyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_matrix_float * B,\n float beta,\n gsl_matrix_float * C);\n\nGSL_FUN int gsl_blas_strmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n float alpha,\n const gsl_matrix_float * A,\n gsl_matrix_float * B);\n\nGSL_FUN int gsl_blas_strsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n float alpha,\n const gsl_matrix_float * A,\n gsl_matrix_float * B);\n\nGSL_FUN int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n double alpha,\n const gsl_matrix * A,\n const gsl_matrix * B,\n double beta,\n gsl_matrix * C);\n\nGSL_FUN int gsl_blas_dsymm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_matrix * A,\n const gsl_matrix * B,\n double beta,\n gsl_matrix * C);\n\nGSL_FUN int gsl_blas_dsyrk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n double alpha,\n const gsl_matrix * A,\n double beta,\n gsl_matrix * C);\n\nGSL_FUN int gsl_blas_dsyr2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n double alpha,\n const gsl_matrix * A,\n const gsl_matrix * B,\n double beta,\n gsl_matrix * C);\n\nGSL_FUN int gsl_blas_dtrmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n double alpha,\n const gsl_matrix * A,\n gsl_matrix * B);\n\nGSL_FUN int gsl_blas_dtrsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n double alpha,\n const gsl_matrix * A,\n gsl_matrix * B);\n\nGSL_FUN int gsl_blas_cgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nGSL_FUN int gsl_blas_csymm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nGSL_FUN int gsl_blas_csyrk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nGSL_FUN int gsl_blas_csyr2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nGSL_FUN int gsl_blas_ctrmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n gsl_matrix_complex_float * B);\n\nGSL_FUN int gsl_blas_ctrsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n gsl_matrix_complex_float * B);\n\nGSL_FUN int gsl_blas_zgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nGSL_FUN int gsl_blas_zsymm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nGSL_FUN int gsl_blas_zsyrk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nGSL_FUN int gsl_blas_zsyr2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex *C);\n\nGSL_FUN int gsl_blas_ztrmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n gsl_matrix_complex * B);\n\nGSL_FUN int gsl_blas_ztrsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n gsl_matrix_complex * B);\n\n/*\n * Routines with prefixes C and Z only\n */\nGSL_FUN int gsl_blas_chemm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nGSL_FUN int gsl_blas_cherk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n float alpha,\n const gsl_matrix_complex_float * A,\n float beta,\n gsl_matrix_complex_float * C);\n\nGSL_FUN int gsl_blas_cher2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n float beta,\n gsl_matrix_complex_float * C);\n\nGSL_FUN int gsl_blas_zhemm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nGSL_FUN int gsl_blas_zherk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n double alpha,\n const gsl_matrix_complex * A,\n double beta,\n gsl_matrix_complex * C);\n\nGSL_FUN int gsl_blas_zher2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n double beta,\n gsl_matrix_complex * C);\n\n\n__END_DECLS\n\n#endif /* __GSL_BLAS_H__ */\n", "meta": {"hexsha": "531e47edbdf9808460c9510ec7d8b5006cf5c618", "size": 23015, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_blas.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_blas.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_blas.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5448613377, "max_line_length": 91, "alphanum_fraction": 0.5446447969, "num_tokens": 5068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979746, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4147749112500926}} {"text": "/*\n** libproj -- library of cartographic projections\n**\n** Copyright (c) 2003, 2006 Gerald I. Evenden\n*/\nstatic const char\nLIBPROJ_ID[] = \"Id\";\n/*\n** Permission is hereby granted, free of charge, to any person obtaining\n** a copy of this software and associated documentation files (the\n** \"Software\"), to deal in the Software without restriction, including\n** without limitation the rights to use, copy, modify, merge, publish,\n** distribute, sublicense, and/or sell copies of the Software, and to\n** permit persons to whom the Software is furnished to do so, subject to\n** the following conditions:\n**\n** The above copyright notice and this permission notice shall be\n** included in all copies or substantial portions of the Software.\n**\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n#define N_TOL 1e-6\n#define PROJ_LIB__\n#ifdef PROJ_HAVE_GSL\n#include \n#define GSL_WORK 1000\n#define PROJ_PARMS__ \\\n double n[2]; \\\n gsl_function func; \\\n gsl_integration_workspace *work; \\\n int mode;\n#include \n double\nmayr_kernel(double x, void * n) {\n return (pow(cos(x), *(double*)n));\n}\n#else\n#define PROJ_PARMS__ \\\n int mode;\n#include \n#endif\nPROJ_HEAD(mayr, \"Mayr (Tobler Meridian Geometric Mean)\") \"\\n\\tPCyl., Sph., NoInv.\";\n/* definition of segment bounds for <1e-7 error (unit sphere) */\n#define SEG1 1.4\n#define SEG2 1.55\n#define SEG3 1.57\n#define BASE1 1.151132004484049\n#define BASE2 1.196140916241303\n#define BASE3 1.19812525384759\n#define HALFN 4\n/* Gauss Legendre weights/abscissa */\ndouble X[] = {\n 0.96028985649753618,\n 0.79666647741362673,\n 0.52553240991632899,\n 0.18343464249564981 };\ndouble W[] = {\n 0.10122853629037638,\n 0.22238103445337443,\n 0.31370664587788744,\n 0.36268378337836199 };\n/* Mayr kernel */\n#define func(v) sqrt(cos(v))\n static\ndouble gauss_legendre(double x0, double x1) {\n int i = 0;\n double s = 0., *x = X, *w = W, xsize, xmean, arg;\n\n xmean = 0.5 * (x1 + x0);\n xsize = 0.5 * (x1 - x0);\n while ( i++ < HALFN ) {\n arg = xsize * *x++;\n s += *w++ * (func(xmean - arg) + func(xmean + arg));\n };\n return xsize * s;\n}\n static\ndouble integrate(double val) {\n double out;\n\n if (val <= SEG1)\n out = gauss_legendre(0., val);\n else if (val <= SEG2)\n out = BASE1 + gauss_legendre(SEG1, val);\n else if (val <= SEG3)\n out = BASE2 + gauss_legendre(SEG2, val);\n else\n out = BASE3 + gauss_legendre(SEG3, val);\n return out;\n}\nFORWARD(s_forward); /* spheroid */\n (void) P; /* avoid warning */\n\n xy.x = lp.lam * func(lp.phi);\n xy.y = integrate(fabs(lp.phi));\n if (lp.phi < 0.)\n xy.y = -xy.y;\n return (xy);\n}\n#ifdef PROJ_HAVE_GSL\nFORWARD(s_forwardg); /* numerical integration n <> 0.5 */\n double error;\n \n gsl_integration_qags(&P->func, 0., fabs(lp.phi), 1e-7, 1e-8, GSL_WORK,\n P->work, &xy.y, &error);\n xy.x = lp.lam * pow(cos(lp.phi), P->n[1]);\n if (lp.phi < 0.)\n xy.y = -xy.y;\n return (xy);\n}\n#endif\nFREEUP;\n if (P) {\n#if PROJ_HAVE_GSL\n if (P->mode) \n gsl_integration_workspace_free(P->work);\n#endif\n free(P);\n }\n}\nENTRY0(mayr)\n P->es = 0;\n if (proj_param(P->params, \"tn\").i) {\n#if PROJ_HAVE_GSL\n P->n[0] = proj_param(P->params, \"dn\").f;\n if ((P->n[0] < N_TOL) || (P->n[0] > 1.-N_TOL))\n E_ERROR(-40)\n P->fwd = s_forwardg;\n P->n[1] = 1. - P->n[0];\n P->func.function = &mayr_kernel;\n P->func.params = P->n;\n P->work = gsl_integration_workspace_alloc (GSL_WORK);\n P->mode = 1;\n#else\n E_ERROR(-47)\n#endif\n } else {\n P->mode = 0;\n P->fwd = s_forward;\n }\nENDENTRY(P)\n/*\n** Log: proj_mayr.c\n** Revision 3.2 2006/01/19 01:52:59 gie\n** correct some casting ^)*^&^\n**\n** Revision 3.1 2006/01/11 01:38:18 gie\n** Initial\n**\n*/\n", "meta": {"hexsha": "8c0b83c5d20af24ae2186077b7b9c3e7a234f7b1", "size": 4156, "ext": "c", "lang": "C", "max_stars_repo_path": "Utilities/vtklibproj4/proj_mayr.c", "max_stars_repo_name": "Lin1225/vtk_v5.10.0", "max_stars_repo_head_hexsha": "b54ac74f4716572862365fbff28cd0ecb8d08c3d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-06-20T23:31:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T02:17:16.000Z", "max_issues_repo_path": "Utilities/vtklibproj4/proj_mayr.c", "max_issues_repo_name": "Armand0s/homemade_vtk", "max_issues_repo_head_hexsha": "6bc7b595a4a7f86e8fa969d067360450fa4e0a6a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-01T23:21:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-02T23:44:43.000Z", "max_forks_repo_path": "Utilities/vtklibproj4/proj_mayr.c", "max_forks_repo_name": "Armand0s/homemade_vtk", "max_forks_repo_head_hexsha": "6bc7b595a4a7f86e8fa969d067360450fa4e0a6a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-03-23T21:13:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T11:15:39.000Z", "avg_line_length": 26.4713375796, "max_line_length": 84, "alphanum_fraction": 0.6530317613, "num_tokens": 1359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.414339534346544}} {"text": "/* gmres.c\n * \n * Copyright (C) 2014 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * The code in this module is based on the Householder GMRES\n * algorithm described in\n *\n * [1] H. F. Walker, Implementation of the GMRES method using\n * Householder transformations, SIAM J. Sci. Stat. Comput.\n * 9(1), 1988.\n *\n * [2] Y. Saad, Iterative methods for sparse linear systems,\n * 2nd edition, SIAM, 2003.\n */\n\ntypedef struct\n{\n size_t n; /* size of linear system */\n size_t m; /* dimension of Krylov subspace K_m */\n gsl_vector *r; /* residual vector r = b - A*x */\n gsl_matrix *H; /* Hessenberg matrix n-by-(m+1) */\n gsl_vector *tau; /* householder scalars */\n gsl_vector *y; /* least squares rhs and solution vector */\n\n double *c; /* Givens rotations */\n double *s;\n\n double normr; /* residual norm ||r|| */\n} gmres_state_t;\n\nstatic void gmres_free(void *vstate);\nstatic int gmres_iterate(const gsl_spmatrix *A, const gsl_vector *b,\n const double tol, gsl_vector *x, void *vstate);\n\n/*\ngmres_alloc()\n Allocate a GMRES workspace for solving an n-by-n system A x = b\n\nInputs: n - size of system\n krylov_m - size of Krylov subspace (ie: number of inner iterations)\n if this parameter is 0, the value GSL_MIN(n,10) is\n used\n\nReturn: pointer to workspace\n*/\n\nstatic void *\ngmres_alloc(const size_t n, const size_t m)\n{\n gmres_state_t *state;\n\n if (n == 0)\n {\n GSL_ERROR_NULL(\"matrix dimension n must be a positive integer\",\n GSL_EINVAL);\n }\n\n state = calloc(1, sizeof(gmres_state_t));\n if (!state)\n {\n GSL_ERROR_NULL(\"failed to allocate gmres state\", GSL_ENOMEM);\n }\n\n state->n = n;\n\n /* compute size of Krylov subspace */\n if (m == 0)\n state->m = GSL_MIN(n, 10);\n else\n state->m = GSL_MIN(n, m);\n\n state->r = gsl_vector_alloc(n);\n if (!state->r)\n {\n gmres_free(state);\n GSL_ERROR_NULL(\"failed to allocate r vector\", GSL_ENOMEM);\n }\n\n state->H = gsl_matrix_alloc(n, state->m + 1);\n if (!state->H)\n {\n gmres_free(state);\n GSL_ERROR_NULL(\"failed to allocate H matrix\", GSL_ENOMEM);\n }\n\n state->tau = gsl_vector_alloc(state->m + 1);\n if (!state->tau)\n {\n gmres_free(state);\n GSL_ERROR_NULL(\"failed to allocate tau vector\", GSL_ENOMEM);\n }\n\n state->y = gsl_vector_alloc(state->m + 1);\n if (!state->y)\n {\n gmres_free(state);\n GSL_ERROR_NULL(\"failed to allocate y vector\", GSL_ENOMEM);\n }\n\n state->c = malloc(state->m * sizeof(double));\n state->s = malloc(state->m * sizeof(double));\n if (!state->c || !state->s)\n {\n gmres_free(state);\n GSL_ERROR_NULL(\"failed to allocate Givens vectors\", GSL_ENOMEM);\n }\n\n state->normr = 0.0;\n\n return state;\n} /* gmres_alloc() */\n\nstatic void\ngmres_free(void *vstate)\n{\n gmres_state_t *state = (gmres_state_t *) vstate;\n\n if (state->r)\n gsl_vector_free(state->r);\n\n if (state->H)\n gsl_matrix_free(state->H);\n\n if (state->tau)\n gsl_vector_free(state->tau);\n\n if (state->y)\n gsl_vector_free(state->y);\n\n if (state->c)\n free(state->c);\n\n if (state->s)\n free(state->s);\n\n free(state);\n} /* gmres_free() */\n\n/*\ngmres_iterate()\n Solve A*x = b using GMRES algorithm\n\nInputs: A - sparse square matrix\n b - right hand side vector\n tol - stopping tolerance (see below)\n x - (input/output) on input, initial estimate x_0;\n on output, solution vector\n work - workspace\n\nReturn:\nGSL_SUCCESS if converged to solution (solution stored in x). In\nthis case the following will be true:\n\n||b - A*x|| <= tol * ||b||\n\nGSL_CONTINUE if not yet converged; in this case x contains the\nmost recent solution vector and calling this function more times\nwith the input x could result in convergence (ie: restarted GMRES)\n\nNotes:\n1) Based on algorithm 2.2 of (Walker, 1998 [1]) and algorithm 6.10 of\n(Saad, 2003 [2])\n\n2) On output, work->normr contains ||b - A*x||\n*/\n\nstatic int\ngmres_iterate(const gsl_spmatrix *A, const gsl_vector *b,\n const double tol, gsl_vector *x,\n void *vstate)\n{\n const size_t N = A->size1;\n gmres_state_t *state = (gmres_state_t *) vstate;\n\n if (N != A->size2)\n {\n GSL_ERROR(\"matrix must be square\", GSL_ENOTSQR);\n }\n else if (N != b->size)\n {\n GSL_ERROR(\"matrix does not match right hand side\", GSL_EBADLEN);\n }\n else if (N != x->size)\n {\n GSL_ERROR(\"matrix does not match solution vector\", GSL_EBADLEN);\n }\n else if (N != state->n)\n {\n GSL_ERROR(\"matrix does not match workspace\", GSL_EBADLEN);\n }\n else\n {\n int status = GSL_SUCCESS;\n const size_t maxit = state->m;\n const double normb = gsl_blas_dnrm2(b); /* ||b|| */\n const double reltol = tol * normb; /* tol*||b|| */\n double normr; /* ||r|| */\n size_t m, k;\n double tau; /* householder scalar */\n gsl_matrix *H = state->H; /* Hessenberg matrix */\n gsl_vector *r = state->r; /* residual vector */\n gsl_vector *w = state->y; /* least squares RHS */\n gsl_matrix_view Rm; /* R_m = H(1:m,2:m+1) */\n gsl_vector_view ym; /* y(1:m) */\n gsl_vector_view h0 = gsl_matrix_column(H, 0);\n\n /*\n * The Hessenberg matrix will have the following structure:\n *\n * H = [ ||r_0|| | v_1 v_2 ... v_m ]\n * [ u_1 | u_2 u_3 ... u_{m+1} ]\n *\n * where v_j are the orthonormal vectors spanning the Krylov\n * subpsace of length j + 1 and u_{j+1} are the householder\n * vectors of length n - j - 1.\n * In fact, u_{j+1} has length n - j since u_{j+1}[0] = 1,\n * but this 1 is not stored.\n */\n gsl_matrix_set_zero(H);\n\n /* Step 1a: compute r = b - A*x_0 */\n gsl_vector_memcpy(r, b);\n gsl_spblas_dgemv(CblasNoTrans, -1.0, A, x, 1.0, r);\n\n /* Step 1b */\n gsl_vector_memcpy(&h0.vector, r);\n tau = gsl_linalg_householder_transform(&h0.vector);\n\n /* store tau_1 */\n gsl_vector_set(state->tau, 0, tau);\n\n /* initialize w (stored in state->y) */\n gsl_vector_set_zero(w);\n gsl_vector_set(w, 0, gsl_vector_get(&h0.vector, 0));\n\n for (m = 1; m <= maxit; ++m)\n {\n size_t j = m - 1; /* C indexing */\n double c, s; /* Givens rotation */\n\n /* v_m */\n gsl_vector_view vm = gsl_matrix_column(H, m);\n\n /* v_m(m:end) */\n gsl_vector_view vv = gsl_vector_subvector(&vm.vector, j, N - j);\n\n /* householder vector u_m for projection P_m */\n gsl_vector_view um = gsl_matrix_subcolumn(H, j, j, N - j);\n\n /* Step 2a: form v_m = P_m e_m = e_m - tau_m w_m */\n gsl_vector_set_zero(&vm.vector);\n gsl_vector_memcpy(&vv.vector, &um.vector);\n tau = gsl_vector_get(state->tau, j); /* tau_m */\n gsl_vector_scale(&vv.vector, -tau);\n gsl_vector_set(&vv.vector, 0, 1.0 - tau);\n\n /* Step 2a: v_m <- P_1 P_2 ... P_{m-1} v_m */\n for (k = j; k > 0 && k--; )\n {\n gsl_vector_view uk =\n gsl_matrix_subcolumn(H, k, k, N - k);\n gsl_vector_view vk =\n gsl_vector_subvector(&vm.vector, k, N - k);\n tau = gsl_vector_get(state->tau, k);\n gsl_linalg_householder_hv(tau, &uk.vector, &vk.vector);\n }\n\n /* Step 2a: v_m <- A*v_m */\n gsl_spblas_dgemv(CblasNoTrans, 1.0, A, &vm.vector, 0.0, r);\n gsl_vector_memcpy(&vm.vector, r);\n\n /* Step 2a: v_m <- P_m ... P_1 v_m */\n for (k = 0; k <= j; ++k)\n {\n gsl_vector_view uk = gsl_matrix_subcolumn(H, k, k, N - k);\n gsl_vector_view vk = gsl_vector_subvector(&vm.vector, k, N - k);\n tau = gsl_vector_get(state->tau, k);\n gsl_linalg_householder_hv(tau, &uk.vector, &vk.vector);\n }\n\n /* Steps 2c,2d: find P_{m+1} and set v_m <- P_{m+1} v_m */\n if (m < N)\n {\n /* householder vector u_{m+1} for projection P_{m+1} */\n gsl_vector_view ump1 = gsl_matrix_subcolumn(H, m, m, N - m);\n\n tau = gsl_linalg_householder_transform(&ump1.vector);\n gsl_vector_set(state->tau, j + 1, tau);\n }\n\n /* Step 2e: v_m <- J_{m-1} ... J_1 v_m */\n for (k = 0; k < j; ++k)\n {\n gsl_linalg_givens_gv(&vm.vector, k, k + 1,\n state->c[k], state->s[k]);\n }\n\n if (m < N)\n {\n /* Step 2g: find givens rotation J_m for v_m(m:m+1) */\n gsl_linalg_givens(gsl_vector_get(&vm.vector, j),\n gsl_vector_get(&vm.vector, j + 1),\n &c, &s);\n\n /* store givens rotation for later use */\n state->c[j] = c;\n state->s[j] = s;\n\n /* Step 2h: v_m <- J_m v_m */\n gsl_linalg_givens_gv(&vm.vector, j, j + 1, c, s);\n\n /* Step 2h: w <- J_m w */\n gsl_linalg_givens_gv(w, j, j + 1, c, s);\n }\n\n /*\n * Step 2i: R_m = [ R_{m-1}, v_m ] - already taken care\n * of due to our memory storage scheme\n */\n\n /* Step 2j: check residual w_{m+1} for convergence */\n normr = fabs(gsl_vector_get(w, j + 1));\n if (normr <= reltol)\n {\n /*\n * method has converged, break out of loop to compute\n * update to solution vector x\n */\n break;\n }\n }\n\n /*\n * At this point, we have either converged to a solution or\n * completed all maxit iterations. In either case, compute\n * an update to the solution vector x and test again for\n * convergence.\n */\n\n /* rewind m if we exceeded maxit iterations */\n if (m > maxit)\n m--;\n\n /* Step 3a: solve triangular system R_m y_m = w, in place */\n Rm = gsl_matrix_submatrix(H, 0, 1, m, m);\n ym = gsl_vector_subvector(w, 0, m);\n gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit,\n &Rm.matrix, &ym.vector);\n\n /*\n * Step 3b: update solution vector x; the loop below\n * uses a different but equivalent formulation from\n * Saad, algorithm 6.10, step 14; store Krylov projection\n * V_m y_m in 'r'\n */\n gsl_vector_set_zero(r);\n for (k = m; k > 0 && k--; )\n {\n double ymk = gsl_vector_get(&ym.vector, k);\n gsl_vector_view uk = gsl_matrix_subcolumn(H, k, k, N - k);\n gsl_vector_view rk = gsl_vector_subvector(r, k, N - k);\n\n /* r <- n_k e_k + r */\n gsl_vector_set(r, k, gsl_vector_get(r, k) + ymk);\n\n /* r <- P_k r */\n tau = gsl_vector_get(state->tau, k);\n gsl_linalg_householder_hv(tau, &uk.vector, &rk.vector);\n }\n\n /* x <- x + V_m y_m */\n gsl_vector_add(x, r);\n\n /* compute new residual r = b - A*x */\n gsl_vector_memcpy(r, b);\n gsl_spblas_dgemv(CblasNoTrans, -1.0, A, x, 1.0, r);\n normr = gsl_blas_dnrm2(r);\n\n if (normr <= reltol)\n status = GSL_SUCCESS; /* converged */\n else\n status = GSL_CONTINUE; /* not yet converged */\n\n /* store residual norm */\n state->normr = normr;\n\n return status;\n }\n} /* gmres_iterate() */\n\nstatic double\ngmres_normr(const void *vstate)\n{\n const gmres_state_t *state = (const gmres_state_t *) vstate;\n return state->normr;\n} /* gmres_normr() */\n\nstatic const gsl_splinalg_itersolve_type gmres_type =\n{\n \"gmres\",\n &gmres_alloc,\n &gmres_iterate,\n &gmres_normr,\n &gmres_free\n};\n\nconst gsl_splinalg_itersolve_type * gsl_splinalg_itersolve_gmres =\n &gmres_type;\n", "meta": {"hexsha": "bfdfa39b4fccb992a1ef0a15ea847deab42c2fa2", "size": 12954, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/splinalg/gmres.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/splinalg/gmres.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/splinalg/gmres.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 29.7110091743, "max_line_length": 81, "alphanum_fraction": 0.5631465184, "num_tokens": 3670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4141910113721943}} {"text": "// xi2bandpow.c\n// 31.08.2018\n// converts xi_+/-, xi_g+/x, and xi_gg to bandpowers\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"bjutils.h\"\n\n#define xi_pm_balance 0.5 // default weight for xi_+/- in P_E\n\nvoid xi_to_derived2pt();\ndouble K_bandpow_ee();\ndouble K_bandpow_ne();\ndouble K_bandpow_nn();\ndouble apod_upper();\ndouble apod_lower();\n\n\n\nint main(int argc, char *argv[])\n{\n int i,j;\n double dr,xip,xim,scale_terms,kernel;\n FILE *dat;\n char name[400],path[200],ident[200],outident[200];\n\n if (argc!=14) {\n printf(\"Syntax: %s\\n1: \\n2: \\n3: \\n4: \\n5: \\n6: \\n7: \\n8: \\n9: \\n10: \\n11: \\n12: \\n13: \\n\\n\",argv[0]);\n exit(-1);\n }\n sprintf(path,\"%s\",argv[1]);\n sprintf(ident,\"%s\",argv[2]);\n sprintf(outident,\"%s\",argv[3]);\n const int NR=atoi(argv[4]); \n const double angmin1=atof(argv[5]); \n const double angmax1=atof(argv[6]); \n const double angmin2=atof(argv[7]); \n const double angmax2=atof(argv[8]); \n const int NOUT=atoi(argv[9]); \n const double ellmin=atof(argv[10]); \n const double ellmax=atof(argv[11]); \n const int corrtype=atoi(argv[12]); \n const double logwidth=atof(argv[13]); \n\n\n // allocations\n if (corrtype>3) {\n printf(\"Error: incorrect input for correlation type!\\n\");\n exit(-1);\n }\n\n double *tin=bj_alloc(NR);\n double *ell_centre=bj_alloc(NOUT);\n double *ell_bound=bj_alloc(NOUT+1);\n double *weight=bj_alloc(NR);\n double *weight_xim=bj_alloc(NR);\n double *pfrac=bj_alloc(NOUT);\n\n gsl_vector *xi=gsl_vector_calloc(2*NR);\n gsl_vector *derived2pt=gsl_vector_calloc(2*NOUT);\n gsl_matrix *trans=gsl_matrix_calloc(2*NOUT,2*NR);\n gsl_matrix *xierr=gsl_matrix_calloc(2*NR,2*NR);\n gsl_matrix *derived2pterr=gsl_matrix_calloc(2*NOUT,2*NOUT);\n\n double logbinwidth=log(ellmax/ellmin)/(1.*NOUT); // output binning\n for (i=0;iangmin1)&&(tin[i]angmin2)&&(tin[i]angmin1*PI/10800.*exp(-logwidth/2.))||(corrtype==1 && tin[0]>angmin2*PI/10800.*exp(-logwidth/2.))) {\n printf(\"Error: correlation function not available out to min. range requested: %g > %g ; %g\\n\",tin[0]/PI*10800.,angmin1*exp(-logwidth/2.),angmin2*PI/10800.*exp(-logwidth/2.));\n exit(-1);\n }\n\n sprintf(name,\"%s/xi2bandpow_pmweights_%s.dat\",path,ident);\n if ((dat=fopen(name,\"r\"))==NULL) {\n printf(\"No file %s - use pmweight of %g instead.\\n\",name,xi_pm_balance);\n for (i=0;ilogxmax) {\n res=0.;\n }\n else {\n res=cos(PI/2.*(logx-logxmin)/(logxmax-logxmin));\n res=res*res; // cos^2\n }\n return(res);\n}\n\n\ndouble apod_lower(double x,double scale,double logwidth)\n{\n double res=0.0;\n double logx=log(x);\n double logxmin=log(scale)-logwidth/2.;\n double logxmax=log(scale)+logwidth/2.;\n\n if (logx<=logxmin) {\n res=0.;\n }\n else if (logx>logxmax) {\n res=1.;\n }\n else {\n res=cos(PI/2.*(logx-logxmax)/(logxmax-logxmin));\n res=res*res; // cos^2\n }\n return(res);\n}\n", "meta": {"hexsha": "fdd7013e5fb7e7d599d273aebbaa04a438c02344", "size": 9961, "ext": "c", "lang": "C", "max_stars_repo_path": "src/bandpowers/xi2bandpow.c", "max_stars_repo_name": "KiDS-WL/Cat_to_Obs_K1000_P1", "max_stars_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-18T12:58:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T08:54:29.000Z", "max_issues_repo_path": "src/bandpowers/xi2bandpow.c", "max_issues_repo_name": "KiDS-WL/Cat_to_Obs_K1000_P1", "max_issues_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bandpowers/xi2bandpow.c", "max_forks_repo_name": "KiDS-WL/Cat_to_Obs_K1000_P1", "max_forks_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T13:30:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T01:40:13.000Z", "avg_line_length": 30.2765957447, "max_line_length": 783, "alphanum_fraction": 0.6473245658, "num_tokens": 3448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4141061959530277}} {"text": "/* specfunc/bessel_K1.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n/* based on SLATEC besk1(), besk1e() */\n\n/* chebyshev expansions \n\n series for bk1 on the interval 0. to 4.00000d+00\n with weighted error 7.02e-18\n log weighted error 17.15\n significant figures required 16.73\n decimal places required 17.67\n\n series for ak1 on the interval 1.25000d-01 to 5.00000d-01\n with weighted error 6.06e-17\n log weighted error 16.22\n significant figures required 15.41\n decimal places required 16.83\n\n series for ak12 on the interval 0. to 1.25000d-01\n with weighted error 2.58e-17\n log weighted error 16.59\n significant figures required 15.22\n decimal places required 17.16\n*/\n\nstatic double bk1_data[11] = {\n 0.0253002273389477705,\n -0.3531559607765448760, \n -0.1226111808226571480, \n -0.0069757238596398643,\n -0.0001730288957513052,\n -0.0000024334061415659,\n -0.0000000221338763073,\n -0.0000000001411488392,\n -0.0000000000006666901,\n -0.0000000000000024274,\n -0.0000000000000000070\n};\n\nstatic cheb_series bk1_cs = {\n bk1_data,\n 10,\n -1, 1,\n 8\n};\n\nstatic double ak1_data[17] = {\n 0.27443134069738830, \n 0.07571989953199368,\n -0.00144105155647540,\n 0.00006650116955125,\n -0.00000436998470952,\n 0.00000035402774997,\n -0.00000003311163779,\n 0.00000000344597758,\n -0.00000000038989323,\n 0.00000000004720819,\n -0.00000000000604783,\n 0.00000000000081284,\n -0.00000000000011386,\n 0.00000000000001654,\n -0.00000000000000248,\n 0.00000000000000038,\n -0.00000000000000006\n};\nstatic cheb_series ak1_cs = {\n ak1_data,\n 16,\n -1, 1,\n 9\n};\n\nstatic double ak12_data[14] = {\n 0.06379308343739001,\n 0.02832887813049721,\n -0.00024753706739052,\n 0.00000577197245160,\n -0.00000020689392195,\n 0.00000000973998344,\n -0.00000000055853361,\n 0.00000000003732996,\n -0.00000000000282505,\n 0.00000000000023720,\n -0.00000000000002176,\n 0.00000000000000215,\n -0.00000000000000022,\n 0.00000000000000002\n};\nstatic cheb_series ak12_cs = {\n ak12_data,\n 13,\n -1, 1,\n 7\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_bessel_K1_scaled_e(const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x <= 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x < 2.0*GSL_DBL_MIN) {\n OVERFLOW_ERROR(result);\n }\n else if(x <= 2.0) {\n const double lx = log(x);\n const double ex = exp(x);\n int stat_I1;\n gsl_sf_result I1;\n gsl_sf_result c;\n cheb_eval_e(&bk1_cs, 0.5*x*x-1.0, &c);\n stat_I1 = gsl_sf_bessel_I1_e(x, &I1);\n result->val = ex * ((lx-M_LN2)*I1.val + (0.75 + c.val)/x);\n result->err = ex * (c.err/x + fabs(lx)*I1.err);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_I1;\n }\n else if(x <= 8.0) {\n const double sx = sqrt(x);\n gsl_sf_result c;\n cheb_eval_e(&ak1_cs, (16.0/x-5.0)/3.0, &c);\n result->val = (1.25 + c.val) / sx;\n result->err = c.err / sx;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n const double sx = sqrt(x);\n gsl_sf_result c;\n cheb_eval_e(&ak12_cs, 16.0/x-1.0, &c);\n result->val = (1.25 + c.val) / sx;\n result->err = c.err / sx;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\n\nint gsl_sf_bessel_K1_e(const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x <= 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x < 2.0*GSL_DBL_MIN) {\n OVERFLOW_ERROR(result);\n }\n else if(x <= 2.0) {\n const double lx = log(x);\n int stat_I1;\n gsl_sf_result I1;\n gsl_sf_result c;\n cheb_eval_e(&bk1_cs, 0.5*x*x-1.0, &c);\n stat_I1 = gsl_sf_bessel_I1_e(x, &I1);\n result->val = (lx-M_LN2)*I1.val + (0.75 + c.val)/x;\n result->err = c.err/x + fabs(lx)*I1.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_I1;\n }\n else {\n gsl_sf_result K1_scaled;\n int stat_K1 = gsl_sf_bessel_K1_scaled_e(x, &K1_scaled);\n int stat_e = gsl_sf_exp_mult_err_e(-x, 0.0,\n K1_scaled.val, K1_scaled.err,\n result);\n result->err = fabs(result->val) * (GSL_DBL_EPSILON*fabs(x) + K1_scaled.err/K1_scaled.val);\n return GSL_ERROR_SELECT_2(stat_e, stat_K1);\n }\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_K1_scaled(const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_K1_scaled_e(x, &result));\n}\n\ndouble gsl_sf_bessel_K1(const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_K1_e(x, &result));\n}\n", "meta": {"hexsha": "85317146756384653e10ae9432535b742c80175b", "size": 6121, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_K1.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_K1.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_K1.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 27.6968325792, "max_line_length": 94, "alphanum_fraction": 0.6028426728, "num_tokens": 2031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.41404849317847403}} {"text": "/* multifit/fsolver.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\ngsl_multifit_fsolver *\ngsl_multifit_fsolver_alloc (const gsl_multifit_fsolver_type * T, \n size_t n, size_t p) \n{\n int status;\n\n gsl_multifit_fsolver * s;\n\n if (n < p)\n {\n GSL_ERROR_VAL (\"insufficient data points, n < p\", GSL_EINVAL, 0);\n }\n\n s = (gsl_multifit_fsolver *) malloc (sizeof (gsl_multifit_fsolver));\n\n if (s == 0)\n {\n GSL_ERROR_VAL (\"failed to allocate space for multifit solver struct\",\n GSL_ENOMEM, 0);\n }\n\n s->x = gsl_vector_calloc (p);\n\n if (s->x == 0) \n {\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for x\", GSL_ENOMEM, 0);\n }\n\n s->f = gsl_vector_calloc (n);\n\n if (s->f == 0) \n {\n gsl_vector_free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for f\", GSL_ENOMEM, 0);\n }\n\n s->dx = gsl_vector_calloc (p);\n\n if (s->dx == 0) \n {\n gsl_vector_free (s->x);\n gsl_vector_free (s->f);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for dx\", GSL_ENOMEM, 0);\n }\n\n s->state = malloc (T->size);\n\n if (s->state == 0)\n {\n gsl_vector_free (s->dx);\n gsl_vector_free (s->x);\n gsl_vector_free (s->f);\n free (s); /* exception in constructor, avoid memory leak */\n \n GSL_ERROR_VAL (\"failed to allocate space for multifit solver state\",\n GSL_ENOMEM, 0);\n }\n\n s->type = T ;\n\n status = (s->type->alloc)(s->state, n, p);\n\n if (status != GSL_SUCCESS)\n {\n (s->type->free)(s->state);\n free (s->state);\n gsl_vector_free (s->dx);\n gsl_vector_free (s->x);\n gsl_vector_free (s->f);\n free (s); /* exception in constructor, avoid memory leak */\n \n GSL_ERROR_VAL (\"failed to set solver\", status, 0);\n }\n \n s->function = NULL;\n\n return s;\n}\n\nint\ngsl_multifit_fsolver_set (gsl_multifit_fsolver * s, \n gsl_multifit_function * f, \n const gsl_vector * x)\n{\n if (s->f->size != f->n)\n {\n GSL_ERROR (\"function size does not match solver\", GSL_EBADLEN);\n }\n\n if (s->x->size != x->size)\n {\n GSL_ERROR (\"vector length does not match solver\", GSL_EBADLEN);\n } \n \n s->function = f;\n gsl_vector_memcpy(s->x,x);\n \n return (s->type->set) (s->state, s->function, s->x, s->f, s->dx);\n}\n\nint\ngsl_multifit_fsolver_iterate (gsl_multifit_fsolver * s)\n{\n return (s->type->iterate) (s->state, s->function, s->x, s->f, s->dx);\n}\n\nvoid\ngsl_multifit_fsolver_free (gsl_multifit_fsolver * s)\n{\n RETURN_IF_NULL (s);\n (s->type->free) (s->state);\n free (s->state);\n gsl_vector_free (s->dx);\n gsl_vector_free (s->x);\n gsl_vector_free (s->f);\n free (s);\n}\n\nconst char *\ngsl_multifit_fsolver_name (const gsl_multifit_fsolver * s)\n{\n return s->type->name;\n}\n\ngsl_vector *\ngsl_multifit_fsolver_position (const gsl_multifit_fsolver * s)\n{\n return s->x;\n}\n", "meta": {"hexsha": "aab59c2f22466fe46ebe53bf1fa27379499ba2cf", "size": 3834, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/multifit/fsolver.c", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/multifit/fsolver.c", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/multifit/fsolver.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 24.2658227848, "max_line_length": 81, "alphanum_fraction": 0.6145018258, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4138900258037189}} {"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008 Gael Guennebaud \n//\n// Eigen is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3 of the License, or (at your option) any later version.\n//\n// Alternatively, you can redistribute it and/or\n// modify it under the terms of the GNU General Public License as\n// published by the Free Software Foundation; either version 2 of\n// the License, or (at your option) any later version.\n//\n// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License and a copy of the GNU General Public License along with\n// Eigen. If not, see .\n\n#ifndef EIGEN_GSL_HELPER\n#define EIGEN_GSL_HELPER\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Eigen {\n\ntemplate::IsComplex> struct GslTraits\n{\n typedef gsl_matrix* Matrix;\n typedef gsl_vector* Vector;\n static Matrix createMatrix(int rows, int cols) { return gsl_matrix_alloc(rows,cols); }\n static Vector createVector(int size) { return gsl_vector_alloc(size); }\n static void free(Matrix& m) { gsl_matrix_free(m); m=0; }\n static void free(Vector& m) { gsl_vector_free(m); m=0; }\n static void prod(const Matrix& m, const Vector& v, Vector& x) { gsl_blas_dgemv(CblasNoTrans,1,m,v,0,x); }\n static void cholesky(Matrix& m) { gsl_linalg_cholesky_decomp(m); }\n static void cholesky_solve(const Matrix& m, const Vector& b, Vector& x) { gsl_linalg_cholesky_solve(m,b,x); }\n static void eigen_symm(const Matrix& m, Vector& eval, Matrix& evec)\n {\n gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc(m->size1);\n Matrix a = createMatrix(m->size1, m->size2);\n gsl_matrix_memcpy(a, m);\n gsl_eigen_symmv(a,eval,evec,w);\n gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_VAL_ASC);\n gsl_eigen_symmv_free(w);\n free(a);\n }\n static void eigen_symm_gen(const Matrix& m, const Matrix& _b, Vector& eval, Matrix& evec)\n {\n gsl_eigen_gensymmv_workspace * w = gsl_eigen_gensymmv_alloc(m->size1);\n Matrix a = createMatrix(m->size1, m->size2);\n Matrix b = createMatrix(_b->size1, _b->size2);\n gsl_matrix_memcpy(a, m);\n gsl_matrix_memcpy(b, _b);\n gsl_eigen_gensymmv(a,b,eval,evec,w);\n gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_VAL_ASC);\n gsl_eigen_gensymmv_free(w);\n free(a);\n }\n\n template\n static void eigen_poly_solve(const EIGEN_VECTOR& poly, EIGEN_ROOTS& roots )\n {\n const int deg = poly.size()-1;\n double *z = new double[2*deg];\n double *a = new double[poly.size()];\n for( int i=0; i struct GslTraits\n{\n typedef gsl_matrix_complex* Matrix;\n typedef gsl_vector_complex* Vector;\n static Matrix createMatrix(int rows, int cols) { return gsl_matrix_complex_alloc(rows,cols); }\n static Vector createVector(int size) { return gsl_vector_complex_alloc(size); }\n static void free(Matrix& m) { gsl_matrix_complex_free(m); m=0; }\n static void free(Vector& m) { gsl_vector_complex_free(m); m=0; }\n static void cholesky(Matrix& m) { gsl_linalg_complex_cholesky_decomp(m); }\n static void cholesky_solve(const Matrix& m, const Vector& b, Vector& x) { gsl_linalg_complex_cholesky_solve(m,b,x); }\n static void prod(const Matrix& m, const Vector& v, Vector& x)\n { gsl_blas_zgemv(CblasNoTrans,gsl_complex_rect(1,0),m,v,gsl_complex_rect(0,0),x); }\n static void eigen_symm(const Matrix& m, gsl_vector* &eval, Matrix& evec)\n {\n gsl_eigen_hermv_workspace * w = gsl_eigen_hermv_alloc(m->size1);\n Matrix a = createMatrix(m->size1, m->size2);\n gsl_matrix_complex_memcpy(a, m);\n gsl_eigen_hermv(a,eval,evec,w);\n gsl_eigen_hermv_sort(eval, evec, GSL_EIGEN_SORT_VAL_ASC);\n gsl_eigen_hermv_free(w);\n free(a);\n }\n static void eigen_symm_gen(const Matrix& m, const Matrix& _b, gsl_vector* &eval, Matrix& evec)\n {\n gsl_eigen_genhermv_workspace * w = gsl_eigen_genhermv_alloc(m->size1);\n Matrix a = createMatrix(m->size1, m->size2);\n Matrix b = createMatrix(_b->size1, _b->size2);\n gsl_matrix_complex_memcpy(a, m);\n gsl_matrix_complex_memcpy(b, _b);\n gsl_eigen_genhermv(a,b,eval,evec,w);\n gsl_eigen_hermv_sort(eval, evec, GSL_EIGEN_SORT_VAL_ASC);\n gsl_eigen_genhermv_free(w);\n free(a);\n }\n};\n\ntemplate\nvoid convert(const MatrixType& m, gsl_matrix* &res)\n{\n// if (res)\n// gsl_matrix_free(res);\n res = gsl_matrix_alloc(m.rows(), m.cols());\n for (int i=0 ; i\nvoid convert(const gsl_matrix* m, MatrixType& res)\n{\n res.resize(int(m->size1), int(m->size2));\n for (int i=0 ; i\nvoid convert(const VectorType& m, gsl_vector* &res)\n{\n if (res) gsl_vector_free(res);\n res = gsl_vector_alloc(m.size());\n for (int i=0 ; i\nvoid convert(const gsl_vector* m, VectorType& res)\n{\n res.resize (m->size);\n for (int i=0 ; i\nvoid convert(const MatrixType& m, gsl_matrix_complex* &res)\n{\n res = gsl_matrix_complex_alloc(m.rows(), m.cols());\n for (int i=0 ; i\nvoid convert(const gsl_matrix_complex* m, MatrixType& res)\n{\n res.resize(int(m->size1), int(m->size2));\n for (int i=0 ; i\nvoid convert(const VectorType& m, gsl_vector_complex* &res)\n{\n res = gsl_vector_complex_alloc(m.size());\n for (int i=0 ; i\nvoid convert(const gsl_vector_complex* m, VectorType& res)\n{\n res.resize(m->size);\n for (int i=0 ; i\n#include \n#include \n#include \n#include \n#include \n#include \n\n// By Tania, October 2017\n\nusing namespace pdb;\n\n/* This class contains our current GMM model, that is:\n * - num of dimensions;\n * - weights: set of (prior) weights for each component\n * - means: mean for each component\n * - covars: covariance for each component\n * - inv_covars: inverse covariance for each component\n * - dets: determinant of each covariance matrix\n */\nclass GmmModel : public Object {\n\nprivate:\n int ndim = 0;\n int k = 0;\n Handle weights;\n Handle>> means; // k*ndim\n Handle>> covars; // k*ndim*ndim\n Handle>> inv_covars; // k*ndim*ndim\n Handle dets;\n\npublic:\n ENABLE_DEEP_COPY\n\n GmmModel() {}\n\n GmmModel(int k, int ndim) {\n std::cout << \"K= \" << k << std::endl;\n std::cout << \"ndim= \" << ndim << std::endl;\n\n this->ndim = ndim;\n this->k = k;\n\n this->weights = pdb::makeObject(k);\n this->dets = pdb::makeObject(k);\n\n this->means = pdb::makeObject>>();\n this->covars = pdb::makeObject>>();\n this->inv_covars = pdb::makeObject>>();\n\n for (int i = 0; i < k; i++) {\n this->weights->setDouble(i, 1.0 / k);\n this->means->push_back(makeObject(ndim));\n this->covars->push_back(makeObject(ndim * ndim));\n this->inv_covars->push_back(makeObject(ndim * ndim));\n }\n\n std::cout << \"Model created!\" << std::endl;\n }\n\n // this prints the first 10 elements of a DoubleVector\n void print_vector(Handle v) {\n int MAX = 10;\n if (v->size < MAX)\n MAX = v->size;\n for (int i = 0; i < MAX; i++) {\n std::cout << i << \": \" << v->getDouble(i) << \"; \";\n }\n std::cout << std::endl;\n }\n\n // Print current model\n void print() {\n // Print mean\n std::cout << \"**Current model**\" << std::endl;\n std::cout << \"Weights: \";\n print_vector(this->weights);\n for (int i = 0; i < k; i++) {\n std::cout << \"**Component \" << i << std::endl;\n std::cout << \"Mean: \";\n print_vector((*this->means)[i]);\n std::cout << \"Covar: \";\n print_vector((*this->covars)[i]);\n std::cout << \"Inv covars: \";\n print_vector((*this->inv_covars)[i]);\n }\n }\n\n int getNumK() { return k; }\n\n int getNDim() { return ndim; }\n\n double getWeight(int i) { return this->weights->getDouble(i); }\n\n void updateWeights(std::vector w) {\n for (int i = 0; i < k; i++) {\n this->weights->setDouble(i, w[i]);\n }\n std::cout << \"updated weights\";\n print_vector(this->weights);\n }\n\n void updateMeans(std::vector> &m) {\n for (int i = 0; i < k; i++) {\n std::cout << \"updated mean for comp \" << i << std::endl;\n\n double *mean = (*this->means)[i]->getRawData();\n for (int j = 0; j < ndim; j++) {\n mean[j] = m[i][j];\n }\n print_vector((*this->means)[i]);\n }\n }\n\n void updateCovars(std::vector> &c) {\n for (int i = 0; i < k; i++) {\n std::cout << \"updated covar for comp \" << i << std::endl;\n\n double *covar = (*this->covars)[i]->getRawData();\n\n for (int j = 0; j < (ndim * ndim); j++) {\n covar[j] = c[i][j];\n }\n print_vector((*this->covars)[i]);\n }\n\n // calcInvCovars();\n }\n\n // It calculates determinants and inverse covariances based on Cholesky\n // decomposition\n void calcInvCovars() {\n\n for (int i = 0; i < this->getNumK(); i++) {\n\n gsl_matrix_view covar =\n gsl_matrix_view_array((*covars)[i]->data->c_ptr(), ndim, ndim);\n gsl_matrix_view inv_covar =\n gsl_matrix_view_array((*inv_covars)[i]->data->c_ptr(), ndim, ndim);\n\n gsl_matrix_memcpy(&inv_covar.matrix, &covar.matrix);\n\n // gsl_permutation *p = gsl_permutation_alloc(ndim);\n\n gsl_linalg_cholesky_decomp(&inv_covar.matrix);\n\n // Calculate determinant -> logdet\n double ax = 0.0;\n for (int i = 0; i < ndim; i++) {\n ax += log(gsl_matrix_get(&inv_covar.matrix, i, i));\n }\n\n // Check for\n gsl_linalg_cholesky_invert(&inv_covar.matrix);\n\n dets->setDouble(i, ax);\n }\n }\n\n // It returns the rvalue, responsability, posterior probability of the\n // datapoint\n // for GMM component i\n double log_normpdf(int i, Handle inputData) {\n\n gsl_vector_view data =\n gsl_vector_view_array(inputData->data->c_ptr(), ndim);\n gsl_vector_view mean =\n gsl_vector_view_array((*means)[i]->data->c_ptr(), ndim);\n gsl_matrix_view covar =\n gsl_matrix_view_array((*covars)[i]->data->c_ptr(), ndim, ndim);\n gsl_matrix_view inv_covar =\n gsl_matrix_view_array((*inv_covars)[i]->data->c_ptr(), ndim, ndim);\n\n double ax, ay;\n int s;\n gsl_vector *ym;\n gsl_vector *datan = gsl_vector_alloc(ndim);\n\n ax = dets->getDouble(i);\n\n gsl_vector_memcpy(datan, &data.vector);\n gsl_vector_sub(datan, &mean.vector);\n\n ym = gsl_vector_alloc(ndim);\n gsl_blas_dsymv(CblasUpper, 1.0, &inv_covar.matrix, datan, 0.0, ym);\n gsl_blas_ddot(datan, ym, &ay);\n\n gsl_vector_free(ym);\n gsl_vector_free(datan);\n\n ay = -ax - 0.5 * ay;\n\n return ay;\n }\n\n // It calculates the sum of elements in vector v in log space\n // To do this, we extract the maximum factor (maxVal) from\n // all the values\n double logSumExp(double *v, size_t size) {\n\n double maxVal = v[0];\n double sum = 0;\n\n for (int i = 1; i < size; i++) {\n if (v[i] > maxVal) {\n maxVal = v[i];\n }\n }\n\n for (int i = 0; i < size; i++) {\n sum += exp(v[i] - maxVal);\n }\n\n return log(sum) + maxVal;\n }\n\n double logSumExp(DoubleVector &vector) {\n return logSumExp(vector.getRawData(), vector.size);\n }\n\n double logSumExp(Vector &vector) {\n return logSumExp(vector.c_ptr(), vector.size());\n }\n\n // It uses the partial results from the Aggregate to update the model\n\n double updateModel(GmmAggregateNewComp update) {\n\n const double MIN_COVAR = 1e-6;\n\n double *sumWeights = update.getSumWeights().c_ptr();\n double totalSumR = 0.0;\n\n for (int i = 0; i < k; i++) {\n totalSumR += sumWeights[i];\n }\n\n // Update weights -> weights = sumR/totalSumR\n gsl_vector_view gSumWeights = gsl_vector_view_array(sumWeights, k);\n gsl_vector_view gweights =\n gsl_vector_view_array((*weights).data->c_ptr(), k);\n gsl_vector_memcpy(&gweights.vector, &gSumWeights.vector);\n gsl_vector_scale(&gweights.vector, 1.0 / totalSumR);\n\n // Update Mean and Covar for each component\n for (int i = 0; i < k; i++) {\n\n // Update means -> means = 1/sumR * weightedX\n gsl_vector_view mean =\n gsl_vector_view_array((*means)[i]->data->c_ptr(), ndim);\n gsl_vector_view gsumMean =\n gsl_vector_view_array(update.getSumMean(i).c_ptr(), ndim);\n gsl_vector_memcpy(&mean.vector, &gsumMean.vector);\n gsl_vector_scale(&mean.vector, 1.0 / sumWeights[i]);\n\n // Update covars -> gsumCovarv / sumR - mean*mean^T\n\n gsl_vector_view gsumCovarv =\n gsl_vector_view_array(update.getSumCovar(i).c_ptr(), ndim * ndim);\n gsl_vector_scale(&gsumCovarv.vector, 1.0 / sumWeights[i]);\n gsl_matrix_view gsumCovarm =\n gsl_matrix_view_array(update.getSumCovar(i).c_ptr(), ndim, ndim);\n gsl_blas_dsyr(CblasUpper, -1.0, &mean.vector, &gsumCovarm.matrix);\n\n // Add constant to diagonal and copy lower triangular\n double d;\n for (int row = 0; row < ndim; row++) {\n d = gsl_matrix_get(&gsumCovarm.matrix, row, row);\n gsl_matrix_set(&gsumCovarm.matrix, row, row, d + MIN_COVAR);\n\n for (int col = row + 1; col < ndim; col++) {\n // matrix[j][i] = matrix[i][j]\n d = gsl_matrix_get(&gsumCovarm.matrix, row, col);\n gsl_matrix_set(&gsumCovarm.matrix, col, row, d);\n }\n }\n\n gsl_vector_view covar =\n gsl_vector_view_array((*covars)[i]->data->c_ptr(), ndim * ndim);\n gsl_vector_memcpy(&covar.vector, &gsumCovarv.vector);\n }\n\n // Finally, calculate inverse covariances and determinants to be used in the\n // next iteration\n calcInvCovars();\n\n return update.getLogLikelihood();\n }\n\n ~GmmModel() {}\n};\n\n#endif\n", "meta": {"hexsha": "0a723e111b71b105679ac5eabf0864ce5ee071d5", "size": 8678, "ext": "h", "lang": "C", "max_stars_repo_path": "src/sharedLibraries/headers/GMM/GmmModel.h", "max_stars_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB", "max_stars_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T16:14:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:06:04.000Z", "max_issues_repo_path": "src/sharedLibraries/headers/GMM/GmmModel.h", "max_issues_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB", "max_issues_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-28T23:17:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T23:17:14.000Z", "max_forks_repo_path": "src/sharedLibraries/headers/GMM/GmmModel.h", "max_forks_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB", "max_forks_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-18T02:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T19:28:19.000Z", "avg_line_length": 28.5460526316, "max_line_length": 80, "alphanum_fraction": 0.6154643927, "num_tokens": 2561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.41371204065086437}} {"text": "/**\n *\n * @file example_strsmpl.c\n *\n * PLASMA testing routines\n * PLASMA is a software package provided by Univ. of Tennessee,\n * Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @brief Example for solving a system of linear equations using \n * LU factorization and PLASMA_strsmpl routine\n *\n * @version 2.6.0\n * @author Bilel Hadri\n * @date 2010-11-15\n * @generated s Tue Jan 7 11:45:21 2014\n *\n **/\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nint check_solution(int, int , float *, int, float *, float *, int);\n\nint IONE=1;\nint ISEED[4] = {0,0,0,1}; /* initial seed for slarnv() */\n\nint main ()\n{\n\n int cores = 2;\n int N = 10;\n int LDA = 10;\n int NRHS = 5;\n int LDB = 10;\n int info;\n int info_solution;\n int i,j;\n int LDAxN = LDA*N;\n int LDBxNRHS = LDB*NRHS;\n\n float *A1 = (float *)malloc(LDA*N*(sizeof*A1));\n float *A2 = (float *)malloc(LDA*N*(sizeof*A2));\n float *B1 = (float *)malloc(LDB*NRHS*(sizeof*B1));\n float *B2 = (float *)malloc(LDB*NRHS*(sizeof*B2));\n PLASMA_desc *L;\n int *IPIV;\n\n /* Check if unable to allocate memory */\n if ((!A1)||(!A2)||(!B1)||(!B2)){\n printf(\"Out of Memory \\n \");\n return EXIT_SUCCESS;\n }\n\n /*Plasma Initialize*/\n PLASMA_Init(cores);\n printf(\"-- PLASMA is initialized to run on %d cores. \\n\",cores);\n\n /* Initialize A1 and A2 Matrix */\n LAPACKE_slarnv_work(IONE, ISEED, LDAxN, A1);\n for ( i = 0; i < N; i++)\n for ( j = 0; j < N; j++)\n A2[LDA*j+i] = A1[LDA*j+i];\n\n /* Initialize B1 and B2 */\n LAPACKE_slarnv_work(IONE, ISEED, LDBxNRHS, B1);\n for ( i = 0; i < N; i++)\n for ( j = 0; j < NRHS; j++)\n B2[LDB*j+i] = B1[LDB*j+i];\n\n\n /* Allocate L and IPIV */\n info = PLASMA_Alloc_Workspace_sgetrf_incpiv(N, N, &L, &IPIV);\n\n /* LU factorization of the matrix A */\n info = PLASMA_sgetrf_incpiv(N, N, A2, LDA, L, IPIV);\n\n /* Solve the problem */\n info = PLASMA_strsmpl(N, NRHS, A2, LDA, L, IPIV, B2, LDB);\n info = PLASMA_strsm(PlasmaLeft, PlasmaUpper, PlasmaNoTrans, PlasmaNonUnit, \n N, NRHS, (float)1.0, A2, LDA, B2, LDB);\n\n /* Check the solution */\n info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB);\n\n if ((info_solution != 0)|(info != 0))\n printf(\"-- Error in SGETRS example ! \\n\");\n else\n printf(\"-- Run of SGETRS example successful ! \\n\");\n\n free(A1); free(A2); free(B1); free(B2); free(IPIV); free(L);\n\n PLASMA_Finalize();\n\n return EXIT_SUCCESS;\n}\n\n/*------------------------------------------------------------------------\n * Check the accuracy of the solution of the linear system\n */\n\nint check_solution(int N, int NRHS, float *A1, int LDA, float *B1, float *B2, int LDB)\n{\n int info_solution;\n float Rnorm, Anorm, Xnorm, Bnorm;\n float alpha, beta;\n float *work = (float *)malloc(N*sizeof(float));\n float eps;\n\n eps = LAPACKE_slamch_work('e');\n\n alpha = 1.0;\n beta = -1.0;\n\n Xnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B2, LDB, work);\n Anorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, A1, LDA, work);\n Bnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B1, LDB, work);\n\n cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, N, NRHS, N, (alpha), A1, LDA, B2, LDB, (beta), B1, LDB);\n Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B1, LDB, work);\n\n printf(\"============\\n\");\n printf(\"Checking the Residual of the solution \\n\");\n printf(\"-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \\n\",Rnorm/((Anorm*Xnorm+Bnorm)*N*eps));\n\n if ( isnan(Rnorm/((Anorm*Xnorm+Bnorm)*N*eps)) || (Rnorm/((Anorm*Xnorm+Bnorm)*N*eps) > 10.0) ){\n printf(\"-- The solution is suspicious ! \\n\");\n info_solution = 1;\n }\n else{\n printf(\"-- The solution is CORRECT ! \\n\");\n info_solution = 0;\n }\n\n free(work);\n\n return info_solution;\n}\n", "meta": {"hexsha": "cfe8fe41f5af12e20920ee06af4d6fc24f90046f", "size": 4168, "ext": "c", "lang": "C", "max_stars_repo_path": "examples/example_strsmpl.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/example_strsmpl.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example_strsmpl.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9444444444, "max_line_length": 115, "alphanum_fraction": 0.587571977, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.41371204065086437}} {"text": "#include \n#include \n\n#ifdef _MSC_VER\n# define inline __inline\n#endif\n\n\n/*\n * General Cholesky Delete.\n * Remove an element from the cholesky factorization\n * m = columns\n * n = rows\n *\n * TODO: put transpose as an option\n */\nstatic inline void cholesky_delete_dbl(int m, int n, double *L, int go_out)\n{\n double c, s;\n\n /* delete row go_out */\n double *L1 = L + (go_out * m);\n int i;\n for (i = go_out; i < n - 1; ++i) {\n cblas_dcopy (i + 2, L1 + m , 1, L1, 1);\n L1 += m;\n }\n\n L1 = L + (go_out * m);\n for (i=go_out; i < n - 1; ++i) {\n\n cblas_drotg(L1 + i, L1 + i + 1, &c, &s);\n if (L1[i] < 0) {\n /* Diagonals cannot be negative */\n L1[i] = fabs(L1[i]);\n c = -c;\n s = -s;\n }\n L1[i+1] = 0.; /* just for cleanup */\n L1 += m;\n\n cblas_drot(n - (i + 2), L1 + i, m, L1 + i + 1,\n m, c, s);\n }\n}\n\n\nstatic inline void cholesky_delete_flt(int m, int n, float *L, int go_out)\n{\n float c, s;\n\n /* delete row go_out */\n float *L1 = L + (go_out * m);\n int i;\n for (i = go_out; i < n - 1; ++i) {\n cblas_scopy (i + 2, L1 + m , 1, L1, 1);\n L1 += m;\n }\n\n L1 = L + (go_out * m);\n for (i=go_out; i < n - 1; ++i) {\n\n cblas_srotg(L1 + i, L1 + i + 1, &c, &s);\n if (L1[i] < 0) {\n /* Diagonals cannot be negative */\n L1[i] = fabsf(L1[i]);\n c = -c;\n s = -s;\n }\n L1[i+1] = 0.; /* just for cleanup */\n L1 += m;\n\n cblas_srot(n - (i + 2), L1 + i, m, L1 + i + 1,\n m, c, s);\n }\n}\n", "meta": {"hexsha": "6e20a2b003ed72af3c03d740b966b463b3078a0b", "size": 1654, "ext": "h", "lang": "C", "max_stars_repo_path": "summary/sumy/sklearn/utils/src/cholesky_delete.h", "max_stars_repo_name": "WangWenjun559/MITS", "max_stars_repo_head_hexsha": "8d7ace2b3b2a58fb33af225c2997106d9402aaf5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6989.0, "max_stars_repo_stars_event_min_datetime": "2017-07-18T06:23:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:58:36.000Z", "max_issues_repo_path": "summary/sumy/sklearn/utils/src/cholesky_delete.h", "max_issues_repo_name": "WangWenjun559/MITS", "max_issues_repo_head_hexsha": "8d7ace2b3b2a58fb33af225c2997106d9402aaf5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1978.0, "max_issues_repo_issues_event_min_datetime": "2017-07-18T09:17:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:28:43.000Z", "max_forks_repo_path": "summary/sumy/sklearn/utils/src/cholesky_delete.h", "max_forks_repo_name": "WangWenjun559/MITS", "max_forks_repo_head_hexsha": "8d7ace2b3b2a58fb33af225c2997106d9402aaf5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1228.0, "max_forks_repo_forks_event_min_datetime": "2017-07-18T09:03:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:57:40.000Z", "avg_line_length": 21.4805194805, "max_line_length": 75, "alphanum_fraction": 0.430471584, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.41354305496693555}} {"text": "#include \"stdio.h\"\n#include \"gsl/gsl_integration.h\"\n#include \"gsl/gsl_errno.h\"\n//include \"limber.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// The integrated C_ell are in general allowed to be zero or negative if\n// they describe cross-correlations. We use these statuses to describe\n// errors where a log was requested also.\n// LIMBER_STATUS_NEGATIVE is probably always an error\n// but LIMBER_STATUS_ZERO is not necessarily\n#define LIMBER_STATUS_OK 0\n#define LIMBER_STATUS_ZERO 1\n#define LIMBER_STATUS_NEGATIVE 2\n#define LIMBER_STATUS_ERROR 3\n\n// These are the options you can set for\n// the Limber integrator.\ntypedef struct cl_config{\n\tint n_ell; // Number of ell values you want in the spline\n\tint * ell; // The chosen ell values you want\n\tdouble prefactor; //Scaling prefactor\n int status; // did everything go okay?\n double delta_range_factor;\n double log_nu_range;\n double absolute_tolerance;\n double relative_tolerance;\n} cl_config;\n\nint cl_integral(cl_config * config, gsl_spline * WX_red, \n\t\t\t gsl_spline * WY_red, gsl_spline2d * P, gsl_spline * D_chi,\n\t\t\t double * cl_out, double * cl_err_out);", "meta": {"hexsha": "3590a1ed3625484bc3d33c9c60c659ed4f857f7c", "size": 1294, "ext": "h", "lang": "C", "max_stars_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.h", "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_issues_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.h", "max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.h", "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "avg_line_length": 34.0526315789, "max_line_length": 72, "alphanum_fraction": 0.756568779, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4133613479667005}} {"text": "/* ode-initval/rkf45.c\n * \n * Copyright (C) 2001 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Runge-Kutta-Fehlberg 4(5)*/\n\n#include \n#include \n#include \n#include \n#include \"gsl_odeiv.h\"\n\n#include \"odeiv_util.h\"\n\n/* Runge-Kutta-Fehlberg constants */\nstatic const double ah[] = { 1.0/4.0, 3.0/8.0, 12.0/13.0, 1.0, 1.0/2.0 };\n\nstatic const double b3[] = { 3.0/32.0, 9.0/32.0 };\n\nstatic const double b4[] = { 1932.0/2197.0, -7200.0/2197.0, 7296.0/2197.0};\n\nstatic const double b5[] = { 8341.0/4104.0, -32832.0/4104.0, 29440.0/4104.0, -845.0/4104.0};\n\nstatic const double b6[] = { -6080.0/20520.0, 41040.0/20520.0, -28352.0/20520.0, 9295.0/20520.0, -5643.0/20520.0};\n\nstatic const double c1 = 902880.0/7618050.0;\nstatic const double c3 = 3953664.0/7618050.0;\nstatic const double c4 = 3855735.0/7618050.0;\nstatic const double c5 = -1371249.0/7618050.0;\nstatic const double c6 = 277020.0/7618050.0;\n\n\nstatic const double ec[] = { 0.0,\n 1.0 / 360.0,\n 0.0,\n -128.0 / 4275.0,\n -2197.0 / 75240.0,\n 1.0 / 50.0,\n 2.0 / 55.0\n};\n\ntypedef struct\n{\n double *k1;\n double *k2;\n double *k3;\n double *k4;\n double *k5;\n double *k6;\n double *y0;\n double *ytmp;\n}\nrkf45_state_t;\n\nstatic void *\nrkf45_alloc (size_t dim)\n{\n rkf45_state_t *state = (rkf45_state_t *) malloc (sizeof (rkf45_state_t));\n\n if (state == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for rkf45_state\", GSL_ENOMEM);\n }\n\n state->k1 = (double *) malloc (dim * sizeof (double));\n\n if (state->k1 == 0)\n {\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k1\", GSL_ENOMEM);\n }\n\n state->k2 = (double *) malloc (dim * sizeof (double));\n\n if (state->k2 == 0)\n {\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k2\", GSL_ENOMEM);\n }\n\n state->k3 = (double *) malloc (dim * sizeof (double));\n\n if (state->k3 == 0)\n {\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k3\", GSL_ENOMEM);\n }\n\n state->k4 = (double *) malloc (dim * sizeof (double));\n\n if (state->k4 == 0)\n {\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k4\", GSL_ENOMEM);\n }\n\n state->k5 = (double *) malloc (dim * sizeof (double));\n\n if (state->k5 == 0)\n {\n free (state->k4);\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k5\", GSL_ENOMEM);\n }\n\n state->k6 = (double *) malloc (dim * sizeof (double));\n\n if (state->k6 == 0)\n {\n free (state->k5);\n free (state->k4);\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k6\", GSL_ENOMEM);\n }\n\n state->y0 = (double *) malloc (dim * sizeof (double));\n\n if (state->y0 == 0)\n {\n free (state->k6);\n free (state->k5);\n free (state->k4);\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y0\", GSL_ENOMEM);\n }\n\n state->ytmp = (double *) malloc (dim * sizeof (double));\n\n if (state->ytmp == 0)\n {\n free (state->y0);\n free (state->k6);\n free (state->k5);\n free (state->k4);\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for ytmp\", GSL_ENOMEM);\n }\n\n return state;\n}\n\n\nstatic int\nrkf45_apply (void *vstate,\n\t size_t dim,\n\t double t,\n\t double h,\n\t double y[],\n\t double yerr[],\n\t const double dydt_in[],\n\t double dydt_out[], const gsl_odeiv_system * sys)\n{\n rkf45_state_t *state = (rkf45_state_t *) vstate;\n\n size_t i;\n int status = 0;\n\n double *const k1 = state->k1;\n double *const k2 = state->k2;\n double *const k3 = state->k3;\n double *const k4 = state->k4;\n double *const k5 = state->k5;\n double *const k6 = state->k6;\n double *const ytmp = state->ytmp;\n\n /* k1 step */\n if (dydt_in != NULL)\n {\n DBL_MEMCPY (k1, dydt_in, dim);\n }\n else\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t, y, k1);\n GSL_STATUS_UPDATE (&status, s);\n }\n\n for (i = 0; i < dim; i++)\n ytmp[i] = y[i] + ah[0] * h * k1[i];\n\n /* k2 step */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + ah[0] * h, ytmp, k2);\n GSL_STATUS_UPDATE (&status, s);\n }\n for (i = 0; i < dim; i++)\n ytmp[i] = y[i] + h * (b3[0] * k1[i] + b3[1] * k2[i]);\n\n /* k3 step */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + ah[1] * h, ytmp, k3);\n GSL_STATUS_UPDATE (&status, s);\n }\n for (i = 0; i < dim; i++)\n ytmp[i] = y[i] + h * (b4[0] * k1[i] + b4[1] * k2[i] + b4[2] * k3[i]);\n\n /* k4 step */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + ah[2] * h, ytmp, k4);\n GSL_STATUS_UPDATE (&status, s);\n }\n for (i = 0; i < dim; i++)\n ytmp[i] =\n y[i] + h * (b5[0] * k1[i] + b5[1] * k2[i] + b5[2] * k3[i] +\n\t\t b5[3] * k4[i]);\n\n /* k5 step */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + ah[3] * h, ytmp, k5);\n GSL_STATUS_UPDATE (&status, s);\n }\n for (i = 0; i < dim; i++)\n ytmp[i] =\n y[i] + h * (b6[0] * k1[i] + b6[1] * k2[i] + b6[2] * k3[i] +\n\t\t b6[3] * k4[i] + b6[4] * k5[i]);\n\n /* k6 step and final sum */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + ah[4] * h, ytmp, k6);\n GSL_STATUS_UPDATE (&status, s);\n }\n\n for (i = 0; i < dim; i++)\n {\n const double d_i = c1 * k1[i] + c3 * k3[i] + c4 * k4[i] + c5 * k5[i] + c6 * k6[i];\n y[i] += h * d_i;\n if (dydt_out != NULL)\n\tdydt_out[i] = d_i;\n }\n\n /* difference between 4th and 5th order */\n for (i = 0; i < dim; i++)\n yerr[i] =\n h * (ec[1] * k1[i] + ec[3] * k3[i] + ec[4] * k4[i] + ec[5] * k5[i] +\n\t ec[6] * k6[i]);\n\n return status;\n}\n\n\nstatic int\nrkf45_reset (void *vstate, size_t dim)\n{\n rkf45_state_t *state = (rkf45_state_t *) vstate;\n\n DBL_ZERO_MEMSET (state->k1, dim);\n DBL_ZERO_MEMSET (state->k2, dim);\n DBL_ZERO_MEMSET (state->k3, dim);\n DBL_ZERO_MEMSET (state->k4, dim);\n DBL_ZERO_MEMSET (state->k5, dim);\n DBL_ZERO_MEMSET (state->k6, dim);\n DBL_ZERO_MEMSET (state->ytmp, dim);\n\n return GSL_SUCCESS;\n}\n\nstatic unsigned int\nrkf45_order (void *vstate)\n{\n rkf45_state_t *state = (rkf45_state_t *) vstate;\n state = 0; /* prevent warnings about unused parameters */\n return 5;\n}\n\nstatic void\nrkf45_free (void *vstate)\n{\n rkf45_state_t *state = (rkf45_state_t *) vstate;\n\n free (state->ytmp);\n free (state->y0);\n free (state->k6);\n free (state->k5);\n free (state->k4);\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n}\n\nstatic const gsl_odeiv_step_type rkf45_type = { \"rkf45\",\t/* name */\n 1,\t\t\t\t/* can use dydt_in */\n 0,\t\t\t\t/* gives exact dydt_out */\n &rkf45_alloc,\n &rkf45_apply,\n &rkf45_reset,\n &rkf45_order,\n &rkf45_free\n};\n\nconst gsl_odeiv_step_type *gsl_odeiv_step_rkf45 = &rkf45_type;\n", "meta": {"hexsha": "d699f0578599f94cba52a0a99b2bc5740c8e4ae6", "size": 7673, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/ode-initval/rkf45.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/ode-initval/rkf45.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/ode-initval/rkf45.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 23.6820987654, "max_line_length": 114, "alphanum_fraction": 0.5794343803, "num_tokens": 2809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.41325932684134725}} {"text": "/* Copyright (c) 2014, Giuseppe Argentieri \n\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n * \n */\n\n/*\n * =====================================================================================\n *\n * Filename: Reg_sc.c\n *\n * Description: \n *\n * Version: 1.0\n * Created: 21/04/2014 12:27:24\n * Revision: none\n * Compiler: gcc\n *\n * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it\n * Organization: Università degli Studi di Trieste\n *\n * =====================================================================================\n */\n\n/*\n Re g_sc is made of 4 integrands: 2 with principal values and 2 without.\n\n The common factor function is k_func = alpha*k*exp(-k/omega_c)/tanh(b*k/2) \n\n The poles are in (omega1-O) and (omega1+O) \n\n The sign of the four fractions\n\n 1/(k+(omega1+O)) , 1/(k+(omega1-O)) , 1/(k-(omega1-O)) , 1/(k-(omega1+O))\n\n are\n\n + , - , + , -\n*/\n\n#include \n\n#include \"funcs.h\"\n#include \n\n/* \n * === FUNCTION ======================================================================\n * Name: k_func\n * Description: Common integrand factor\n * =====================================================================================\n */\ndouble k_func ( double k, void* params )\n{\n\n\t/* Copying parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1, alpha ;\n\tassign_p( pars, &o_c, &b, &O, &o_1 ) ;\n\talpha = pars->alpha ;\n\n\tdouble temp = alpha*k*exp(-k/o_c) ;\n\tdouble val = temp/tanh(b*k/2) ;\n\t\n\treturn val;\n}\t\t/* ----- end of function k_func ----- */\n\n\n/* \n * === FUNCTION ======================================================================\n * Name: k_func_1\n * Description: First integrand: k_func/(k+(omega1+O))\n * =====================================================================================\n */\ndouble k_func_1 ( double k, void* params )\n{\n\t/* Copying parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p( pars, &o_c, &b, &O, &o_1 ) ;\n\n\t/* Invoking k_func and returning value */\n\tdouble v , v1 ;\n\tv = k_func( k, pars ) ;\n\tv1 = v/(k+(o_1+O)) ;\n\n\treturn v1 ;\n}\t\t/* ----- end of function k_func_1 ----- */\n\n/* \n * === FUNCTION ======================================================================\n * Name: first_int\n * Description: Integrating k_func/(k+(omega1+O))\n * =====================================================================================\n */\nint first_int ( double* val, double* error, void* params )\n{\n\t/* Copying parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p( pars, &o_c, &b, &O, &o_1 ) ;\n\t\n\t/* Allocating workspace for integration */\n\tgsl_integration_workspace* first_int_ws =\n\t\tgsl_integration_workspace_alloc(WS_SZ) ;\n\n\tgsl_function F ;\n\tF.function = &k_func_1 ;\n\tF.params = pars ;\n\n\t/* Integration over (0,+Infinity) */\n\tdouble res, err ;\n\tint status = gsl_integration_qagiu( &F, 0, 1e-9, 1e-3, WS_SZ, first_int_ws, \n\t\t\t&res, &err ) ;\n\n\t*val = res ; *error = err ;\n\n\tgsl_integration_workspace_free(first_int_ws) ;\n\treturn status;\n}\t\t/* ----- end of function first_int ----- */\n\n\n/* \n * FUNCTION \n * Name: k_func_2\n * Description: Second integrand: k_func/(k+omega1-O)\n * \n */\ndouble k_func_2 ( double k , void* params )\n{\n\t/* Copying parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p( pars, &o_c, &b, &O, &o_1 ) ;\n\t\n\t/* Invoking k_func and returning value */\n\tdouble v, v2 ;\n\tv = k_func( k, pars ) ;\n\tv2 = v/(k+(o_1-O)) ;\n\n\treturn v2;\n}\t\t/* ----- end of function k_func_2 ----- */\n\n\n/* \n * FUNCTION \n * Name: second_int\n * Description: Integration k_func/(k+(omega1-O))\n * \n */\nint second_int ( double* val, double* error, void* params )\n{\n\t/* Copying parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p( pars, &o_c, &b, &O, &o_1 ) ;\n\n\t/* Allocating workspace for integration */\n\tgsl_integration_workspace* second_int_ws =\n\t\tgsl_integration_workspace_alloc(WS_SZ) ;\n\n\tgsl_function F;\n\tF.function = &k_func_2 ;\n\tF.params = pars ;\n\n\tdouble res, err ;\n\tint status = gsl_integration_qagiu( &F, 0, 1e-9, 1e-3, WS_SZ, second_int_ws,\n\t\t\t&res, &err ) ;\n\t*val = res ; *error = err ;\n\n\tgsl_integration_workspace_free(second_int_ws) ;\n\n\treturn status;\n}\t\t/* ----- end of function second_int ----- */\n\n\n/* \n * FUNCTION \n * Name: k_func_3\n * Description: k_func/(k-(omega1-O)) to be integrated on the tail +inf\n * \n */\ndouble k_func_3 ( double k, void* params )\n{\n\t/* Copying parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p( pars, &o_c, &b, &O, &o_1 ) ;\n\n\tdouble temp , val ;\n\ttemp = k_func( k, pars ) ;\n\tval = temp/(k-(o_1-O)) ; \n\n\treturn val;\n}\t\t/* ----- end of function k_func_3 ----- */\n\n\n/* \n * FUNCTION \n * Name: third_int\n * Description: Integration of the p.v. k_func/(k-(omega1-O))\n * \n */\nint third_int ( double* val, double* err, void* params )\n{\n\t/* Copying parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p( pars, &o_c, &b, &O, &o_1 ) ;\n\n\t/* Integration of the p.v. */\n\tgsl_function F ;\n\tF.function = &k_func ;\n\tF.params = pars ;\n\n\tgsl_integration_workspace* third_int_ws =\n\t\tgsl_integration_workspace_alloc(WS_SZ) ;\n\n\tdouble v1 , err1 ;\n\tint status1 = gsl_integration_qawc( &F, (o_1-O)/2, 3*(o_1-O)/2, o_1-O, \n\t\t\t1e-9, 1e-3, WS_SZ, third_int_ws, &v1, &err1 ) ;\n\n\tgsl_integration_workspace_free(third_int_ws) ;\n\n\t/* Integration to +infinity */\n\tgsl_function G ;\n\tG.function = &k_func_3 ;\n\tG.params = pars ;\n\n\tgsl_integration_workspace* third_int_ws_2 =\n\t\tgsl_integration_workspace_alloc(WS_SZ) ;\n\n\tdouble v2, err2 ;\n\tint status2 = gsl_integration_qagiu( &G, 3*(o_1-O)/2, 1e-9, 1e-3, WS_SZ,\n\t\t\tthird_int_ws_2, &v2, &err2 ) ;\n\n\tgsl_integration_workspace_free(third_int_ws_2) ;\n\n\t/* Integration on ( 0, (o_1-O)/2 ) */\n\tgsl_integration_workspace* third_int_ws_3 = \n\t\tgsl_integration_workspace_alloc(WS_SZ) ;\n\n\tgsl_function H ;\n\tH.function = &k_func_3 ;\n\tH.params = pars ;\n\n\tdouble v3, err3 ;\n\tint status3 = gsl_integration_qag( &H, 0, (o_1-O)/2, 1e-9, 1e-3, WS_SZ, 6,\n\t\t\tthird_int_ws_3, &v3, &err3 ) ;\n\n\tgsl_integration_workspace_free(third_int_ws_3) ;\n\n\t*val = v1 + v2 + v3 ; *err = err1 + err2 + err3 ;\n\n\treturn status1 + status2 + status3 ;\n}\t\t/* ----- end of function third_int ----- */\n\n\n/* \n * FUNCTION \n * Name: k_func_4\n * Description: k_func/(k-(omega1+O))\n * \n */\ndouble k_func_4 ( double k, void* params )\n{\n\t/* Copying parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p( pars, &o_c, &b, &O, &o_1 ) ;\n\t\n\tdouble temp , val ;\n\ttemp = k_func( k, pars ) ;\n\tval = temp/(k-(o_1+O)) ; \n\n\treturn val;\n}\t\t/* ----- end of function k_func_4 ----- */\n\n\n/* \n * FUNCTION \n * Name: fourth_integ\n * Description: Integration of the p.v. kfunc/(k-(omega1+O))\n * \n */\nint fourth_int ( double* val, double* err, void* params )\n{\n\t/* Copying parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p( pars, &o_c, &b, &O, &o_1 ) ;\n\n\t/* Integration of the p.v. */\n\tgsl_function F ;\n\tF.function = &k_func ;\n\tF.params = pars ;\n\n\tgsl_integration_workspace* fourth_int_ws =\n\t\tgsl_integration_workspace_alloc(WS_SZ) ;\n\n\tdouble v1 , err1 ;\n\tint status1 = gsl_integration_qawc( &F, (o_1+O)/2, 3*(o_1+O)/2, o_1+O, \n\t\t\t1e-9, 1e-3, WS_SZ, fourth_int_ws, &v1, &err1 ) ;\n\n\tgsl_integration_workspace_free(fourth_int_ws) ;\n\n\t/* Integration to +infinity */\n\tgsl_function G ;\n\tG.function = &k_func_4 ;\n\tG.params = pars ;\n\n\tgsl_integration_workspace* fourth_int_ws_2 =\n\t\tgsl_integration_workspace_alloc(WS_SZ) ;\n\n\tdouble v2, err2 ;\n\tint status2 = gsl_integration_qagiu( &G, 3*(o_1+O)/2, 1e-9, 1e-3, WS_SZ,\n\t\t\tfourth_int_ws_2, &v2, &err2 ) ;\n\n\tgsl_integration_workspace_free(fourth_int_ws_2) ;\n\n\t/* Integration on ( 0 , (O+o_1)/2 ) */\n\tgsl_integration_workspace* fourth_int_ws_3 =\n\t\tgsl_integration_workspace_alloc(WS_SZ) ;\n\n\tgsl_function K ;\n\tK.function = &k_func_4 ;\n\tK.params = pars ;\n\tdouble v3, err3 ;\n\n\tint status3 = gsl_integration_qag( &K, 0, (O+o_1)/2, 1e-9, 1e-3, WS_SZ, \n\t\t\tGSL_INTEG_GAUSS61, fourth_int_ws_3, &v3, &err3 ) ;\n\n\tgsl_integration_workspace_free(fourth_int_ws_3) ;\n\n\t*val = v1 + v2 + v3 ; *err = err1 + err2 + err3 ;\n\n\treturn status1 + status2 + status3;\n}\t\t/* ----- end of function fourth_integ ----- */\n\n\n/* \n * FUNCTION \n * Name: re_gsc\n * Description: \n * \n */\nint re_gsc ( double* result, double* error, void* params )\n{\n\t/* Copying parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p( pars, &o_c, &b, &O, &o_1 ) ;\n\n\tdouble v1, v2, v3, v4, err1, err2, err3, err4 ;\n\tint status = first_int( &v1, &err1, pars ) + second_int( &v2, &err2, pars )\n\t\t+ third_int( &v3, &err3, pars ) + fourth_int( &v4, &err4, pars ) ;\n\t*result = -(v1 - v2 + v3 - v4)/4.0 ;\n\t*error = (err1 + err2 + err3 + err4)/4.0 ;\n\n\treturn status;\n}\t\t/* ----- end of function re_gsc ----- */\n\n/* \n * FUNCTION \n * Name: re_gcs\n * Description: Re g_cs is the same of Re g_sc but with O and o_1 exchanged. \n * \t\t Therefore the signs are\n *\n * \t\t + , + , - , -\n * \n */\nint re_gcs ( double* result, double* error, void* params )\n{\n\t/* Copying parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p( pars, &o_c, &b, &O, &o_1 ) ;\n\n\tdouble v1, v2, v3, v4, err1, err2, err3, err4 ;\n\tint status = first_int( &v1, &err1, pars ) + second_int( &v2, &err2, pars )\n\t\t+ third_int( &v3, &err3, pars ) + fourth_int( &v4, &err4, pars ) ;\n\n\t*result = -(v1 + v2 - v3 - v4)/4 ; *error = (err1 + err2 + err3 + err4)/4 ;\n\n\treturn status;\n}\t\t/* ----- end of function re_gcs ----- */\n", "meta": {"hexsha": "1dfac77b736d30a78678934d3e1cfc5e14aec906", "size": 11224, "ext": "c", "lang": "C", "max_stars_repo_path": "Reg_sc.c", "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Reg_sc.c", "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Reg_sc.c", "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5098039216, "max_line_length": 88, "alphanum_fraction": 0.5981824661, "num_tokens": 3450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.41315028726884373}} {"text": "/**\n * Various binning and weighting routines for aperture pixel tables.\n *\n*/\n\n#include \n\n#include \n#include \n\n#include \"spc_trace_functions.h\"\n#include \"aXe_utils.h\"\n#include \"aXe_grism.h\"\n#include \"spc_spc.h\"\n#include \"spc_driz.h\"\n#include \"aper_conf.h\"\n#include \"spce_output.h\"\n#include \"spc_optimum.h\"\n\n#define SQR(x) ((x)*(x))\n#define MIN(x,y) (((x)<(y))?(x):(y))\n#define MAX(x,y) (((x)>(y))?(x):(y))\n\n/*\ngsl_matrix *\ncreate_weightimage(ap_pixel *ap_p, const beam actbeam,\n\t\t const aperture_conf *conf, const double exptime,\n\t\t const double sky_cps)\n{\n drzstamp_dim dimension;\n drzstamp *modvar;\n gsl_matrix *weights;\n\n dimension = get_resample_dims(ap_p, actbeam);\n\n if (!dimension.resolution)\n return get_default_weight();\n\n compute_model_ivar(ap_p, conf->rdnoise, exptime, sky_cps);\n\n modvar = compute_modvar(ap_p, actbeam, dimension);\n\n weights = comp_allweight(modvar);\n\n return weights;\n}\n*/\n\n/**\n * Function: compute_modvar\n *\n *\n * Parameters:\n * @param ap_p - the PET table\n * @param actbeam - beam to compute the modvar structure for\n * @param dimension - dimenasion of the images\n * @param modvar - the structure to fill\n */\ndrzstamp *\ncompute_modvar(ap_pixel *ap_p, const beam actbeam,\n\t const drzstamp_dim dimension)\n{\n ap_pixel *cur_p;\n ap_pixel *tmp_p;\n\n quadrangle quad;\n\n double jacob;\n\n int jcen, icen;\n int jupp, iupp;\n int jlow, ilow;\n\n int ii, jj;\n int stpi, stpj;\n\n double maxarr, arr;\n //int iim, jjm;\n double value, allweig, weig;\n double stpc;\n double totweight;\n drzstamp *modvar;\n\n // allocate memory for the result structure\n modvar = alloc_drzstamp(dimension);\n\n // allocate memory\n tmp_p = (ap_pixel *) malloc(sizeof(ap_pixel));\n\n // go over each pixel\n for (cur_p = ap_p; cur_p->p_x != -1; cur_p++)\n {\n // Skip this pixel if it was not actually used\n if (fabs(cur_p->dist)>actbeam.width+0.5)\n continue;\n\n // transfer values to the temporary pixel\n tmp_p->lambda = cur_p->xi;\n tmp_p->dist = cur_p->dist;\n tmp_p->dxs = cur_p->dxs;\n tmp_p->dlambda = 1.0;\n\n // create the quadrangle for the current pixel\n quad = get_quad_from_pixel(tmp_p, actbeam.orient, dimension);\n\n\n // get the jacobian (well, easy here)\n // the term \"cos(cur_p->dxs)\" must be there\n // to correct the enlargement necessary\n // to cover the whole lambda-crossdispersion area!\n // NOT COMPLETELY understood\n jacob = cos(cur_p->dxs);\n\n // get the central pixel (icen, jcen) of the current PET-pixel\n icen = (int) floor(cur_p->xi - dimension.xstart+.5);\n jcen = (int) floor(cur_p->dist - dimension.ystart+.5);\n\n // get the uper and lower extend of the quadrangle in x\n iupp = (int)floor(quad.xmax - (double)icen + 0.5)+1;\n ilow = (int)floor(quad.xmin - (double)icen + 0.5);\n\n // get the uper and lower extend of the quadrangle in x\n jupp = (int)floor(quad.ymax - (double)jcen + 0.5)+1;\n jlow = (int)floor(quad.ymin - (double)jcen + 0.5);\n\n maxarr=0.0;\n totweight = 0.0;\n // go over the extend in x\n for (ii=ilow;ii=dimension.xsize)||(stpi<0)\n\t\t ||(stpj>=dimension.ysize)||(stpj<0))\n\t\tcontinue;\n\n\t // get the area which falls onto the current output pixel\n\t arr = boxer(stpi,stpj,quad.x,quad.y);\n\n\t if (arr > 0.0)\n\t\t{\n\t\t // get the already existing counts and weights\n\t\t stpc = gsl_matrix_get(modvar->counts,stpi,stpj);\n\t\t weig = gsl_matrix_get(modvar->weight,stpi,stpj);\n\n\t\t // compute the new, total weight of the current output pixel\n\t\t allweig = weig + arr*cur_p->weight;\n\n\t\t // do a weighted sum of the count value at the current\n\t\t // output pixel\n\t\t value = (stpc*weig + arr*cur_p->model*cur_p->weight*jacob)\n\t\t / (allweig);\n\n\t\t // store the new count value and the new weight\n\t\t gsl_matrix_set(modvar->counts,stpi,stpj,value);\n\t\t gsl_matrix_set(modvar->weight,stpi,stpj,allweig);\n\t\t}\n\t }\n\t}\n }\n\n // freep the temporary PET pixel\n free(tmp_p);\n\n // return the result\n return modvar;\n}\n\nvoid\nshift_tracelength(ap_pixel *ap_p, const double xi_shift)\n{\n ap_pixel *cur_p;\n\n // go over each PET pixel\n for (cur_p = ap_p; cur_p->p_x != -1; cur_p++)\n {\n // apply a shift in trace distance\n cur_p->xi += xi_shift;\n }\n}\n\n/**\n * Function: prepare_inv_variance\n * The function prepares the inverse model variances\n * for a data set containing an object and a background PET.\n * This is done in subroutines which compute the\n * theoretical inverse pixel variance following\n * different methods for the object and the background PET.\n *\n * Parameters:\n * @param ap_p - the object PET table\n * @param bg_p - the background PET table\n * @param dobck - integer indicating background subtraction\n * @param conf - the configuration structure\n * @param exptime - the exposure time\n * @param sky_cps - the sky background\n */\nvoid\nprepare_inv_variance(ap_pixel *ap_p, ap_pixel *bg_p, const int dobck,\n\t\t const aperture_conf *conf, const double exptime,\n\t\t const double sky_cps, const double xi_shift)\n{\n\n if (dobck)\n {\n // shift both, the object and the background PET\n shift_tracelength(ap_p, xi_shift);\n shift_tracelength(bg_p, xi_shift);\n\n // compute the inverse variance for the object + background PET\n compute_total_ivar(bg_p, bg_p, conf->rdnoise, exptime, sky_cps);\n }\n else\n {\n // shift both, the object PET\n shift_tracelength(ap_p, xi_shift);\n\n // compute the inverse variance for the object PET\n compute_object_ivar(ap_p, conf->rdnoise, exptime, sky_cps);\n }\n}\n\n/**\n * Function: compute_model_ivar\n * The function computes for each PET pixel the\n * associated inverse variance value. The input\n * for variance and inverse variance are the\n * model value, the contamination value, the\n * constant sky background value and the readnoise.\n * The computed inverse variance value is stored\n * in the weight entry of the PET.\n * The function also offers the possibility to\n * shift the trace distance by a fixed amount.\n *\n * Parameters:\n * @param ap_p - the PET table\n * @param rdnoise - the readnoise value\n * @param exptime - the exposure time\n * @param sky_cps - the sky background\n * @param xi_shift - shift in trace distance\n */\nvoid\ncompute_object_ivar(ap_pixel *ap_p, const double rdnoise,\n\t\t const double exptime, const double sky_cps)\n{\n double variance;\n double sqr_rdnoise;\n double sqr_exptime;\n ap_pixel *cur_p;\n\n // square the readnoise\n sqr_rdnoise = rdnoise*rdnoise;\n\n // square the exposure time\n sqr_exptime = exptime*exptime;\n\n // go over each PET pixel\n for (cur_p = ap_p; cur_p->p_x != -1; cur_p++)\n {\n\t// compute the variance\n\tvariance = ((cur_p->model + cur_p->contam + sky_cps) * exptime\n\t\t + sqr_rdnoise) / sqr_exptime;\n\n // store the inverse variance\n cur_p->weight = 1.0/variance;\n }\n}\n\n/**\n * Function: compute_value_ivar\n * The function computes for each PET pixel the\n * associated inverse variance value. The input\n * to derive the variance is the count value and\n * the readnoise.\n * The computed inverse variance value is stored\n * in the weight entry of the PET.\n * The function also offers the possibility to\n * shift the trace distance by a fixed amount.\n *\n * Parameters:\n * @param ap_p - the PET table\n * @param rdnoise - the readnoise value\n * @param exptime - the exposure time\n * @param sky_cps - the sky background\n * @param xi_shift - shift in trace distance\n */\nvoid\ncompute_total_ivar(ap_pixel *ap_p, const ap_pixel *bg_p, const double rdnoise,\n\t\t const double exptime, const double sky_cps)\n{\n double variance;\n double sqr_rdnoise;\n double sqr_exptime;\n\n ap_pixel *cur_p;\n const ap_pixel *bac_p;\n\n // square the readnoise\n sqr_rdnoise = rdnoise*rdnoise;\n\n // square the exposure time\n sqr_exptime = exptime*exptime;\n\n // go over each PET pixel\n bac_p = bg_p;\n for (cur_p = ap_p; cur_p->p_x != -1; cur_p++)\n {\n // check that the foreground and background\n // PET element describe the same pixel\n if (bac_p->x != cur_p->x || bac_p->y != cur_p->y)\n\taXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"aXe_PET2SPC: Background PET and Object PET \"\n\t\t \"have different pixel orders in PET's.\\n\");\n else\n // compute the variance\n variance = ((cur_p->count + bac_p->count + sky_cps) * exptime + sqr_rdnoise) / sqr_exptime;\n\n // store the inverse variance\n cur_p->weight = 1.0/variance;\n\n // increase the background pointer\n bac_p++;\n }\n}\n\n/**\n * Function: alloc_drzstamp\n * Allocates memory for a drizzle stamp structure\n * according the the dimension specified in the input.\n *\n * Parameters:\n * @param dimension - the dimesions to allocate\n *\n * Returns:\n * @return ret - the drizzle stamp image allocated\n */\ndrzstamp *\nalloc_drzstamp(const drzstamp_dim dimension)\n{\n drzstamp *ret;\n gsl_matrix *counts;\n gsl_matrix *weight;\n\n ret = (drzstamp *) malloc(sizeof(drzstamp));\n\n /* Allocate the stamp matrix*/\n /* Fill stamp with NaN values */\n counts = gsl_matrix_alloc(dimension.xsize,dimension.ysize);\n // gsl_matrix_set_all(counts, GSL_NAN);\n gsl_matrix_set_all(counts, 0.0);\n\n /* Allocate the weight matrix*/\n /* Fill weight with 0.0 values */\n weight = gsl_matrix_alloc(dimension.xsize,dimension.ysize);\n gsl_matrix_set_all(weight, 0.0);\n\n // fill the output structure\n ret->counts = counts;\n ret->weight = weight;\n\n // return the allocated structure\n return ret;\n}\n\n/**\n * Function: get_all_dims\n * The function derives the dimensional information\n * on the foreground and, if available, on the\n * background PET. The dimensions are compared, and\n * in case of inequality an error is thrown.\n * If the dimensions are equal, one of them is\n * returned.\n *\n * Parameters:\n * @param ap_p - the table of aperture pixels\n * @param bg_p - the table of background pixels\n * @param actbeam - the beam to compute the dimensions for\n * @param dobck - integer indicating background subtraction\n *\n * Returns:\n * @return ret - the dimension structure\n */\ndrzstamp_dim\nget_all_dims(const ap_pixel *ap_p, const ap_pixel *bg_p, const beam actbeam,\n\t const int dobck)\n{\n drzstamp_dim ret;\n drzstamp_dim bck;\n\n // get the aperture PET diemnsion\n ret = get_resample_dims(ap_p, actbeam);\n\n if (dobck)\n {\n // get the background PET dimension\n bck = get_resample_dims(bg_p, actbeam);\n\n // check whether the two dimensions\n // are equal, throw an error if not\n if (ret.resolution != bck.resolution\n\t || ret.xstart != bck.xstart\n\t || ret.ystart != bck.ystart\n\t || ret.xsize != bck.xsize\n\t || ret.ysize != bck.ysize)\n\taXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"aXe_PET2SPC: Background PET and Object PET \"\n\t\t \"do not have the same dimension.\\n\");\n }\n\n // return one of the dimensional infos\n return ret;\n}\n\n\n/**\n * Function: get_resample_dims\n * The function parses through a PET table and determines\n * the dimension of the image in the coordinates\n * trace distance - cross-dispersion direction. Those\n * dimensions are stored in a special structure and\n * returned to the calling routine.\n *\n * Parameters:\n * @param ap_p - the table of aperture pixels\n * @param actbeam - the beam to compute the dimensions for\n *\n * Returns:\n * @return ret - the dimension structure\n */\ndrzstamp_dim\nget_resample_dims(const ap_pixel *ap_p, const beam actbeam)\n{\n drzstamp_dim ret;\n\n const ap_pixel *cur_p;\n\n int i_xint, i_dist;\n int imin_xint=0, imin_dist=0;\n int imax_xint=0, imax_dist=0;\n\n int npixel = 0;\n\n // immediately return empty PET's\n if (ap_p==NULL)\n return get_default_dim();\n\n // set the tmp pixel to the table start\n cur_p = ap_p;\n\n // initialize some relevant numbers\n // based on the first pixel\n i_xint = floor(cur_p->xi + 0.5);\n i_dist = floor(cur_p->dist + 0.5);\n imin_xint = i_xint;\n imax_xint = i_xint;\n imin_dist = i_dist;\n imax_dist = i_dist;\n\n // go over all pixels, check\n // for new MIN's ans MAX's\n for (cur_p = ap_p; cur_p->p_x != -1; cur_p++)\n {\n // Skip the pixel if it was not actually used\n if (fabs(cur_p->dist)>actbeam.width+.5)\n\tcontinue;\n\n // compute the rounded value in (x,y)\n i_xint = floor(cur_p->xi + 0.5);\n i_dist = floor(cur_p->dist + 0.5);\n\n // check for extrema in x\n imin_xint = MIN(imin_xint, i_xint);\n imax_xint = MAX(imax_xint, i_xint);\n\n // check for extrema in y\n imin_dist = MIN(imin_dist, i_dist);\n imax_dist = MAX(imax_dist, i_dist);\n\n // enhance the pixel counter\n npixel++;\n }\n\n\n // in case there were no valid pixels,\n // return a dummy structure\n if (!npixel)\n return get_default_dim();\n\n // fill the structure with the correct values\n ret.resolution = 1.0;\n ret.xstart = imin_xint - NSPARE_PIX;\n ret.ystart = imin_dist - NSPARE_PIX;\n ret.xsize = imax_xint - imin_xint + 2 * NSPARE_PIX;\n ret.ysize = imax_dist - imin_dist + 2 * NSPARE_PIX;\n\n // return the structure\n return ret;\n}\n\n/**\n * Function: get_default_dim\n * The function creates and returns the default\n * dimension structure. The dewfault dimension\n * structure contains a 0.0 in all fields.\n *\n * Returns:\n * @return res - the dimension structure\n */\ndrzstamp_dim\nget_default_dim()\n{\n drzstamp_dim ret;\n\n // just set everything to zero\n ret.resolution=0.0;\n ret.xstart = 0;\n ret.ystart = 0;\n ret.xsize = 0;\n ret.ysize = 0;\n\n // return the result\n return ret;\n}\n\n/**\n * Function: get_default_modvar\n * The function computes the default drizzle stamp\n * structure, which in this case is used for\n * tha calculation of the resampled variance and\n * profile image.\n *\n * Returns:\n * @return res - the resulting drzstamp structure\n */\ndrzstamp *\nget_default_modvar()\n{\n gsl_matrix *counts;\n gsl_matrix *weight;\n drzstamp *res;\n\n res = (drzstamp *) malloc(sizeof(drzstamp));\n\n /* Create a dummy stamp image */\n counts = gsl_matrix_alloc(10,10);\n weight = gsl_matrix_alloc(10,10);\n /* Fill stamp with 0.0 values */\n gsl_matrix_set_all(counts, 0.0);\n gsl_matrix_set_all(weight, 0.0);\n\n // fill the output\n res->counts = counts;\n res->weight = weight;\n\n // return the output\n return res;\n}\n\ngsl_matrix *\nget_default_weight()\n{\n gsl_matrix *res;\n\n res = gsl_matrix_alloc(10,10);\n gsl_matrix_set_all(res, 0.0);\n\n // return the output\n return res;\n}\n\n/*\n * Function: comp_opt_weight\n * The function uses the model map and and the variance\n * map and computes optimale weigths according to the\n * Hoorne method.\n * Pixels outside of the extraction\n * area are set to 1000.0\n *\n * Parameters:\n * @param mod_map - the matrix with the model values\n * @param var_map - the matrix with the variance values\n * @param ob - the object structure\n *\n * Returns:\n * @return weight - the matrix with the exposure time weights\n */\ngsl_matrix *\ncomp_allweight(drzstamp *modvar)\n{\n gsl_matrix *weight;\n\n double mod_sum, weight_sum;\n double contr, norm, allweight;\n double mod_val;\n double act_weight=0;\n\n //int beamInt = 0;\n int i, j;\n\n // allocate the weight matrix and set the default\n weight = gsl_matrix_alloc(modvar->counts->size1, modvar->counts->size2);\n gsl_matrix_set_all(weight, 1000.0);\n\n //* go over all columns\n for (i=0; i < (int)modvar->counts->size1; i++)\n {\n mod_sum = 0.0;\n contr = 0.0;\n allweight = 0.0;\n weight_sum=0.0;\n\n // determine for each column the total model counts\n // and the number of pixels with non-zero model_counts\n for (j=0; j < (int)modvar->counts->size2; j++)\n\t{\n\t mod_sum = mod_sum + gsl_matrix_get(modvar->counts, i, j);\n\t contr = contr + 1.0;\n\t}\n\n // check whether the column has model values.\n // normalize the model values and compute\n // optimal weights if yes.\n if (mod_sum > 0.0)\n\t{\n\t //* determine the mean model value\n\t //\t norm = mod_sum / contr;\n\t norm = mod_sum;\n\n\t // go over each row\n\t for (j=0; j < (int)modvar->counts->size2; j++)\n\t {\n\t // normalize the model counts\n\t mod_val = gsl_matrix_get(modvar->counts, i, j)/norm;\n\n\t // store the normalized model counts\n\t gsl_matrix_set(modvar->counts, i, j, mod_val);\n\n\t // add up the normalization value for the optimal weights\n\t weight_sum = weight_sum\n\t\t+ mod_val*mod_val*gsl_matrix_get(modvar->weight, i, j);\n\t }\n\n\t // finally compute and write the weights:\n\t // go over each pixel\n\t for (j=0; j < (int)modvar->counts->size2; j++)\n\t {\n\t if (gsl_matrix_get(modvar->counts, i, j) > 0.0 )\n\t\t{\n\t\t // compute and set the individual pixel weight\n\t\t act_weight = gsl_matrix_get(modvar->counts,i,j)\n\t\t *gsl_matrix_get(modvar->weight,i,j)/weight_sum;\n\t\t //\t\t gsl_matrix_set(weight,i,j,gsl_matrix_get(modvar->counts,i,j)\n\t\t //\t\t *gsl_matrix_get(modvar->weight,i,j)/weight_sum);\n\t\t gsl_matrix_set(weight, i, j, act_weight);\n\t\t allweight = allweight + gsl_matrix_get(weight, i, j);\n\t\t}\n\t else\n\t\t{\n\t\t // set the default value if no model value is zero\n\t\t gsl_matrix_set(weight, i, j,0.0);\n\t\t}\n\t }\n\t}\n // if the column does not have model values at all:\n else\n\t{\n\t // go over each row\n\t for (j=0; j < (int)modvar->counts->size2; j++)\n\t {\n\t // set the inside default value\n\t gsl_matrix_set(weight, i,j,1.0);\n\t allweight = allweight + gsl_matrix_get(modvar->counts, i, j);\n\n\t }\n\t}\n }\n\n // return the weight matrix\n return weight;\n}\n", "meta": {"hexsha": "0e52925f417ac4e7db28d55b77bf3ce4ef26b283", "size": 17793, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/spc_optimum.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spc_optimum.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spc_optimum.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.824383164, "max_line_length": 97, "alphanum_fraction": 0.6643061878, "num_tokens": 5037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933227109649, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.41314930448964593}} {"text": "#ifndef __LISAUTILS_H__\n#define __LISAUTILS_H__ 1\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n#include \"struct.h\"\n#include \"EOBNRv2HMROMstruct.h\"\n#include \"EOBNRv2HMROM.h\"\n#include \"waveform.h\"\n#include \"wip.h\"\n#include \"splinecoeffs.h\"\n#include \"fresnel.h\"\n#include \"likelihood.h\"\n#include \"LISAFDresponse.h\"\n#include \"LISAnoise.h\"\n\n#if defined(__cplusplus)\nextern \"C\" {\n#define complex _Complex\n#elif 0\n} /* so that editors will match preceding brace */\n#endif\n\n/***************** Enumerator to choose what masses/time set to sample for *****************/\n\ntypedef enum SampleMassParamstag {\n m1m2,\n Mchirpeta\n} SampleMassParamstag;\n/* Superseded by sampleLframe */\n// typedef enum SampleTimeParamtag {\n// tSSB,\n// tL\n// } SampleTimeParamtag;\n\n/* Function to convert string input SampleMassParams to tag */\nSampleMassParamstag ParseSampleMassParamstag(char* string);\n/* Function to convert string input SampleTimeParams to tag */\n//SampleTimeParamtag ParseSampleTimeParamtag(char* string);\n\n/***************** Structure definitions *****************/\n\n/* Parameters for the generation of a LISA waveform (in the form of a list of modes) */\ntypedef struct tagLISAParams {\n double tRef; /* reference time (s) - GPS time at the frequency representing coalescence */\n double phiRef; /* reference phase (rad) - phase at the frequency representing coalescence (or at fRef if specified) */\n double m1; /* mass of companion 1 (solar masses, default 2e6) */\n double m2; /* mass of companion 2 (solar masses, default 1e6) */\n double distance; /* distance of source (Mpc, default 1e3) */\n double lambda; /* first angle for the position in the sky (rad, default 0) */\n double beta; /* second angle for the position in the sky (rad, default 0) */\n double inclination; /* inclination of L relative to line of sight (rad, default PI/3) */\n double polarization; /* polarization angle (rad, default 0) */\n int nbmode; /* number of modes to generate (starting with 22) - defaults to 5 (all modes) */\n} LISAParams;\n\n/* Global parameters for the waveform generation and overlap computation */\ntypedef struct tagLISAGlobalParams {\n double fRef; /* reference frequency (Hz, default 0 which is interpreted as Mf=0.14) */\n double deltatobs; /* max duration of observation (years, default 2) - the start of the signals might be cut in time instead of cut in frequency */\n double minf; /* Minimal frequency (Hz, default=0) - when set to 0, use the lowest frequency where the detector noise model is trusted __LISASimFD_Noise_fLow (set somewhat arbitrarily)*/\n double maxf; /* Maximal frequency (Hz, default=0) - when set to 0, use the highest frequency where the detector noise model is trusted __LISASimFD_Noise_fHigh (set somewhat arbitrarily)*/\n int tagextpn; /* Tag to allow PN extension of the waveform at low frequencies */\n int tagtRefatLISA; /* Tag to signal time to be referenced to arrival at LISA rather than at SSB */\n double Mfmatch; /* When PN extension allowed, geometric matching frequency: will use ROM above this value. If <=0, use ROM down to the lowest covered frequency */\n int setphiRefatfRef; /* Flag for adjusting the FD phase at phiRef at the given fRef, which depends also on tRef - if false, treat phiRef simply as an orbital phase shift (minus an observer phase shift) (default=1) */\n int nbmodeinj; /* number of modes to include in the injection (starting with 22) - defaults to 5 (all modes) */\n int nbmodetemp; /* number of modes to include in the templates (starting with 22) - defaults to 5 (all modes) */\n int tagint; /* Tag choosing the integrator: 0 for wip (default), 1 for linear integration */\n TDItag tagtdi; /* Tag choosing the TDI variables to use */\n int nbptsoverlap; /* Number of points to use in loglinear overlaps (default 32768) */\n LISAconstellation *variant; /* A structure defining the LISA constellation features */\n int zerolikelihood; /* Tag to zero out the likelihood, to sample from the prior for testing purposes (default 0) */\n int frozenLISA; /* Freeze the orbital configuration to the time of peak of the injection (default 0) */\n ResponseApproxtag responseapprox; /* Approximation in the GAB and orb response - choices are full (full response, default), lowfL (keep orbital delay frequency-dependence but simplify constellation response) and lowf (simplify constellation and orbital response) - WARNING : at the moment noises are not consistent, and TDI combinations from the GAB are unchanged */\n int tagsimplelikelihood22; /* Tag to use simplified, frozen-LISA and lowf likelihood where mode overlaps are precomputed - 22-mode only - can only be used when the masses and time (tL) are pinned to injection values (Note: when using --snr, distance adjustment done using responseapprox, not the simple response) */\n int tagsimplelikelihoodHM; /* Tag to use simplified, frozen-LISA and lowf likelihood where mode overlaps are precomputed - set of modes - can only be used when the masses and time (tL) are pinned to injection values (Note: when using --snr, distance adjustment done using responseapprox, not the simple response) */\n} LISAGlobalParams;\n\ntypedef struct tagLISASignalCAmpPhase\n{\n struct tagListmodesCAmpPhaseFrequencySeries* TDI1Signal; /* Signal in the TDI channel 1, in the form of a list of the contribution of each mode */\n struct tagListmodesCAmpPhaseFrequencySeries* TDI2Signal; /* Signal in the TDI channel 2, in the form of a list of the contribution of each mode */\n struct tagListmodesCAmpPhaseFrequencySeries* TDI3Signal; /* Signal in the TDI channel 3, in the form of a list of the contribution of each mode */\n double TDI123hh; /* Combined Inner product (h|h) for TDI channels 123 */\n} LISASignalCAmpPhase;\n\ntypedef struct tagLISAInjectionCAmpPhase\n{\n struct tagListmodesCAmpPhaseSpline* TDI1Splines; /* Signal in the TDI channel 1, in the form of a list of splines for the contribution of each mode */\n struct tagListmodesCAmpPhaseSpline* TDI2Splines; /* Signal in the TDI channel 2, in the form of a list of splines for the contribution of each mode */\n struct tagListmodesCAmpPhaseSpline* TDI3Splines; /* Signal in the TDI channel 3, in the form of a list of splines for the contribution of each mode */\n double TDI123ss; /* Combined Inner product (s|s) for TDI channels 123 */\n} LISAInjectionCAmpPhase;\n\ntypedef struct tagLISASignalReIm /* We don't store the SNRs here, as we will use -1/2(h-s|h-s) for the likelihood */\n{\n struct tagReImFrequencySeries* TDI1Signal; /* Signal in the TDI channel 1, in the form of a Re/Im frequency series where the modes have been summed */\n struct tagReImFrequencySeries* TDI2Signal; /* Signal in the TDI channel 2, in the form of a Re/Im frequency series where the modes have been summed */\n struct tagReImFrequencySeries* TDI3Signal; /* Signal in the TDI channel 3, in the form of a Re/Im frequency series where the modes have been summed */\n} LISASignalReIm;\n\ntypedef struct tagLISAInjectionReIm /* Storing the vectors of frequencies and noise values - We don't store the SNRs here, as we will use -1/2(h-s|h-s) for the likelihood */\n{\n struct tagReImFrequencySeries* TDI1Signal; /* Signal in the TDI channel 1, in the form of a Re/Im frequency series where the modes have been summed */\n struct tagReImFrequencySeries* TDI2Signal; /* Signal in the TDI channel 2, in the form of a Re/Im frequency series where the modes have been summed */\n struct tagReImFrequencySeries* TDI3Signal; /* Signal in the TDI channel 3, in the form of a Re/Im frequency series where the modes have been summed */\n gsl_vector* freq; /* Vector of frequencies of the injection (assumed to be the same for A,E,T) */\n gsl_vector* noisevalues1; /* Vector of noise values on freq for TDI channel 1 */\n gsl_vector* noisevalues2; /* Vector of noise values on freq for TDI channel 2 */\n gsl_vector* noisevalues3; /* Vector of noise values on freq for TDI channel 3 */\n} LISAInjectionReIm;\n\ntypedef struct tagLISAPrior {\n SampleMassParamstag samplemassparams; /* Choose the set of mass params to sample from - options are m1m2 and Mchirpeta (default m1m2) */\n //SampleTimeParamtag sampletimeparam; /* Choose the time param to sample from - options are tSSB and tL (default tSSB) */\n int sampleLframe; /* flag to sample L-frame params tL, lambdaL, betaL, psiL instead of SSB-frame params -- priors are interpreted for those L-frame params - no phase transformation */\n double deltaT; /* width of time prior centered on injected value (s) (default 1e5) */\n double comp_min; /* minimum component mass (solar masses) (default 1e4) */\n double comp_max; /* maximum component mass (solar masses) (default 1e8) */\n double mtot_min; /* minimum total mass (solar masses) (default 5*1e4) */\n double mtot_max; /* maximum total mass (solar masses) (default 1e8) */\n double qmax; /* maximum asymmetric mass ratio (>=1) (default 11.98) */\n double Mchirp_min; /* Minimum chirp mass in Solar masses - when sampling Mchirpeta (default=2e4) */\n double Mchirp_max; /* Maximum chirp mass in Solar masses - when sampling Mchirpeta (default=4e7) */\n double eta_min; /* Minimum symmetric mass ratio eta - when sampling Mchirpeta (default=0.072) */\n double eta_max; /* Maximum symmetric mass ratio eta - when sampling Mchirpeta (default=0.25) */\n double dist_min; /* minimum distance of source (Mpc) (default 100) */\n double dist_max; /* maximum distance of source (Mpc) (default 40*1e3) */\n double lambda_min; /* minimum lambda (rad, default 0) - for testing */\n double lambda_max; /* maximum lambda (rad, default 2pi) - for testing */\n double beta_min; /* minimum beta (rad, default 0) - for testing */\n double beta_max; /* maximum beta (rad, default pi) - for testing */\n double phase_min; /* minimum phase (rad, default 0) - for testing */\n double phase_max; /* maximum phase (rad, default 2pi) - for testing */\n double pol_min; /* minimum polarization (rad, default 0) - for testing */\n double pol_max; /* maximum polarization (rad, default 2pi) - for testing */\n double inc_min; /* minimum inclination (rad, default 0) - for testing */\n double inc_max; /* maximum inclination (rad, default pi) - for testing */\n double fix_m1;\n double fix_m2;\n double fix_Mchirp;\n double fix_eta;\n double fix_time;\n double fix_lambda;\n double fix_beta;\n double fix_phase;\n double fix_pol;\n double fix_dist;\n double fix_inc;\n int pin_m1;\n int pin_m2;\n int pin_Mchirp;\n int pin_eta;\n int pin_time;\n int pin_lambda;\n int pin_beta;\n int pin_phase;\n int pin_pol;\n int pin_dist;\n int pin_inc;\n double snr_target;\n int rescale_distprior;\n int flat_distprior;\n int logflat_massprior;\n} LISAPrior;\n\ntypedef struct tagLISARunParams {\n double eff; /* target efficiency (default 0.1) */\n double tol; /* logZ tolerance (default 0.5) */\n int consteff; /* constant efficiency mode (default 0) */\n int nlive; /* number of live points (default 1000) */\n int writeparams; /* Write params - if 1, write run parameters to file (default 1) */\n char outroot[200]; /* output root (default \"chains/LISAinference_\") */\n int bambi; /* run BAMBI? (default 0) */\n int resume; /* resume form previous run? (default 0) */\n int maxiter; /* max number of iterations (default 0 - ignore) */\n char netfile[200]; /* NN settings file (default \"LISAinference.inp\") */\n int mmodal; /* use multimodal decomposition ? */\n int maxcls; /* max number of modes in multimodal decomposition */\n int nclspar; /* number of parameters to use for multimodal decomposition - in the order of the cube */\n double ztol; /* in multimodal decomposition, modes with lnZ lower than Ztol are ignored */\n int seed; /* seed the inference by setting one of the live points to the injection ? */\n} LISARunParams;\n\n/* Parameters for the generation of a LISA waveform (in the form of a list of modes) */\ntypedef struct tagLISAAddParams {\n double tRef; /* reference time (s) - GPS time at the frequency representing coalescence */\n double phiRef; /* reference phase (rad) - phase at the frequency representing coalescence (or at fRef if specified) */\n double m1; /* mass of companion 1 (solar masses, default 2e6) */\n double m2; /* mass of companion 2 (solar masses, default 1e6) */\n double distance; /* distance of source (Mpc, default 1e3) */\n double lambda; /* first angle for the position in the sky (rad, default 0) */\n double beta; /* second angle for the position in the sky (rad, default 0) */\n double inclination; /* inclination of L relative to line of sight (rad, default PI/3) */\n double polarization; /* polarization angle (rad, default 0) */\n int loadparamsfile; /* Option to load physical parameters from file for LISAlikelihood and to output resulting likelihoods to file (default 0) */\n int nlinesparams; /* Number of lines in params file for LISAlikelihood */\n char indir[256]; /* Input directory for LISAlikelihood */\n char infile[256]; /* Input file for LISAlikelihood */\n char outdir[256]; /* Output directory for LISAlikelihood */\n char outfile[256]; /* Output file for LISAlikelihood */\n} LISAAddParams;\n\n/* Saved precomputed values for the injection , when using the simplified frozenLISA lowf likelihood - here for now assumes 22 mode only, old convention */\n/* NOTE: difference in convention, new convention has a factor 3 in the integrand defining */\ntypedef struct tagSimpleLikelihoodPrecomputedValues22 {\n double normalization;\n double complex sa;\n double complex se;\n} SimpleLikelihoodPrecomputedValues22;\n/* Saved precomputed values for the injection , when using the simplified frozenLISA lowf likelihood - here for set of modes, new convention */\n/* NOTE: difference in convention, new convention has a factor 3 in the integrand defining */\ntypedef struct tagSimpleLikelihoodPrecomputedValuesHM {\n gsl_matrix* Lambda_lm_lpmp; /* Matrix */\n gsl_vector* sa_lm_real; /* Vector s_a^{lm}, real part*/\n gsl_vector* sa_lm_imag; /* Vector s_a^{lm}, imaginary part */\n gsl_vector* se_lm_real; /* Vector s_e^{lm}, real part*/\n gsl_vector* se_lm_imag; /* Vector s_e^{lm}, imaginary part */\n} SimpleLikelihoodPrecomputedValuesHM;\n\n/************ Functions for LISA parameters, injection, likelihood, prior ************/\n\n/* Parse command line to initialize LISAParams, LISAGlobalParams, LISAPrior, and LISARunParams objects */\n/* Masses are input in solar masses and distances in Mpc - converted in SI for the internals */\nvoid parse_args_LISA(ssize_t argc, char **argv,\n LISAParams* params,\n LISAGlobalParams* globalparams,\n LISAPrior* prior,\n LISARunParams* run,\n LISAAddParams* addparams);\n\n/* Functions to print the parameters of the run in files for reference */\nint print_parameters_to_file_LISA(\n LISAParams* params,\n LISAGlobalParams* globalparams,\n LISAPrior* prior,\n LISARunParams* run);\nint print_rescaleddist_to_file_LISA(\n LISAParams* params,\n LISAGlobalParams* globalparams,\n LISAPrior* prior,\n LISARunParams* run);\nint print_snrlogZ_to_file_LISA(LISARunParams* run, double SNR, double logZ);\n/* Function printing injection/signal parameters to stdout */\nvoid report_LISAParams(LISAParams* params);\n\n/* Initialization and clean-up for LISASignal structures */\nvoid LISASignalCAmpPhase_Cleanup(LISASignalCAmpPhase* signal);\nvoid LISASignalCAmpPhase_Init(LISASignalCAmpPhase** signal);\nvoid LISAInjectionCAmpPhase_Cleanup(LISAInjectionCAmpPhase* signal);\nvoid LISAInjectionCAmpPhase_Init(LISAInjectionCAmpPhase** signal);\nvoid LISASignalReIm_Cleanup(LISASignalReIm* signal);\nvoid LISASignalReIm_Init(LISASignalReIm** signal);\nvoid LISAInjectionReIm_Cleanup(LISAInjectionReIm* signal);\nvoid LISAInjectionReIm_Init(LISAInjectionReIm** signal);\n\n//Function to restrict range of the signal/injection to within desired limits.\nint listmodesCAmpPhaseTrim(ListmodesCAmpPhaseFrequencySeries* listSeries);\n\n/* Function generating a LISA signal as a list of modes in CAmp/Phase form, from LISA parameters */\nint LISAGenerateSignalCAmpPhase(\n struct tagLISAParams* params, /* Input: set of LISA parameters of the signal */\n struct tagLISASignalCAmpPhase* signal); /* Output: structure for the generated signal */\n/* Function generating a LISA injection as a list of modes, given as preinterpolated splines, from LISA parameters */\nint LISAGenerateInjectionCAmpPhase(\n struct tagLISAParams* injectedparams, /* Input: set of LISA parameters of the signal */\n struct tagLISAInjectionCAmpPhase* signal); /* Output: structure for the generated signal */\n/* Function generating a LISA signal as a frequency series in Re/Im form where the modes have been summed, from LISA parameters - takes as argument the frequencies on which to evaluate */\nint LISAGenerateSignalReIm(\n struct tagLISAParams* params, /* Input: set of LISA parameters of the template */\n gsl_vector* freq, /* Input: frequencies on which evaluating the waveform (from the injection) */\n struct tagLISASignalReIm* signal); /* Output: structure for the generated signal */\n/* Function generating a LISA injection as a frequency series in Re/Im form where the modes have been summed, from LISA parameters - frequencies on which to evaluate are to be determined internally */\nint LISAGenerateInjectionReIm(\n struct tagLISAParams* injectedparams, /* Input: set of LISA parameters of the injection */\n double fLow, /* Input: starting frequency */\n int nbpts, /* Input: number of frequency samples */\n int tagsampling, /* Input: tag for using linear (0) or logarithmic (1) sampling */\n struct tagLISAInjectionReIm* signal); /* Output: structure for the generated signal */\n\n/*Wrapper for waveform generation with possibly a combination of EOBNRv2HMROM and TaylorF2*/\n/* Note: GenerateWaveform accepts masses and distances in SI units, whereas LISA params is in solar masses and Mpc */\nint GenerateWaveform(\n struct tagListmodesCAmpPhaseFrequencySeries **listhlm, /* Output: list of modes in Frequency-domain amplitude and phase form */\n int nbmode, /* Number of modes to generate (starting with the 22) */\n double f_match, /* Minimum frequency using EOBNRv2HMROM */\n double f_min, /* Minimum frequency required */\n double deltatRef, /* Time shift so that the peak of the 22 mode occurs at deltatRef */\n double phiRef, /* Phase at reference frequency */\n double fRef, /* Reference frequency (Hz); 0 defaults to fLow */\n double m1SI, /* Mass of companion 1 (kg) */\n double m2SI, /* Mass of companion 2 (kg) */\n double distance /* Distance of source (m) */\n\t\t );\n\n/* Non-spinning merger TaylorF2 waveform, copied and condensed from LAL */\nvoid TaylorF2nonspin(\n\t\tdouble *amp, /**< FD waveform amplitude (modulus)*/\n\t\tdouble *phase, /**< FD waveform phase */\n\t\tconst double *freqs, /**< frequency points at which to evaluate the waveform (Hz) */\n\t\tconst int size, /** number of freq samples */\n\t\tconst double m1_SI, /**< mass of companion 1 (kg) */\n\t\tconst double m2_SI, /**< mass of companion 2 (kg) */\n\t\tconst double distance, /** distance (m) */\n\t\tconst double imatch /**< index at which to match phase;\n\t\t\t\t\t\t\t assumes arrays are preloaded at imatch and imatch+1\n\t\t\t\t\t\t\t with the required result */\n\t\t );\n\n/* checks prior boundaires */\nint PriorBoundaryCheckm1m2(LISAPrior *prior, double *Cube);\nint PriorBoundaryCheckMchirpeta(LISAPrior *prior, double *Cube);\n\n/* Prior functions from Cube to physical parameters\n x1 is min, x2 is max when specified\n r is Cube value */\ndouble CubeToFlatPrior(double r, double x1, double x2);\ndouble CubeToLogFlatPrior(double r, double x1, double x2);\ndouble CubeToPowerPrior(double p, double r, double x1, double x2);\ndouble CubeToGaussianPrior(double r, double mean, double sigma);\ndouble CubeToSinPrior(double r, double x1, double x2);\ndouble CubeToCosPrior(double r, double x1, double x2);\n/* Prior functions from physical parameters to Cube\n x1 is min, x2 is max when specified\n y is physical value */\ndouble FlatPriorToCube(double y, double x1, double x2);\ndouble LogFlatPriorToCube(double y, double x1, double x2);\ndouble PowerPriorToCube(double p, double y, double x1, double x2);\ndouble SinPriorToCube(double y, double x1, double x2);\ndouble CosPriorToCube(double y, double x1, double x2);\n\n/* log-Likelihood functions */\ndouble CalculateLogLCAmpPhase(LISAParams *params, LISAInjectionCAmpPhase* injection);\ndouble CalculateLogLReIm(LISAParams *params, LISAInjectionReIm* injection);\n\n/* Functions for simplified likelihood using precomputing relevant values */\nint LISAComputeSimpleLikelihoodPrecomputedValues22(SimpleLikelihoodPrecomputedValues22* simplelikelihoodvals22, LISAParams* params);\nint LISAComputeSimpleLikelihoodPrecomputedValuesHM(SimpleLikelihoodPrecomputedValuesHM* simplelikelihoodvalsHM, LISAParams* params);\ndouble CalculateLogLSimpleLikelihood22(SimpleLikelihoodPrecomputedValues22* simplelikelihoodvals22, LISAParams* params);\ndouble CalculateLogLSimpleLikelihoodHM(SimpleLikelihoodPrecomputedValuesHM* simplelikelihoodvalsHM, LISAParams* params);\n\n/************ Global Parameters ************/\n\nextern LISAParams* injectedparams;\nextern LISAGlobalParams* globalparams;\nextern LISAPrior* priorParams;\nextern LISAAddParams* addparams;\nextern double logZdata; /* TODO: not used */\nextern SimpleLikelihoodPrecomputedValues22* simplelikelihoodinjvals22;\nextern SimpleLikelihoodPrecomputedValuesHM* simplelikelihoodinjvalsHM;\n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "2cf1486a9c976410b5a4fccd53877273a2edd59b", "size": 23167, "ext": "h", "lang": "C", "max_stars_repo_path": "LISAinference/LISAutils.h", "max_stars_repo_name": "JohnGBaker/flare", "max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "LISAinference/LISAutils.h", "max_issues_repo_name": "JohnGBaker/flare", "max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LISAinference/LISAutils.h", "max_forks_repo_name": "JohnGBaker/flare", "max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 63.4712328767, "max_line_length": 371, "alphanum_fraction": 0.6951266888, "num_tokens": 5651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.41278367268691424}} {"text": "/*\n Copyright (C) 2004-2007 M. Oliveira, F. Nogueira\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2, or (at your option)\n any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA\n 02111-1307, USA.\n*/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n/* This file contains interface routines that allow Fortran 90/95\nroutines to call GSL routines. The names of these routines are\ncompiler dependent: Fortran 90/95 compilers have different\nname-mangling schemes. For a description of the routines please refer\nto the GSL documentation. */\n\n\n /* Error Handling */\n\nvoid FC_FUNC_(gsl_strerror, GSL_STRERROR)\n (int *err, STR_F_TYPE res STR_ARG1)\n{\n char *c;\n\n c = gsl_strerror(*err);\n /*TO_F_STR1(c, res);!!not too sure what this does*/\n}\n\n\n /* Mathematical Functions */\n\ndouble FC_FUNC_(gsl_asinh, GSL_ASINH)\n (const double *x) \n{\n return gsl_asinh(*x);\n}\n\n\n /* Special Functions */\n\ndouble FC_FUNC_(gsl_sf_bessel_knu_scaled, GSL_SF_BESSEL_KNU_SCALED)\n (double *nu, double *x) \n{\n return gsl_sf_bessel_Knu_scaled(*nu,*x);\n}\n\n\n /* Vectors and Matrices */\n\nvoid FC_FUNC_(gsl_vector_alloc, GSL_VECTOR_ALLOC)\n (int *n, void **v)\n{\n *v = (void*) gsl_vector_alloc (*n);\n}\n\nvoid FC_FUNC_(gsl_vector_free, GSL_VECTOR_FREE)\n (void **v)\n{\n gsl_vector_free ((gsl_vector *)(*v));\n}\n\ndouble FC_FUNC_(gsl_vector_get, GSL_VECTOR_GET) (void **v, int *i)\n{\n return gsl_vector_get ((gsl_vector *)(*v), *i);\n}\n\nvoid FC_FUNC_(gsl_vector_set, GSL_VECTOR_SET)\n (void **v, int *i, double *x)\n{\n gsl_vector_set ((gsl_vector *)(*v), *i, *x);\n} \n\nvoid FC_FUNC_(gsl_matrix_alloc, GSL_MATRIX_ALLOC)\n (int *n1, int *n2, void **m)\n{\n *m = (void*) gsl_matrix_alloc (*n1, *n2);\n}\n\nvoid FC_FUNC_(gsl_matrix_calloc, GSL_MATRIX_CALLOC)\n (int *n1, int *n2, void **m)\n{\n *m = (void*) gsl_matrix_calloc (*n1, *n2);\n}\n\nvoid FC_FUNC_(gsl_matrix_free, GSL_MATRIX_FREE)\n (void **m)\n{\n gsl_matrix_free ((gsl_matrix *)(*m));\n}\n\ndouble FC_FUNC_(gsl_matrix_get, GSL_MATRIX_GET)\n (void **m, int *i, int *j)\n{\n return gsl_matrix_get ((gsl_matrix *)(*m), *i, *j);\n}\n\nvoid FC_FUNC_(gsl_matrix_set, GSL_MATRIX_SET)\n (void **m, int *i, int *j, double *x)\n{\n gsl_matrix_set ((gsl_matrix *)(*m), *i, *j, *x);\n}\n\n\n /* Permutations */\n\n\nvoid FC_FUNC_(gsl_permutation_alloc, GSL_PERMUTATION_ALLOC)\n (int *n, void **p)\n{\n *p = (void*) gsl_permutation_alloc (*n);\n}\n\nvoid FC_FUNC_(gsl_permutation_free, GSL_PERMUTATION_FREE)\n (void **p)\n{\n gsl_permutation_free ((gsl_permutation *)(*p));\n}\n\n\n /* Linear Algebra */\n\n\nint FC_FUNC_(gsl_linalg_lu_decomp, GSL_LINALG_LU_DECOMP)\n (void **m, void **p, int *signum)\n{\n int s,ierr;\n ierr = gsl_linalg_LU_decomp ((gsl_matrix *)(*m) , (gsl_permutation *)(*p), &s);\n *signum = s;\n return (ierr);\n}\n\nint FC_FUNC_(gsl_linalg_lu_invert, GSL_LINALG_LU_INVERT)\n (void **LU, void **p, void **inverse)\n{\n\n return gsl_linalg_LU_invert ((gsl_matrix *)(*LU),(gsl_permutation *)(*p), (gsl_matrix *)(*inverse)); \n}\n\nint FC_FUNC_(gsl_linalg_lu_solve, GSL_LINALG_LU_SOLVE)\n (void **LU, void **p, void **b, void **x)\n{\n return gsl_linalg_LU_solve ((gsl_matrix *)(*LU), (gsl_permutation *)(*p), (gsl_vector *)(*b), (gsl_vector *)(*x));\n}\n\n\n /* Ordinary Differential Equations */\n\nvoid FC_FUNC_(gsl_odeiv_step_alloc, GSL_ODEIV_STEP_ALLOC)\n (const int *stepping_func, const int *dim, void **stp)\n{\n /* WARNING: This routine has a small modification: the user needs to\n pass an integer in order to choose the stepping function instead of\n a variable of type gsl_odeiv_step_type. */\n\n switch(*stepping_func) {\n case 1 : // Embedded 2nd order Runge-Kutta with 3rd order error estimate\n *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rk2, *dim);\n break;\n case 2 : // 4th order (classical) Runge-Kutta\n *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rk4, *dim);\n break;\n case 3 : // Embedded 4th order Runge-Kutta-Fehlberg method with 5th order error estimate. This method is a good general-purpose integrator\n *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rkf45, *dim);\n break;\n case 4 : // Embedded 4th order Runge-Kutta Cash-Karp method with 5th order error estimate\n *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rkck, *dim);\n break;\n case 5 : // Embedded 8th order Runge-Kutta Prince-Dormand method with 9th order error estimate\n *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rk8pd, *dim);\n break;\n case 6 : // Implicit 2nd order Runge-Kutta at Gaussian points \n *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rk2imp, *dim);\n break;\n case 7 : // Implicit 4th order Runge-Kutta at Gaussian points\n *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rk4imp, *dim);\n break;\n case 8 : // Implicit Bulirsch-Stoer method of Bader and Deuflhard. This algorithm requires the Jacobian\n *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_bsimp, *dim);\n break;\n case 9 : // M=1 implicit Gear method \n *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_gear1, *dim);\n break;\n case 10 : // M=2 implicit Gear method\n *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_gear2, *dim);\n break;\n }\n}\n\nvoid FC_FUNC_(gsl_odeiv_step_free, GSL_ODEIV_STEP_FREE)\n (void **stp)\n{\n gsl_odeiv_step_free((gsl_odeiv_step *)(*stp));\n}\n\nvoid FC_FUNC_(gsl_odeiv_evolve_alloc, GSL_ODEIV_EVOLVE_ALLOC)\n (const int *dim, void **evl)\n{\n *evl = (void *)gsl_odeiv_evolve_alloc (*dim);\n}\n\nint FC_FUNC_(gsl_odeiv_evolve_reset, GSL_ODEIV_EVOLVE_RESET)\n (void **evl)\n{\n return gsl_odeiv_evolve_reset ((gsl_odeiv_evolve *)(*evl));\n}\n\nvoid FC_FUNC_(gsl_odeiv_evolve_free, GSL_ODEIV_EVOLVE_FREE)\n (void **evl)\n{\n gsl_odeiv_evolve_free((gsl_odeiv_evolve *)(*evl));\n}\n\nvoid FC_FUNC_(gsl_odeiv_control_standart_new, GSL_ODEIV_CONTROL_STANDART_NEW)\n (void **ctrl, double *epsabs, double *epsrel, double *ay, double *adydt)\n{\n *ctrl = (void*) gsl_odeiv_control_standard_new (*epsabs, *epsrel, *ay, *adydt);\n}\n\nvoid FC_FUNC_(gsl_odeiv_control_free, GSL_ODEIV_CONTROL_FREE)\n (void **ctrl)\n{\n gsl_odeiv_control_free((gsl_odeiv_control *)(*ctrl));\n}\n\n\n /* Interpolation */\n\nvoid FC_FUNC_(gsl_interp_accel_alloc, GSL_INTERP_ACCEL_ALLOC)\n (void **acc)\n{\n *acc = (void *)gsl_interp_accel_alloc();\n}\n\nvoid FC_FUNC_(gsl_spline_alloc, GSL_SPLINE_ALLOC)\n (void **spl, int *n, short int *opt)\n{\n /* WARNING: This routine has a small modification: the user needs to\n pass an integer in order to choose the interpolation type instead\n of a variable of type gsl_interp_type. */\n\n switch (*opt) {\n case 1 : // linear interpolation\n *spl = (void *)gsl_spline_alloc(gsl_interp_linear, *n);\n break;\n case 2 : // polynomial interpolation\n *spl = (void *)gsl_spline_alloc(gsl_interp_polynomial, *n);\n break;\n case 3 : // cubic spline with natural boundary conditions\n *spl = (void *)gsl_spline_alloc(gsl_interp_cspline, *n);\n break;\n case 4 : // cubic spline with periodic boundary conditions \n *spl = (void *)gsl_spline_alloc(gsl_interp_cspline_periodic, *n);\n break;\n case 5 : // Akima spline with natural boundary conditions\n *spl = (void *)gsl_spline_alloc(gsl_interp_akima, *n);\n break;\n case 6 : // Akima spline with periodic boundary conditions \n *spl = (void *)gsl_spline_alloc(gsl_interp_akima_periodic, *n);\n break;\n }\n}\n\nvoid FC_FUNC_(gsl_spline_init, GSL_SPLINE_INIT)\n (void **spl, int *n, double *x, double *f)\n{\n gsl_spline_init((gsl_spline *)(*spl), x, f, *n);\n}\n\ndouble FC_FUNC_(gsl_spline_eval, GSL_SPLINE_EVAL)\n (double *x, void **spl, void **acc)\n{\n return gsl_spline_eval((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc));\n}\n\ndouble FC_FUNC_(gsl_spline_eval_deriv, GSL_SPLINE_EVAL_DERIV)\n (double *x, void **spl, void **acc)\n{\n return gsl_spline_eval_deriv((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc));\n}\n\ndouble FC_FUNC_(gsl_spline_eval_deriv2, GSL_SPLINE_EVAL_DERIV2)\n (double *x, void **spl, void **acc)\n{\n return gsl_spline_eval_deriv2((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc));\n}\n\nvoid FC_FUNC_(gsl_spline_free, GSL_SPLINE_FREE)\n (void **spl)\n{\n gsl_spline_free((gsl_spline *)(*spl));\n \n}\n\nvoid FC_FUNC_(gsl_interp_accel_free, GSL_INTERP_ACCEL_FREE)\n (void **acc)\n{\n gsl_interp_accel_free((gsl_interp_accel *)(*acc));\n}\n\ndouble FC_FUNC_(gsl_spline_eval_integ, GSL_SPLINE_EVAL_INTEG)\n (double *a, double *b, void **spl, void **acc)\n{\n return gsl_spline_eval_integ((gsl_spline *)(*spl), *a, *b, (gsl_interp_accel *)(*acc));\n}\n\n\n /* Multidimensional Root-Finding */\n\n void FC_FUNC_(gsl_multiroot_fsolver_alloc, GSL_MULTIROOT_FSOLVER_ALLOC)\n (void **s, const int *solver_type, const int *n)\n{\n switch(*solver_type) {\n case 1 : // hybrid algorithm with internal scaling.\n *s = (void *)gsl_multiroot_fsolver_alloc(gsl_multiroot_fsolver_hybrids, *n);\n break;\n case 2 : // hybrid algorithm without internal scaling.\n *s = (void *)gsl_multiroot_fsolver_alloc(gsl_multiroot_fsolver_hybrid, *n);\n break;\n case 3 : // discrete Newton algorithm\n *s = (void *)gsl_multiroot_fsolver_alloc(gsl_multiroot_fsolver_dnewton, *n);\n break;\n case 4 : // Broyden algorithm\n *s = (void *)gsl_multiroot_fsolver_alloc(gsl_multiroot_fsolver_broyden, *n);\n break;\n }\n}\n\nvoid FC_FUNC_(gsl_multiroot_fsolver_free, GSL_MULTIROOT_FSOLVER_FREE)\n (void **s)\n{\n gsl_multiroot_fsolver_free((gsl_multiroot_fsolver *)(*s));\n}\n", "meta": {"hexsha": "c9e4524532cbf39b90d87426e233782cb7b98884", "size": 10280, "ext": "c", "lang": "C", "max_stars_repo_path": "siesta/gsl_interface_c.c", "max_stars_repo_name": "cathcart/CCPG", "max_stars_repo_head_hexsha": "43a72c0ae47b3c3b3975e75f18185a886c143ab1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "siesta/gsl_interface_c.c", "max_issues_repo_name": "cathcart/CCPG", "max_issues_repo_head_hexsha": "43a72c0ae47b3c3b3975e75f18185a886c143ab1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "siesta/gsl_interface_c.c", "max_forks_repo_name": "cathcart/CCPG", "max_forks_repo_head_hexsha": "43a72c0ae47b3c3b3975e75f18185a886c143ab1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7955182073, "max_line_length": 140, "alphanum_fraction": 0.6998054475, "num_tokens": 3195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.6406358685621719, "lm_q1q2_score": 0.41271371939539236}} {"text": "/*\n** compute correlation matrix\n**\n** G.Lohmann, Feb 2011\n*/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"viaio/Vlib.h\"\n#include \"viaio/VImage.h\"\n#include \"viaio/mu.h\"\n\n#ifdef _OPENMP\n#include \n#endif /*_OPENMP*/\n\n#define SQR(x) ((x) * (x))\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\nextern void VNormalize(float *data,int nt,VBoolean stddev);\nextern long GetAddr(VImage mapimage,int bi,int ri,int ci,int m,int k,int l);\n\nint VNumNeigbours(size_t id,VImage map,VImage mapimage,int adjdef)\n{\n int nslices = VImageNBands(mapimage);\n int nrows = VImageNRows(mapimage);\n int ncols = VImageNColumns(mapimage);\n\n int bi = VPixel(map,0,0,id,VShort);\n int ri = VPixel(map,0,1,id,VShort);\n int ci = VPixel(map,0,2,id,VShort);\n if (bi < 1 || bi >= nslices-2) return 0;\n if (ri < 1 || ri >= nrows-2) return 0;\n if (ci < 1 || ci >= ncols-2) return 0;\n\n int wn=1,rad2=0;\n if (adjdef == 3) {\n wn = 2;\n rad2 = 2*2;\n }\n\n int n=0;\n int k,l,m;\n for (m=-wn; m<=wn; m++) {\n for (k=-wn; k<=wn; k++) {\n for (l=-wn; l<=wn; l++) {\n \tlong jj = GetAddr(mapimage,bi,ri,ci,m,k,l);\n \tif (jj < 0) continue; /* outside of brain mask */\n\n \tif (adjdef == 0) { /* 6 adjacency */\n \t if (ABS(m)+ABS(k)+ABS(l) > 1) continue;\n \t}\n \tif (adjdef == 1) { /* 18-adjacency */\n \t if (ABS(m) > 0 && ABS(k) > 0 && ABS(l) > 0) continue;\n \t}\t\n\tif (adjdef == 3) { /* sphere */\n\t if (m*m + k*k + l*l > rad2) continue;\n\t}\n \tn++;\n }\n }\n }\n return n;\n}\n\n/* convert to ranks */\nvoid GetRank(float *data,gsl_vector *v,gsl_permutation *perm,gsl_permutation *rank)\n{\n size_t i;\n size_t n = v->size;\n for (i=0; idata[i];\n}\n\ndouble Spearman(const float *data1,const float *data2,int n)\n{\n int i;\n double nx = (double)n;\n double kx = nx*(nx*nx-1.0);\n double sxy=0.0;\n for (i=0; i 0) return corr;\n else return 0.0;\n}\n\n\n\nvoid GetSNR(gsl_matrix_float **X1,gsl_matrix_float **X2,int *table,int n,gsl_matrix_float *SNR,int metric)\n{\n long j,nvox=X1[0]->size1;\n long k,s,nt=X1[0]->size2;\n\n if (n < 3) VError(\" n: %d\",n);\n double nx = (double)n;\n double *sum1 = (double *)VCalloc(nt,sizeof(double));\n double *sum2 = (double *)VCalloc(nt,sizeof(double));\n\n gsl_vector *vec = NULL;\n gsl_permutation *perm = NULL;\n gsl_permutation *rank = NULL;\n if (metric == 1) { /* only needed for spearman correlation */\n vec = gsl_vector_calloc(nt);\n perm = gsl_permutation_alloc(nt);\n rank = gsl_permutation_alloc(nt);\n }\n\n double ave=0,var=0,snr=0;\n\n for (j=0; j 0) snr = ave / sqrt(var);\n gsl_matrix_float_set(SNR,j,k,snr);\n }\n\n if (metric == 0) { /* pearson correlation */\n float *qq = gsl_matrix_float_ptr(SNR,j,0);\n VNormalize(qq,nt,TRUE);\n }\n if (metric == 1) { /* spearman ranks */\n float *qq = gsl_matrix_float_ptr(SNR,j,0);\n GetRank(qq,vec,perm,rank);\n }\n }\n VFree(sum1);\n VFree(sum2);\n}\n\n\n\n\nfloat ZMatrix(gsl_histogram *histogram,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2,\n\t VImage roi,VImage map,VImage mapimage,int adjdef,float elength,float quantile,int step,int metric)\n{\n size_t i;\n size_t nvox=SNR1->size1;\n int nt=SNR1->size2;\n size_t progress=0;\n int rad2 = (int)(elength*elength);\n double tiny=1.0e-8;\n gsl_set_error_handler_off ();\n\n\n fprintf(stderr,\" Computing matrix...\\n\");\n\n gsl_histogram_reset(histogram);\n size_t nbins = gsl_histogram_bins (histogram);\n double hmax = gsl_histogram_max (histogram);\n double hmin = gsl_histogram_min (histogram);\n double zmin = 99999.0;\n double zmax = -99999.0;\n int minadj = 1;\n\n\n#pragma omp parallel for shared(progress,histogram) schedule(dynamic) firstprivate(SNR1,SNR2)\n for (i=0; i 0.5) roiflagi = 1;\n }\n\n gsl_histogram *tmphist = gsl_histogram_alloc (nbins);\n gsl_histogram_set_ranges_uniform (tmphist,hmin,hmax);\n gsl_histogram_reset(tmphist);\n \n const float *datax1 = gsl_matrix_float_const_ptr(SNR1,i,0);\n const float *datax2 = gsl_matrix_float_const_ptr(SNR2,i,0);\n\n\n size_t j=0;\n for (j=0; j 0.5) roiflagj = 1;\n\tif (roiflagi + roiflagj != 1) continue; \n }\n const float *datay1 = gsl_matrix_float_const_ptr(SNR1,j,0);\n const float *datay2 = gsl_matrix_float_const_ptr(SNR2,j,0);\n\n /* edge z-value */\n double z1 = EdgeCorr(datax1,datay1,nt,metric);\n double z2 = EdgeCorr(datax2,datay2,nt,metric);\n double z = (z1-z2);\n if (z < zmin) zmin = z;\n if (z > zmax) zmax = z;\n\n if (z < hmin) z = hmin;\n if (z > hmax-tiny) z = hmax-tiny;\n gsl_histogram_increment (tmphist,z);\n }\n\n\n#pragma omp critical \n {\n gsl_histogram_add (histogram,tmphist);\n }\n gsl_histogram_free (tmphist);\n }\n\n\n /* get quantile cutoff */\n gsl_histogram_pdf *pdf = gsl_histogram_pdf_alloc(nbins);\n gsl_histogram_pdf_init(pdf,histogram);\n double lower=0,upper=0;\n\n size_t i0=0;\n for (i=nbins-1; i>=0; i--) {\n gsl_histogram_get_range (histogram,i,&lower,&upper);\n if (pdf->sum[i] < quantile) {\n if (gsl_histogram_get_range (histogram,i,&lower,&upper) == GSL_EDOM) VError(\" err hist\");\n i0 = i;\n break;\n }\n }\n double sum=0;\n for (i=nbins-1; i>i0; i--) {\n sum += gsl_histogram_get(histogram,i);\n }\n return (float)upper;\n}\n", "meta": {"hexsha": "9f4923082c54501b20b250cd4feea18ba5ad30e2", "size": 7668, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ted/vted/ZMatrix.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/ted/vted/ZMatrix.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/ted/vted/ZMatrix.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 25.9054054054, "max_line_length": 106, "alphanum_fraction": 0.6078508086, "num_tokens": 2650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.41271188122389924}} {"text": "/* randist/pascal.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n\n/* The Pascal distribution is a negative binomial with valued integer n\n\n prob(k) = (n - 1 + k)!/(n!(k - 1)!) * p^n (1-p)^k for k = 0, 1, ..., n\n\n */\n\nunsigned int\ngsl_ran_pascal (const gsl_rng * r, double p, unsigned int n)\n{\n /* This is a separate interface for the pascal distribution so that\n it can be optimized differently from the negative binomial in\n future.\n \n e.g. if n < 10 it might be faster to generate the Pascal\n distributions as the sum of geometric variates directly. */\n \n unsigned int k = gsl_ran_negative_binomial (r, p, (double) n);\n return k;\n}\n\ndouble\ngsl_ran_pascal_pdf (const unsigned int k, const double p, unsigned int n)\n{\n double P = gsl_ran_negative_binomial_pdf (k, p, (double) n);\n return P;\n}\n", "meta": {"hexsha": "38a25a42a8914ed7dc124ff8bfdf6f316227a030", "size": 1685, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/pascal.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/pascal.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/pascal.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 33.0392156863, "max_line_length": 81, "alphanum_fraction": 0.7050445104, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.41247126168223175}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define NXPA 10\n\ntypedef struct _Box {\n double x;\n double y;\n double fwhm;\n double cenx;\n double ceny;\n double counts;\n double background;\n double noise;\n double sigmaxythresh;\n double snr;\n double sigmaxy;\n double sigmafwhmthresh;\n double sigmafwhm;\n double strehl;\n double max;\n int r;\n} Box;\n\ntypedef struct _Back {\n double x;\n double y;\n double background;\n double sigma;\n int r;\n int width;\n} Back;\n\nBox box[3];\nBack back;\nlong nelements, naxes[2], fpixel;\nint boxsize = 17;\n\n/* MASSDIMM values */\n/* 20101228: determined DIMM pixel scale to be 1.78\"/pixel using HR1866 \n and HR8895 as astrometric double stars\n*/\ndouble pixel_scale = 1.78;\ndouble d = 0.080;\ndouble r = 0.170;\n\ndouble lambda = 0.6e-6;\n\ndouble stardist(int i, int j) {\n return( sqrt( (box[i].cenx-box[j].cenx)*(box[i].cenx-box[j].cenx) +\n\t\t (box[i].ceny-box[j].ceny)*(box[i].ceny-box[j].ceny) ) );\n}\n\n/* this routine uses a. tokovinin's modified equation given in\n 2002, PASP, 114, 1156\n */\ndouble seeing(double var) {\n double b, K, seeing;\n \n b = r/d;\n \n /* pixel scale in \"/pixel, convert to rad */\n var = var * pow(pixel_scale/206265.0, 2);\n \n K = 0.364 * (1.0 - 0.532 * pow(b, -1/3) - 0.024 * pow(b, -7/3));\n \n seeing = 206265.0 * 0.98 * pow(d/lambda, 0.2) * pow(var/K, 0.6);\n \n return seeing;\n}\n\n/* this routine uses the classic DIMM equation */\ndouble old_seeing(double var) {\n double r0;\n \n /* pixel scale in \"/pixel, convert to rad */\n var = var * pow(pixel_scale/206265.0, 2);\n \n r0 = pow(2.0 * (lambda * lambda) * ( \n\t\t ( 0.1790 * pow(d, -1.0/3.0) - \n\t\t 0.0968 * pow(r, -1.0/3.0) ) / var \n\t\t ), 0.6);\n \n // return 206265.0*0.98*lambda/r0;\n return r0;\n}\n\n/* measure the background in an annulus around the spot pattern */\nint background(unsigned char *image, int imwidth, int imheight) {\n int i, j, backpix;\n int low_y, up_y, low_x, up_x;\n double dist, sum, sumsq;\n \n backpix = 0;\n sum = 0.0;\n sumsq = 0.0;\n \n low_y = back.y - back.r - back.width;\n up_y = back.y + back.r + back.width;\n low_x = back.x - back.r - back.width;\n up_x = back.x + back.r + back.width;\n if (low_y < 0) {\n\tlow_y = 0;\n }\n if (up_y >= imheight) {\n\tup_y = imheight;\n }\n if (low_x < 0) {\n\tlow_x = 0;\n }\n if (up_x >= imwidth) {\n\tup_x = imwidth;\n }\n \n for (i=low_y; i= back.r && dist <= back.r+back.width) {\n\t\tsum += image[i*naxes[0]+j];\n\t\tbackpix++;\n\t }\n\t}\n }\n \n back.background = sum/backpix;\n //back.background = 0.0;\n\n for (i=low_y; i= back.r && dist <= back.r+back.width) {\n\t\tsumsq += (image[i*naxes[0]+j]-back.background)*\n\t\t (image[i*naxes[0]+j]-back.background);\n\t }\n\t}\n }\n \n back.sigma = sqrt(sumsq/backpix);\n //back.sigma = 1.0;\n \n return 1;\n}\n\n/* measure centroid using center-of-mass algorithm */\nint centroid(unsigned char *image, int imwidth, int imheight, int num) {\n int i, j;\n double max = 0.0;\n double sum = 0.0;\n double sumx = 0.0;\n double sumxx = 0.0;\n double sumy = 0.0;\n double sumyy = 0.0;\n double val = 0.0;\n double gain = 0.9;\n double rmom;\n double dist, dx;\n double nsigma = 3.0;\n int low_y, up_y, low_x, up_x;\n int sourcepix = 0;\n\n dx = pixel_scale/206265.0;\n \n low_y = box[num].y - box[num].r;\n up_y = box[num].y + box[num].r;\n low_x = box[num].x - box[num].r;\n up_x = box[num].x + box[num].r;\n if (low_y < 0) {\n\tlow_y = 0;\n }\n if (up_y >= imheight) {\n\tup_y = imheight;\n }\n if (low_x < 0) {\n\tlow_x = 0;\n }\n if (up_x >= imwidth) {\n\tup_x = imwidth;\n }\n \n for (i=low_y; i= nsigma*back.sigma) {\n\t\t if (val > max) {\n\t\t\tmax = val;\n\t\t }\n\t\t sum += val;\n\t\t sumx += val*j;\n\t\t sumxx += val*j*j;\n\t\t sumy += val*i;\n\t\t sumyy += val*i*i;\n\t\t sourcepix++;\n\t\t}\n\t }\n\t}\n }\n \n if ( sum <= 0.0 ) {\n\tbox[num].sigmaxy = -1.0;\n\tbox[num].sigmafwhm = -1.0;\n\tbox[num].snr = 0.0;\n\tbox[num].fwhm = -1.0;\n\tbox[num].counts = 1.0;\n\tbox[num].strehl = 0.0;\n } else {\n\tbox[num].max = max;\n\tbox[num].strehl = (max/sum)*(4.0/3.14159)*pow( lambda/(d*dx), 2);\n\trmom = ( sumxx - sumx * sumx / sum + sumyy - sumy * sumy / sum ) / sum;\n \n\tif ( rmom <= 0 ) {\n\t box[num].fwhm = -1.0;\n } else {\n\t box[num].fwhm = sqrt(rmom) * 2.354 / sqrt(2.0);\n }\n \n box[num].counts = sum;\n box[num].cenx = sumx / sum;\n box[num].ceny = sumy / sum;\n box[num].noise = back.sigma*sourcepix;\n box[num].x += gain*(box[num].cenx - box[num].x);\n box[num].y += gain*(box[num].ceny - box[num].y);\n box[num].snr = sum/sqrt(box[num].noise*box[num].noise + sum);\n box[num].sigmaxy = 1.0 / box[num].snr / sqrt(6.0);\n box[num].sigmafwhm = back.sigma * pow(sourcepix,1.5) / 10.\n\t/ box[num].fwhm / box[num].counts\n\t* 2.354 * 2.354 / 2.0;\n } \n \n return 1;\n \n}\n\nint grab_frame(dc1394camera_t *c, unsigned char *buf, int nbytes) {\n dc1394video_frame_t *frame=NULL;\n dc1394error_t err;\n \n err = dc1394_capture_dequeue(c, DC1394_CAPTURE_POLICY_WAIT, &frame);\n if (err != DC1394_SUCCESS) {\n\tdc1394_log_error(\"Unable to capture.\");\n\tdc1394_capture_stop(c);\n\tdc1394_camera_free(c);\n\texit(1);\n }\n memcpy(buf, frame->image, nbytes);\n dc1394_capture_enqueue(c, frame);\n return 1;\n}\n\nint add_gaussian(unsigned char *buffer, float cenx, float ceny, float a, float sigma) {\n float gauss, rsq;\n int i, j, low_x, up_x, low_y, up_y, size;\n double xoff, yoff;\n\n xoff = 2.0*drand48() - 1.0;\n yoff = 2.0*drand48() - 1.0;\n \n cenx += 0.5*xoff;\n ceny += 0.5*yoff;\n \n size = 30;\n low_x = (int)(cenx-size);\n up_x = (int)(cenx+size);\n low_y = (int)(ceny-size);\n up_y = (int)(ceny+size);\n \n for (i=low_y; i 255) \n\t\tgauss = 255;\n\t buffer[i*naxes[0]+j] += (unsigned char)gauss;\n\t}\n }\n \n return 1;\n}\n\nint main(int argc, char *argv[]) {\n dc1394_t * dc;\n dc1394camera_t * camera;\n dc1394camera_list_t * list;\n dc1394error_t err;\n dc1394video_mode_t mode;\n unsigned int max_height, max_width, winleft, wintop;\n uint64_t total_bytes = 0;\n unsigned char *buffer, *buffer2, *average;\n char *names[NXPA];\n char *messages[NXPA];\n char filename[256], xpastr[256];\n char *froot;\n fitsfile *fptr;\n int i, j, f, fstatus, status, nimages, nboxes, test, xsize, ysize;\n int nbad = 0, nbad_l = 0;\n FILE *init, *out, *cenfile;\n float xx = 0.0, yy = 0.0, xsum = 0.0, ysum = 0.0;\n float elapsed_time, fps, avemax;\n double *dist, *sig, *dist_l, *sig_l, *weight, *weight_l;\n double mean, var, var_l, avesig, airmass, exptime;\n double r0, seeing_short, seeing_long, seeing_ave;\n struct timeval start_time, end_time;\n struct tm ut;\n time_t start_sec, end_sec;\n suseconds_t start_usec, end_usec;\n\n srand48((unsigned)time(NULL));\n \n XPA xpa;\n xpa = XPAOpen(NULL);\n \n stderr = freopen(\"measure_seeing.log\", \"w\", stderr);\n \n if (argc <= 3) {\n\tprintf(\"Usage: measure_seeing \\n\");\n\texit(-1);\n }\n \n nimages = atoi(argv[1]);\n airmass = atof(argv[2]);\n exptime = atof(argv[3]);\n fstatus = 0;\n status = 0;\n xsize = 320;\n ysize = 240;\n naxes[0] = xsize;\n naxes[1] = ysize;\n fpixel = 1;\n\n fps = 1.0/exptime;\n if (fps > 330.0) {\n\tfps = 330.0;\n }\n\n nelements = naxes[0]*naxes[1];\n \n mode = DC1394_VIDEO_MODE_FORMAT7_1;\n dc = dc1394_new();\n if (!dc)\n\treturn -1;\n err = dc1394_camera_enumerate(dc, &list);\n DC1394_ERR_RTN(err, \"Failed to enumerate cameras.\");\n \n if (list->num == 0) {\n\tdc1394_log_error(\"No cameras found.\");\n\treturn -1;\n }\n \n camera = dc1394_camera_new(dc, list->ids[0].guid);\n if (!camera) {\n\tdc1394_log_error(\"Failed to initialize camera with guid %\"PRIx64\".\", \n\t\t\t list->ids[0].guid);\n\treturn -1;\n }\n dc1394_camera_free_list(list);\n \n printf(\"Using camera with GUID %\"PRIx64\"\\n\", camera->guid);\n \n // need to use legacy firewire400 mode for now. 800 not quite reliable.\n dc1394_video_set_iso_speed(camera, DC1394_ISO_SPEED_400);\n \n // configure camera for format7\n err = dc1394_video_set_mode(camera, mode);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"Can't choose video mode.\");\n err = dc1394_format7_get_max_image_size(camera, mode, &max_width, &max_height);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"cannot get max image size.\");\n \n winleft = 0;\n wintop = 0;\n\n err = dc1394_format7_set_roi(camera,\n\t\t\t\t mode,\n\t\t\t\t DC1394_COLOR_CODING_MONO8,\n\t\t\t\t DC1394_USE_MAX_AVAIL,\n\t\t\t\t winleft, wintop, // left, top\n\t\t\t\t xsize, ysize);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"Can't set ROI.\");\n \n // set the frame rate to absolute value in frames/sec\n err = dc1394_feature_set_mode(camera, DC1394_FEATURE_FRAME_RATE,\n\t\t\t\t DC1394_FEATURE_MODE_MANUAL);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free (camera), \"cannot set framerate to manual\");\n err = dc1394_feature_set_absolute_control(camera,\n\t\t\t\t\t DC1394_FEATURE_FRAME_RATE, DC1394_TRUE);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free (camera),\n\t\t \"cannot set framerate to absolute mode\");\n err = dc1394_feature_set_absolute_value(camera, DC1394_FEATURE_FRAME_RATE, fps);\n DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot set framerate\");\n printf(\"I: framerate is %f fps\\n\", fps);\n \n // set the shutter speed to absolute value in seconds \n err = dc1394_feature_set_mode(camera, DC1394_FEATURE_SHUTTER, DC1394_FEATURE_MODE_MANUAL);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"cannot set shutter to manual\");\n err = dc1394_feature_set_absolute_control(camera, DC1394_FEATURE_SHUTTER, DC1394_TRUE);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"cannot set shutter to absolute mode\");\n err = dc1394_feature_set_absolute_value(camera, DC1394_FEATURE_SHUTTER, exptime);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"cannot set shutter\");\n printf(\"I: exptime is %f s\\n\", exptime);\n \n // set gain manually. use relative value here in range 48 to 730. \n err = dc1394_feature_set_mode(camera, DC1394_FEATURE_GAIN, DC1394_FEATURE_MODE_MANUAL);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"cannot set gain to manual\");\n err = dc1394_feature_set_value(camera, DC1394_FEATURE_GAIN, 400);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"cannot set gain\");\n \n // set brightness manually. use relative value in range 0 to 1023.\n err = dc1394_feature_set_mode(camera, DC1394_FEATURE_BRIGHTNESS, DC1394_FEATURE_MODE_MANUAL);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"cannot set brightness to manual\");\n err = dc1394_feature_set_value(camera, DC1394_FEATURE_BRIGHTNESS, 100);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"cannot set brightness\");\n \n err = dc1394_format7_get_total_bytes(camera, DC1394_VIDEO_MODE_FORMAT7_1, &total_bytes);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"Can't get total bytes.\");\n \n err = dc1394_capture_setup(camera, 16, DC1394_CAPTURE_FLAGS_DEFAULT);\n DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"Error capturing.\");\n \n // start the camera up\n err = dc1394_video_set_transmission(camera, DC1394_ON);\n if (err != DC1394_SUCCESS) {\n\tdc1394_log_error(\"Unable to start camera iso transmission.\");\n\tdc1394_capture_stop(camera);\n\tdc1394_camera_free(camera);\n\treturn -1;\n }\n\n printf(\"Camera successfully initialized.\\n\");\n \n out = fopen(\"seeing.dat\", \"a\");\n cenfile = fopen(\"centroids.dat\", \"w\");\n init = fopen(\"init_cen_all\", \"r\");\n \n i = 0;\n while (fscanf(init, \"%f %f\\n\", &xx, &yy) != EOF) {\n\tbox[i].x = xx;\n\tbox[i].cenx = xx;\n\tbox[i].y = yy;\n\tbox[i].ceny = yy;\n\tbox[i].r = boxsize/2.0;\n\ti++;\n }\n nboxes = i;\n fclose(init); \n \n back.r = 60;\n back.width = 10;\n\n /* allocate the buffers */\n if (!(dist = calloc(nimages, sizeof(double)))) {\n\tprintf(\"Couldn't allocate dist array.\\n\");\n\texit(-1);\n }\n if (!(sig = calloc(nimages, sizeof(double)))) {\n\tprintf(\"Couldn't allocate sig array.\\n\");\n\texit(-1);\n }\n if (!(weight = calloc(nimages, sizeof(double)))) {\n\tprintf(\"Couldn't allocate sig array.\\n\");\n\texit(-1);\n }\n if (!(weight_l = calloc(nimages, sizeof(double)))) {\n\tprintf(\"Couldn't allocate sig array.\\n\");\n\texit(-1);\n }\n if (!(dist_l = calloc(nimages, sizeof(double)))) {\n\tprintf(\"Couldn't allocate dist_l array.\\n\");\n\texit(-1);\n }\n if (!(sig_l = calloc(nimages, sizeof(double)))) {\n\tprintf(\"Couldn't allocate sig_l array.\\n\");\n\texit(-1);\n }\n if (!(buffer = malloc(nelements*sizeof(char)))) {\n\tprintf(\"Couldn't Allocate Image Buffer\\n\");\n\texit(-1);\n }\n if (!(buffer2 = malloc(nelements*sizeof(char)))) {\n\tprintf(\"Couldn't Allocate 2nd Image Buffer\\n\");\n\texit(-1);\n }\n if (!(average = malloc(nelements*sizeof(char)))) {\n\tprintf(\"Couldn't Allocate Average Image Buffer\\n\");\n\texit(-1);\n }\n \n froot = \"seeing.fits\";\n avemax = 0.0;\n\n /* get initial frame */\n grab_frame(camera, buffer2, nelements*sizeof(char));\n grab_frame(camera, buffer2, nelements*sizeof(char));\n grab_frame(camera, buffer2, nelements*sizeof(char));\n grab_frame(camera, buffer2, nelements*sizeof(char));\n // add_gaussian(buffer2, 195.0, 130.0, 140.0, 1.5);\n // add_gaussian(buffer2, 140.0, 115.0, 140.0, 1.5);\n\n gettimeofday(&start_time, NULL);\n\n for (f=0; f 55.0 || dist[f] < 15.0) {\n\t weight[f] = 0.0;\n\t}\n\n\tif (box[0].fwhm > 0.0 && box[1].fwhm > 0.0) {\n\t for (i=0; i box[1].max) {\n\t\tavemax += box[0].max;\n\t } else {\n\t\tavemax += box[1].max;\n\t }\n\t}\n \n\t/* now average two exposures */\n\tfor (j=0; j 100.0) {\n if (exptime > 1.0e-3) {\n\texptime -= 1.0e-3;\n } else {\n\texptime /= 2.0;\n }\n printf(\"\\033[0;33mStar too bright, reducing exposure time to %.1e seconds.\\033[0;39m\\n\", exptime);\n }\n\n /* increase if too faint, but max out at 8 ms */\n if (avemax < 25.0) {\n if (exptime >= 1.0e-3) {\n\texptime += 1.0e-3;\n } else {\n\texptime *= 2.0;\n }\n if (exptime > 8.0e-3) {\n\texptime = 8.0e-3;\n\tprintf(\"\\033[0;33mStar too faint, but exposure time max'ed out at %.1e seconds.\\033[0;39m\\n\", \n\t exptime);\n } else {\n\tprintf(\"\\033[0;33mStar too faint, exposure time increased to %.1e seconds.\\033[0;39m\\n\", \n\t exptime);\n }\n }\n\n init = fopen(\"exptime\", \"w\");\n fprintf(init, \"%.2e\\n\", exptime);\n fclose(init);\n\n if (nbad < 30) {\n\tseeing_ave = pow(seeing_short, 1.75)*pow(seeing_long,-0.75);\n\tprintf(\"\\033[0;32mAirmass corrected seeing = %4.2f\\\"\\033[0;39m\\n\\n\", seeing_short);\n\tprintf(\"\\033[0;32mFried Parameter, R0 = %.2f cm\\033[0;39m\\n\\n\", 100*r0);\n \n\tgmtime_r(&end_sec, &ut);\n\tfprintf(out, \"%d-%02d-%02d %02d:%02d:%02d %f %f %f %f %f %f\\n\", \n\t\tut.tm_year+1900,\n\t\tut.tm_mon+1,\n\t\tut.tm_mday,\n\t\tut.tm_hour,\n\t\tut.tm_min,\n\t\tut.tm_sec,\n\t\tvar,\n\t\tvar_l,\n\t\tseeing_short,\n\t\tseeing_long,\n\t\tseeing_ave,\n\t\tairmass);\n \n\tinit = fopen(\"init_cen_all\", \"w\");\n\tfor (i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define NUM_THREAD 1\n#define min(a,b) ((a)>(b)?(b):(a))\n#define VERBOSE ((int) 1)\n\n#ifndef HEAD\n#define HEAD ((int) 0)\n#endif\n\n#define BUF ((int) 2)\n\n\n\n\ntensor_train* TT_init(const int d, const int* restrict n)\n{\n tensor_train* sim = (tensor_train*) malloc(sizeof(tensor_train));\n sim->d = d;\n sim->n = (int*) malloc(sizeof(int)*d);\n sim->r = (int*) malloc(sizeof(int)*(d+1));\n sim->trains = (double**) malloc(sizeof(double*)*d);\n\n sim->r[0] = 1;\n for (int j = 0; j < d; ++j) {\n sim->n[j] = n[j];\n\n if (j < d-1) {\n sim->r[j+1] = n[j];\n }\n }\n sim->r[d] = 1;\n\n for (int j = 0; j < d; ++j) {\n sim->trains[j] = (double*) malloc(sizeof(double)*(sim->r[j])*(sim->n[j])*(sim->r[j+1]));\n }\n\n return sim;\n}\n\ntensor_train* TT_init_rank(const int d, const int* restrict n, const int* restrict r)\n{\n tensor_train* sim = (tensor_train*) malloc(sizeof(tensor_train));\n sim->d = d;\n sim->n = (int*) malloc(sizeof(int)*d);\n sim->r = (int*) malloc(sizeof(int)*(d+1));\n sim->trains = (double**) malloc(sizeof(double*)*d);\n\n for (int j = 0; j < d; ++j) {\n sim->n[j] = n[j];\n }\n for (int j = 0; j < d+1; ++j) {\n sim->r[j] = r[j];\n }\n\n for (int j = 0; j < d; ++j) {\n sim->trains[j] = (double*) malloc(sizeof(double)*(sim->r[j])*(sim->n[j])*(sim->r[j+1]));\n }\n\n return sim;\n}\n\ntensor_train* TT_copy(tensor_train* X)\n{\n int d = X->d;\n int* n = X->n;\n int* r = X->r;\n tensor_train* Y = TT_init_rank(d, n, r);\n for (int j = 0; j < X->d; ++j) {\n int N = r[j] * n[j] * r[j+1];\n memcpy(Y->trains[j], X->trains[j], N * sizeof(double));\n }\n\n return Y;\n}\n\nvoid TT_free(tensor_train* sim)\n{\n for (int j = 0; j < sim->d; ++j) {\n free(sim->trains[j]); sim->trains[j] = NULL;\n }\n free(sim->trains); sim->trains = NULL;\n free(sim->r); sim->r = NULL;\n free(sim->n); sim->n = NULL;\n free(sim);\n}\n\nvoid TT_print(tensor_train* tt)\n{\n\n int d = tt->d;\n int* n = tt->n;\n int* r = tt->r;\n double** trains = tt->trains;\n printf(\"Printing the tensor train with d = %d\\n\",d);\n\n for (int ii = 0; ii < d; ++ii){\n printf(\"\\nTensor %d/d (r[%d] = %d, n[%d]=%d, r[%d]=%d):\\n\",ii,ii,r[ii],ii,n[ii],ii+1,r[ii+1]);\n matrix_tt* A = matrix_tt_wrap(r[ii], n[ii] * r[ii+1], trains[ii]);\n matrix_tt_print(A, 1);\n free(A); A = NULL;\n }\n}\n\nvoid tt_broadcast(MPI_Comm comm, tensor_train* tt){\n for (int ii = 0; ii < tt->d; ++ii){\n matrix_tt* A = matrix_tt_wrap((tt->r[ii]) * (tt->n[ii]) * (tt->r[ii+1]), 1, tt->trains[ii]);\n matrix_tt_broadcast(comm, A);\n free(A);\n }\n}\n\n\ndouble get_compression(const tensor_train* tt)\n{\n long N = 1;\n for (int ii = 0; ii < tt->d; ++ii)\n {\n N = N * tt->n[ii];\n }\n\n long Ntt = 0;\n for (int ii = 0; ii < tt->d; ++ii)\n {\n Ntt = Ntt + ((tt->r[ii])*(tt->n[ii])*(tt->r[ii+1]));\n }\n\n double compression = (double) Ntt/N;\n return compression;\n}\n\n", "meta": {"hexsha": "eefd45d2024f9bd83bda1ce4bdc44cc0948d333b", "size": 3220, "ext": "c", "lang": "C", "max_stars_repo_path": "src/tt.c", "max_stars_repo_name": "SidShi/Parallel_TT_sketching", "max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tt.c", "max_issues_repo_name": "SidShi/Parallel_TT_sketching", "max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tt.c", "max_forks_repo_name": "SidShi/Parallel_TT_sketching", "max_forks_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8368794326, "max_line_length": 102, "alphanum_fraction": 0.5065217391, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584174871563662, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4122511074185068}} {"text": "/**\n * tlibs2\n * (container-agnostic) math library\n * @author Tobias Weber , \n * @date 2017-2021\n * @license GPLv3, see 'LICENSE' file\n *\n * @note The present version was forked on 8-Nov-2018 from my privately developed \"magtools\" project (https://github.com/t-weber/magtools).\n * @note Additional functions forked on 7-Nov-2018 from my privately and TUM-PhD-developed \"tlibs\" project (https://github.com/t-weber/tlibs).\n * @note Further functions and updates forked on 1-Feb-2021 and 19-Apr-2021 from my privately developed \"geo\" and \"misc\" projects (https://github.com/t-weber/geo and https://github.com/t-weber/misc).\n *\n * @desc for the references, see the 'LITERATURE' file\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021 Tobias WEBER (Institut Laue-Langevin (ILL),\n * Grenoble, France).\n * Copyright (C) 2015-2017 Tobias WEBER (Technische Universitaet Muenchen\n * (TUM), Garching, Germany).\n * \"magtools\", \"geo\", and \"misc\" projects\n * Copyright (C) 2017-2021 Tobias WEBER (privately developed).\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n * ----------------------------------------------------------------------------\n */\n\n#ifndef __TLIBS2_CXX20_MATH_ALGOS_H__\n#define __TLIBS2_CXX20_MATH_ALGOS_H__\n\n//#define USE_LAPACK\n#define __TLIBS2_QR_METHOD 0\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if __has_include()\n\t#include \n\n\t#define __TLIBS2_USE_NUMBERS__\n#endif\n\n#include \n#include \n#include \n#include \n\n#include \"log.h\"\n#include \"str.h\"\n#include \"bits.h\"\n#include \"traits.h\"\n\n#if __has_include() && USE_LAPACK\n\textern \"C\"\n\t{\n\t\t#define lapack_complex_double std::complex\n\t\t#define lapack_complex_double_real(z) (z.real())\n\t\t#define lapack_complex_double_imag(z) (z.imag())\n\n\t\t#define lapack_complex_float std::complex\n\t\t#define lapack_complex_float_real(z) (z.real())\n\t\t#define lapack_complex_float_imag(z) (z.imag())\n\n\t\t#include \n\t}\n\n\t#define __TLIBS2_USE_LAPACK__\n#else\n\t#pragma message(\"tlibs2: Disabling Lapack(e) library (not found).\")\n#endif\n\n#if __has_include()\n\t#include \n\tusing t_real_fadd = double;\n\n\t#define __TLIBS2_USE_FADDEEVA__\n#else\n\t#pragma message(\"tlibs2: Disabling Faddeeva library (not found).\")\n#endif\n\n#if __has_include()\n\t#include \n\t#include \n\t#include \n\n\t#define __TLIBS2_USE_QHULL__\n#else\n\t#pragma message(\"tlibs2: Disabling QHull library (not found).\")\n#endif\n\n// separator tokens\n#define TL2_COLSEP ';'\n#define TL2_ROWSEP '|'\n\n\nnamespace tl2 {\n// ----------------------------------------------------------------------------\n// forward declarations\n// ----------------------------------------------------------------------------\ntemplate\nt_mat prod(const t_mat& mat1, const t_mat& mat2, bool assert_sizes=true)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat;\n\ntemplate\nt_mat zero(std::size_t N1, std::size_t N2)\nrequires is_basic_mat;\n\ntemplate\nt_vec zero(std::size_t N=0)\nrequires is_basic_vec;\n\ntemplate\nstd::tuple qr(const t_mat& mat)\nrequires is_mat && is_vec;\n\ntemplate\nstd::tuple inv(const t_mat& mat)\nrequires is_mat;\n\ntemplate\ntypename t_mat::value_type det(const t_mat& mat)\nrequires is_mat;\n// ----------------------------------------------------------------------------\n\n\n// ----------------------------------------------------------------------------\n// helpers and constants\n// ----------------------------------------------------------------------------\n\n// constants\n#ifdef __TLIBS2_USE_NUMBERS__\n\ttemplate constexpr T golden{std::numbers::phi_v};\n\ttemplate constexpr T pi{std::numbers::pi_v};\n#else\n\t// see: https://en.wikipedia.org/wiki/Golden_ratio\n\ttemplate constexpr T golden{1.618033988749895};\n\ttemplate constexpr T pi{M_PI};\n#endif\n\n// constant calculated using scipy:\n// import scipy.constants as co\n// E_to_k2 = 2.*co.neutron_mass/(co.Planck/co.elementary_charge*1000./2./co.pi)**2. / co.elementary_charge*1000. * 1e-20\ntemplate constexpr T E_to_k2 = 0.482596423544;\n\n\ntemplate bool is_even(INT i) { return (i%2 == 0); }\ntemplate bool is_odd(INT i) { return !is_even(i); }\n\ntemplate constexpr T r2d(T rad) { return rad/pi*T(180); }\t// rad -> deg\ntemplate constexpr T d2r(T deg) { return deg/T(180)*pi; }\t// deg -> rad\ntemplate constexpr T r2m(T rad) { return rad/pi*T(180*60); }\t// rad -> min\ntemplate constexpr T m2r(T min) { return min/T(180*60)*pi; }\t// min -> rad\n\n/**\n * Gaussian around 0: f(x) = exp(-1/2 * (x/sig)^2)\n * at hwhm: f(x_hwhm) = 1/2\n * exp(-1/2 * (x_hwhm/sig)^2) = 1/2\n * -1/2 * (x_hwhm/sig)^2 = ln(1/2)\n * (x_hwhm/sig)^2 = -2*ln(1/2)\n * x_hwhm^2 = sig^2 * 2*ln(2)\n */\ntemplate static constexpr T SIGMA2FWHM = T(2)*std::sqrt(T(2)*std::log(T(2)));\ntemplate static constexpr T SIGMA2HWHM = std::sqrt(T(2)*std::log(T(2)));\ntemplate static constexpr T FWHM2SIGMA = T(1)/SIGMA2FWHM;\ntemplate static constexpr T HWHM2SIGMA = T(1)/SIGMA2HWHM;\n\n\ntemplate T sign(T t)\n{\n\tif(t<0.) return -T(1);\n\treturn T(1);\n}\n\n\ntemplate T cot(T t)\n{\n\treturn std::tan(T(0.5)*pi - t);\n}\n\n\ntemplate T coth(T t)\n{\n\treturn T(1) / std::tanh(t);\n}\n\n\ntemplate\nT log(T tbase, T tval)\n{\n\treturn T(std::log(tval)/std::log(tbase));\n}\n\n\ntemplate\nT nextpow(T tbase, T tval)\n{\n\treturn T(std::pow(tbase, std::ceil(log(tbase, tval))));\n}\n\n\ntemplate\nT lerp(const T& a, const T& b, REAL val)\n{\n\treturn a + T((b-a)*val);\n}\n\n\n/**\n * unsigned angle between two vectors\n * / (|q1| |q2|) = cos(alpha)\n */\ntemplate\ntypename t_vec::value_type angle_unsigned(const t_vec& q1, const t_vec& q2)\nrequires is_basic_vec\n{\n\tusing t_real = typename t_vec::value_type;\n\n\tif(q1.size() != q2.size())\n\t\treturn t_real(0);\n\n\tt_real dot = t_real(0);\n\tt_real len1 = t_real(0);\n\tt_real len2 = t_real(0);\n\n\tfor(std::size_t i=0; i / (|q1| |q2|) = cos(alpha)\n */\ntemplate\ntypename t_quat::value_type angle_unsigned(const t_quat& q1, const t_quat& q2)\nrequires is_quat\n{\n\tusing t_real = typename t_quat::value_type;\n\n\tt_real dot = q1.R_component_1() * q2.R_component_1() +\n\t\tq1.R_component_2() * q2.R_component_2() +\n\t\tq1.R_component_3() * q2.R_component_3() +\n\t\tq1.R_component_4() * q2.R_component_4();\n\n\tt_real len1 = q1.R_component_1() * q1.R_component_1() +\n\t\tq1.R_component_2() * q1.R_component_2() +\n\t\tq1.R_component_3() * q1.R_component_3() +\n\t\tq1.R_component_4() * q1.R_component_4();\n\n\tt_real len2 = q2.R_component_1() * q2.R_component_1() +\n\t\tq2.R_component_2() * q2.R_component_2() +\n\t\tq2.R_component_3() * q2.R_component_3() +\n\t\tq2.R_component_4() * q2.R_component_4();\n\n\tlen1 = std::sqrt(len1);\n\tlen2 = std::sqrt(len2);\n\n\tdot /= len1;\n\tdot /= len2;\n\n\treturn std::acos(dot);\n}\n\n\n\n/**\n * slerp\n * @see K. Shoemake, \"Animating rotation with quaternion curves\", http://dx.doi.org/10.1145/325334.325242\n * @see (Desktop Bronstein 2008), formula 4.207\n * @see (Bronstein 2008), p. 306, formula 4.155\n */\ntemplate\nT slerp(const T& q1, const T& q2, typename T::value_type t)\n{\n\tusing t_real = typename T::value_type;\n\tt_real angle = angle_unsigned(q1, q2);\n\n\tT q = std::sin((t_real(1)-t)*angle)/std::sin(angle) * q1 +\n\tstd::sin(t*angle)/std::sin(angle) * q2;\n\n\treturn q;\n}\n\n\n\n/**\n * x = 0..1\n */\ntemplate\nT linear_interp(T x0, T x1, T x)\n{\n\treturn lerp(x0, x1, x);\n}\n\n\n/**\n * x = 0..1, y = 0..1\n */\ntemplate\nT bilinear_interp(T x0y0, T x1y0, T x0y1, T x1y1, T x, T y)\n{\n\tT top = linear_interp(x0y1, x1y1, x);\n\tT bottom = linear_interp(x0y0, x1y0, x);\n\n\treturn linear_interp(bottom, top, y);\n}\n\n\ntemplate class t_vec = std::vector>\nt_vec linspace(const T& tmin, const T& tmax, std::size_t iNum)\n{\n\tt_vec vec;\n\tvec.reserve(iNum);\n\n\tfor(std::size_t i=0; i(tmin, tmax, REAL(i)/REAL(iNum-1)));\n\treturn vec;\n}\n\n\ntemplate class t_vec = std::vector>\nt_vec logspace(const T& tmin, const T& tmax, std::size_t iNum, T tBase=T(10))\n{\n\tt_vec vec = linspace(tmin, tmax, iNum);\n\n\tfor(T& t : vec)\n\t\tt = std::pow(tBase, t);\n\treturn vec;\n}\n\n\ntemplate\nT clamp(T t, T min, T max)\n{\n\tif(t < min) t = min;\n\tif(t > max) t = max;\n\n\treturn t;\n}\n\n\ntemplate\nbool is_in_range(T val, T centre, T pm)\n{\n\tpm = std::abs(pm);\n\n\tif(val < centre-pm) return false;\n\tif(val > centre+pm) return false;\n\treturn true;\n}\n\n\n/**\n * point contained in linear range?\n */\ntemplate\nbool is_in_linear_range(T dStart, T dStop, T dPoint)\n{\n\tif(dStop < dStart)\n\t\tstd::swap(dStart, dStop);\n\n\treturn (dPoint >= dStart) && (dPoint <= dStop);\n}\n\n\n/**\n * angle contained in angular range?\n */\ntemplate\nbool is_in_angular_range(T dStart, T dRange, T dAngle)\n{\n\tif(dStart < T(0)) dStart += T(2)*pi;\n\tif(dAngle < T(0)) dAngle += T(2)*pi;\n\n\tdStart = std::fmod(dStart, T(2)*pi);\n\tdAngle = std::fmod(dAngle, T(2)*pi);\n\n\tT dStop = dStart + dRange;\n\n\n\t// if the end point is contained in the circular range\n\tif(dStop < T(2)*pi)\n\t{\n\t\treturn is_in_linear_range(dStart, dStop, dAngle);\n\t}\n\t// else end point wraps around\n\telse\n\t{\n\t\treturn is_in_linear_range(dStart, T(2)*pi, dAngle) ||\n\t\t\tis_in_linear_range(T(0), dRange-(T(2)*pi-dStart), dAngle);\n\t}\n}\n\n\n/**\n * converts a string to a scalar value\n */\ntemplate\nt_scalar stoval(const t_str& str)\n{\n\tif constexpr(std::is_same_v)\n\t\treturn std::stof(str);\n\telse if constexpr(std::is_same_v)\n\t\treturn std::stod(str);\n\telse if constexpr(std::is_same_v)\n\t\treturn std::stold(str);\n\telse if constexpr(std::is_same_v)\n\t\treturn std::stoi(str);\n//\telse if constexpr(std::is_same_v)\n//\t\treturn std::stoui(str);\n\telse if constexpr(std::is_same_v)\n\t\treturn std::stol(str);\n\telse if constexpr(std::is_same_v)\n\t\treturn std::stoul(str);\n\telse if constexpr(std::is_same_v)\n\t\treturn std::stoll(str);\n\telse if constexpr(std::is_same_v)\n\t\treturn std::stoull(str);\n\telse\n\t{\n\t\tt_scalar val{};\n\t\tstd::istringstream{str} >> val;\n\t\treturn val;\n\t}\n}\n\n\ntemplate\nt_num get_rand(t_num min=1, t_num max=-1)\n{\n\tstatic std::mt19937 rng{std::random_device{}()};\n\n\tif(max <= min)\n\t{\n\t\tmin = std::numeric_limits::lowest() / 10.;\n\t\tmax = std::numeric_limits::max() / 10.;\n\t}\n\n\tif constexpr(std::is_integral_v)\n\t\treturn std::uniform_int_distribution(min, max)(rng);\n\telse\n\t\treturn std::uniform_real_distribution(min, max)(rng);\n}\n// ----------------------------------------------------------------------------\n\n\n\n// -----------------------------------------------------------------------------\n// peak model functions\n// -----------------------------------------------------------------------------\n/**\n * gaussian\n * @see https://en.wikipedia.org/wiki/Gaussian_function\n */\ntemplate\nT gauss_model(T x, T x0, T sigma, T amp, T offs)\n{\n\tT norm = T(1)/(std::sqrt(T(2)*pi) * sigma);\n\treturn amp * norm * std::exp(-0.5 * ((x-x0)/sigma)*((x-x0)/sigma)) + offs;\n}\n\n\ntemplate\nT gauss_model_amp(T x, T x0, T sigma, T amp, T offs)\n{\n\treturn amp * std::exp(-0.5 * ((x-x0)/sigma)*((x-x0)/sigma)) + offs;\n}\n\n\ntemplate\nT gauss_model_amp_slope(T x, T x0, T sigma, T amp, T offs, T slope)\n{\n\treturn amp * std::exp(-0.5 * ((x-x0)/sigma)*((x-x0)/sigma)) + (x-x0)*slope + offs;\n}\n\n\n/**\n * lorentzian\n * @see https://en.wikipedia.org/wiki/Cauchy_distribution\n */\ntemplate\nT lorentz_model_amp(T x, T x0, T hwhm, T amp, T offs)\n{\n\treturn amp*hwhm*hwhm / ((x-x0)*(x-x0) + hwhm*hwhm) + offs;\n}\n\n\ntemplate\nT lorentz_model_amp_slope(T x, T x0, T hwhm, T amp, T offs, T slope)\n{\n\treturn amp*hwhm*hwhm / ((x-x0)*(x-x0) + hwhm*hwhm) + (x-x0)*slope + offs;\n}\n\n\ntemplate\nT parabola_model(T x, T x0, T amp, T offs)\n{\n\treturn amp*(x-x0)*(x-x0) + offs;\n}\n\n\ntemplate\nT parabola_model_slope(T x, T x0, T amp, T offs, T slope)\n{\n\treturn amp*(x-x0)*(x-x0) + (x-x0)*slope + offs;\n}\n\n\n// -----------------------------------------------------------------------------\ntemplate::value>\nstruct complex_cast\n{\n\tconst std::complex& operator()(const std::complex& c) const\n\t{ return c; }\n};\n\ntemplate\nstruct complex_cast\n{\n\tstd::complex operator()(const std::complex& c) const\n\t{ return std::complex(t_real_to(c.real()), t_real_to(c.imag())); }\n};\n// -----------------------------------------------------------------------------\n\n\n\n// -----------------------------------------------------------------------------\n// Faddeeva function\n// -----------------------------------------------------------------------------\n#ifdef __TLIBS2_USE_FADDEEVA__\n\n/**\n * Complex error function\n */\ntemplate\nstd::complex erf(const std::complex& z)\n{\n\tcomplex_cast cst;\n\tcomplex_cast inv_cst;\n\treturn inv_cst(::Faddeeva::erf(cst(z)));\n}\n\n/**\n * Complex complementary error function\n */\ntemplate\nstd::complex erfc(const std::complex& z)\n{\n\tcomplex_cast cst;\n\tcomplex_cast inv_cst;\n\treturn inv_cst(::Faddeeva::erfc(cst(z)));\n}\n\n/**\n * Faddeeva function\n * @see https://en.wikipedia.org/wiki/Faddeeva_function\n */\ntemplate\nstd::complex faddeeva(const std::complex& z)\n{\n\tstd::complex i(0, 1.);\n\treturn std::exp(-z*z) * erfc(-i*z);\n}\n\n/**\n * Voigt profile\n * @see https://en.wikipedia.org/wiki/Voigt_profile\n */\ntemplate\nT voigt_model(T x, T x0, T sigma, T gamma, T amp, T offs)\n{\n\tT norm = T(1)/(std::sqrt(T(2)*pi) * sigma);\n\tstd::complex z = std::complex(x-x0, gamma) / (sigma * std::sqrt(T(2)));\n\n\treturn amp*norm * faddeeva(z).real() + offs;\n}\n\ntemplate\nT voigt_model_amp(T x, T x0, T sigma, T gamma, T amp, T offs)\n{\n\tstd::complex z = std::complex(x-x0, gamma) / (sigma * std::sqrt(T(2)));\n\treturn amp * faddeeva(z).real() + offs;\n}\n\ntemplate\nT voigt_model_amp_slope(T x, T x0, T sigma, T gamma, T amp, T offs, T slope)\n{\n\tstd::complex z = std::complex(x-x0, gamma) / (sigma * std::sqrt(T(2)));\n\treturn amp * faddeeva(z).real() + (x-x0)*slope + offs;\n}\n\n#endif\n// -----------------------------------------------------------------------------\n\n\n\n// -----------------------------------------------------------------------------\n// physics-related functions\n// -----------------------------------------------------------------------------\n\n/**\n * wrapper for boost's Y function\n */\ntemplate\nstd::complex Ylm(int l /*0..i*/, int m /*-l..l*/, T th /*0..pi*/, T ph /*0..2pi*/)\n{\n\treturn boost::math::spherical_harmonic(l,m, th, ph);\n}\n\n\n\n/**\n * CG coefficients\n * @see (Arfken 2013), p. 790 for the formula\n *\n * e.g. two e- spins: s1 = s2 = 0.5, ms[1,2] = 0.5 (up) or -0.5 (down), S = 0 (sing.) or 1 (trip.)\n */\ntemplate\nT CG_coeff(T S, T s1, T s2, T ms1, T ms2)\n{\n\tT (*fak)(T) = [](T t) -> T { return boost::math::factorial(t); };\n\n\tT tCG = fak(S + s1 - s2)*fak(S - s1 + s2)*fak(-S + s1 + s2);\n\ttCG *= (T(2)*S + T(1));\n\ttCG *= fak(S + ms1 + ms2) * fak(S - (ms1 + ms2));\n\ttCG *= fak(s1 + ms1) * fak(s1 - ms1);\n\ttCG *= fak(s2 + ms2) * fak(s2 - ms2);\n\ttCG /= fak(S + s1 + s2 + T(1));\n\ttCG = std::sqrt(tCG);\n\n\tauto k_fkt = [&](T k) -> T\n\t{\n\t\tT t = std::pow(T(-1), k);\n\t\tt /= fak(k);\n\t\tt /= fak(-S + s1 + s2 - k)*fak(S - s1 - ms2 + k)*fak(S - s2 + ms1 + k);\n\t\tt /= fak(s2 + ms2 - k)*fak(s1 - ms1 - k);\n\t\treturn t;\n\t};\n\n\tauto k_minmax = [&]() -> std::pair\n\t{\n\t\tT kmax = s1 - ms1;\n\t\tkmax = std::min(kmax, s2 + ms2);\n\t\tkmax = std::min(kmax, -S + s1 + s2);\n\n\t\tT kmin = -(S - s1 - ms2);\n\t\tkmin = std::max(kmin, -(S - s2 + ms1));\n\t\tkmin = std::max(kmin, T(0));\n\n\t\treturn std::make_pair(kmin, kmax);\n\t};\n\n\tT kmin, kmax;\n\tstd::tie(kmin, kmax) = k_minmax();\n\tT kfact = T(0);\n\tfor(T k=kmin; k<=kmax; k+=T(1))\n\t\tkfact += k_fkt(k);\n\ttCG *= kfact;\n\n\treturn tCG;\n}\n// -----------------------------------------------------------------------------\n\n\n\n// -----------------------------------------------------------------------------\n// coordinate trafos\n// -----------------------------------------------------------------------------\n\n/**\n * cartesian -> spherical\n * @see https://en.wikipedia.org/wiki/Spherical_coordinate_system\n */\ntemplate\nstd::tuple cart_to_sph(T x, T y, T z)\n{\n\tT rho = std::sqrt(x*x + y*y + z*z);\n\tT phi = std::atan2(y, x);\n\tT theta = std::acos(z/rho);\n\n\treturn std::make_tuple(rho, phi, theta);\n}\n\n\n/**\n * spherical -> cartesian\n * @see https://en.wikipedia.org/wiki/Spherical_coordinate_system\n */\ntemplate\nstd::tuple sph_to_cart(T rho, T phi, T theta)\n{\n\tT x = rho * std::cos(phi)*std::sin(theta);\n\tT y = rho * std::sin(phi)*std::sin(theta);\n\tT z = rho * std::cos(theta);\n\n\treturn std::make_tuple(x, y, z);\n}\n\n\n/**\n * cylindrical -> spherical\n * @see https://en.wikipedia.org/wiki/Spherical_coordinate_system\n */\ntemplate\nstd::tuple cyl_to_sph(T rho_cyl, T phi_cyl, T z_cyl)\n{\n\tT rho = std::sqrt(rho_cyl*rho_cyl + z_cyl*z_cyl);\n\tT theta = std::acos(z_cyl/rho);\n\n\treturn std::make_tuple(rho, phi_cyl, theta);\n}\n\n\n/**\n * spherical -> cylindrical\n * @see https://en.wikipedia.org/wiki/Spherical_coordinate_system\n */\ntemplate\nstd::tuple sph_to_cyl(T rho_sph, T phi_sph, T theta_sph)\n{\n\tT rho = rho_sph * std::sin(theta_sph);\n\tT z = rho_sph * std::cos(theta_sph);\n\n\treturn std::make_tuple(rho, phi_sph, z);\n}\n\n\n/**\n * cylindrical -> cartesian\n * @see https://en.wikipedia.org/wiki/Cylindrical_coordinate_system\n */\ntemplate\nstd::tuple cyl_to_cart(T rho, T phi, T z)\n{\n\tT x = rho * std::cos(phi);\n\tT y = rho * std::sin(phi);\n\n\treturn std::make_tuple(x, y, z);\n}\n\n\n/**\n * cartesian -> cylindrical\n * @see https://en.wikipedia.org/wiki/Cylindrical_coordinate_system\n */\ntemplate\nstd::tuple cart_to_cyl(T x, T y, T z)\n{\n\tT rho = std::sqrt(x*x + y*y);\n\tT phi = std::atan2(y, x);\n\n\treturn std::make_tuple(rho, phi, z);\n}\n\n\n\ntemplate\nstd::tuple crys_to_sph(T twophi_crys, T twotheta_crys)\n{\n\t// converts the out-of-plane scattering angle '2theta' to the spherical theta\n\tT theta_sph = pi/T(2) - twotheta_crys;\n\t// converts in-plane scattering angle '2phi' to the spherical phi\n\tT phi_sph = twophi_crys - pi/T(2);\n\n\treturn std::make_tuple(phi_sph, theta_sph);\n}\n\n\ntemplate\nstd::tuple sph_to_crys(T phi, T theta)\n{\n\treturn crys_to_sph(phi, theta);\n}\n\n\n/**\n * gnomonic projection (similar to perspective projection with fov=90°)\n * @return [x,y]\n * @see see http://mathworld.wolfram.com/GnomonicProjection.html\n */\ntemplate\nstd::tuple gnomonic_proj(T twophi_crys, T twotheta_crys)\n{\n\tT x = -std::tan(twophi_crys);\n\tT y = std::tan(twotheta_crys) / std::cos(twophi_crys);\n\n\treturn std::make_tuple(x, y);\n}\n\n/**\n * stereographic projection\n * @return [x,y]\n * @see http://mathworld.wolfram.com/StereographicProjection.html\n */\ntemplate\nstd::tuple stereographic_proj(T twophi_crys, T twotheta_crys, T rad)\n{\n\tconst T sth = std::sin(twotheta_crys);\n\tconst T cth = std::cos(twotheta_crys);\n\tconst T sph = std::sin(twophi_crys);\n\tconst T cph = std::cos(twophi_crys);\n\n\tT x = -T(2) * rad * sph * cth / (T(1) + cth*cph);\n\tT y = T(2) * rad * sth / (T(1) + cth*cph);\n\n\treturn std::make_tuple(x, y);\n}\n// -----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n// adapters\n// ----------------------------------------------------------------------------\ntemplate class t_mat_base>\nclass qvec_adapter : public t_mat_base<1, N, T>\n{\npublic:\n\t// types\n\tusing base_type = t_mat_base<1, N, T>;\n\tusing size_type = size_t;\n\tusing value_type = T;\n\n\t// constructors\n\tusing base_type::base_type;\n\tqvec_adapter(const base_type& vec) : base_type{vec} {}\n\n\tstatic constexpr size_t size() { return N; }\n\n\tT& operator[](size_t i) { return base_type::operator()(i,0); }\n\tconst T operator[](size_t i) const { return base_type::operator()(i,0); }\n};\n\ntemplate class t_mat_base>\nclass qmat_adapter : public t_mat_base\n{\npublic:\n\t// types\n\tusing base_type = t_mat_base;\n\tusing size_type = size_t;\n\tusing value_type = T;\n\n\t// constructors\n\tusing base_type::base_type;\n\tqmat_adapter(const base_type& mat) : base_type{mat} {}\n\n\tstatic constexpr size_t size1() { return ROWS; }\n\tstatic constexpr size_t size2() { return COLS; }\n};\n\n\ntemplate\nclass qvecN_adapter : public t_vec_base\n{\npublic:\n\t// types\n\tusing base_type = t_vec_base;\n\tusing size_type = size_t;\n\tusing value_type = T;\n\n\t// constructors\n\tusing base_type::base_type;\n\tqvecN_adapter(const base_type& vec) : base_type{vec} {}\n\n\tstatic constexpr size_t size() { return N; }\n\n\tT& operator[](size_t i) { return static_cast(*this)[i]; }\n\tconst T operator[](size_t i) const { return static_cast(*this)[i]; }\n};\n\ntemplate\nclass qmatNN_adapter : public t_mat_base\n{\npublic:\n\t// types\n\tusing base_type = t_mat_base;\n\tusing size_type = size_t;\n\tusing value_type = T;\n\n\t// constructors\n\tusing base_type::base_type;\n\tqmatNN_adapter(const base_type& mat) : base_type{mat} {}\n\n\t// convert from a different matrix type\n\ttemplate qmatNN_adapter(const t_matOther& matOther)\n\t\trequires is_basic_mat\n\t{\n\t\tconst std::size_t minRows = std::min(static_cast(size1()), static_cast(matOther.size1()));\n\t\tconst std::size_t minCols = std::min(static_cast(size2()), static_cast(matOther.size2()));\n\n\t\tfor(std::size_t i=0; i(matOther(i,j));\n\t}\n\n\tstatic constexpr size_t size1() { return ROWS; }\n\tstatic constexpr size_t size2() { return COLS; }\n};\n// ----------------------------------------------------------------------------\n}\n\n\n\nnamespace tl2_ops {\n// ----------------------------------------------------------------------------\n// vector operators\n// ----------------------------------------------------------------------------\n\n/**\n * unary +\n */\ntemplate\nconst t_vec& operator+(const t_vec& vec1)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\treturn vec1;\n}\n\n\n/**\n * unary -\n */\ntemplate\nt_vec operator-(const t_vec& vec1)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\tt_vec vec(vec1.size());\n\n\tfor(std::size_t i=0; i\nt_vec operator+(const t_vec& vec1, const t_vec& vec2)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\tif constexpr(tl2::is_dyn_vec)\n\t\tassert((vec1.size() == vec2.size()));\n\n\tt_vec vec(vec1.size());\n\n\tfor(std::size_t i=0; i\nt_vec operator-(const t_vec& vec1, const t_vec& vec2)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\treturn vec1 + (-vec2);\n}\n\n\n/**\n * vector * scalar\n */\ntemplate\nt_vec operator*(const t_vec& vec1, typename t_vec::value_type d)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\tt_vec vec(vec1.size());\n\n\tfor(std::size_t i=0; i\nt_vec operator*(typename t_vec::value_type d, const t_vec& vec)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n\t//&& !tl2::is_basic_mat\t// hack!\n{\n\treturn vec * d;\n}\n\n\n/**\n * vector / scalar\n */\ntemplate\nt_vec operator/(const t_vec& vec1, typename t_vec::value_type d)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\tt_vec vec(vec1.size());\n\n\tfor(std::size_t i=0; i\nt_vec& operator+=(t_vec& vec1, const t_vec& vec2)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\tvec1 = vec1 + vec2;\n\treturn vec1;\n}\n\n\n/**\n * vector -= vector\n */\ntemplate\nt_vec& operator-=(t_vec& vec1, const t_vec& vec2)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\tvec1 = vec1 - vec2;\n\treturn vec1;\n}\n\n\n/**\n * vector *= scalar\n */\ntemplate\nt_vec& operator*=(t_vec& vec1, typename t_vec::value_type d)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\tvec1 = vec1 * d;\n\treturn vec1;\n}\n\n/**\n * vector /= scalar\n */\ntemplate\nt_vec& operator/=(t_vec& vec1, typename t_vec::value_type d)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\tvec1 = vec1 / d;\n\treturn vec1;\n}\n\n\n/**\n * operator <<\n */\ntemplate\nstd::ostream& operator<<(std::ostream& ostr, const t_vec& vec)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\tconst std::size_t N = vec.size();\n\n\tfor(std::size_t i=0; i>\n */\ntemplate\nstd::istream& operator>>(std::istream& istr, t_vec& vec)\nrequires tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\tvec.clear();\n\n\tstd::string str;\n\tstd::getline(istr, str);\n\n\tstd::vector vecstr;\n\tboost::split(vecstr, str, [](auto c)->bool { return c==TL2_COLSEP; }, boost::token_compress_on);\n\n\tfor(auto& tok : vecstr)\n\t{\n\t\tboost::trim(tok);\n\t\ttypename t_vec::value_type c = tl2::stoval(tok);\n\t\tvec.emplace_back(std::move(c));\n\t}\n\n\treturn istr;\n}\n// ----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n// matrix operators\n// ----------------------------------------------------------------------------\n\n/**\n * unary +\n */\ntemplate\nconst t_mat& operator+(const t_mat& mat1)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\treturn mat1;\n}\n\n\n/**\n * unary -\n */\ntemplate\nt_mat operator-(const t_mat& mat1)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\tt_mat mat(mat1.size1(), mat1.size2());\n\n\tfor(std::size_t i=0; i\nt_mat operator+(const t_mat& mat1, const t_mat& mat2)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\tif constexpr(tl2::is_dyn_mat)\n\t\tassert((mat1.size1() == mat2.size1() && mat1.size2() == mat2.size2()));\n\n\tt_mat mat(mat1.size1(), mat1.size2());\n\n\tfor(std::size_t i=0; i\nt_mat operator-(const t_mat& mat1, const t_mat& mat2)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\treturn mat1 + (-mat2);\n}\n\n\n/**\n * matrix * scalar\n */\ntemplate\nt_mat operator*(const t_mat& mat1, typename t_mat::value_type d)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\tt_mat mat(mat1.size1(), mat1.size2());\n\n\tfor(std::size_t i=0; i\nt_mat operator*(typename t_mat::value_type d, const t_mat& mat)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\treturn mat * d;\n}\n\n\n/**\n * matrix / scalar\n */\ntemplate\nt_mat operator/(const t_mat& mat, typename t_mat::value_type d)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\tusing T = typename t_mat::value_type;\n\treturn mat * (T(1)/d);\n}\n\n\n/**\n * matrix-matrix product\n */\ntemplate\nt_mat operator*(const t_mat& mat1, const t_mat& mat2)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\treturn tl2::prod(mat1, mat2);\n}\n\n\n/**\n * matrix *= scalar\n */\ntemplate\nt_mat& operator*=(t_mat& mat1, typename t_mat::value_type d)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\tmat1 = mat1 * d;\n\treturn mat1;\n}\n\n\n/**\n* matrix *= matrix\n */\ntemplate\nt_mat& operator*=(t_mat& mat1, const t_mat& mat2)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\tmat1 = mat1 * mat2;\n\treturn mat1;\n}\n\n\n/**\n * matrix += matrix\n */\ntemplate\nt_mat& operator+=(t_mat& mat1, const t_mat& mat2)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\tmat1 = mat1 + mat2;\n\treturn mat1;\n}\n\n/**\n * matrix /= scalar\n */\ntemplate\nt_mat& operator/=(t_mat& mat1, typename t_mat::value_type d)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\tmat1 = mat1 / d;\n\treturn mat1;\n}\n\n\n/**\n * operator <<\n */\ntemplate\nstd::ostream& operator<<(std::ostream& ostr, const t_mat& mat)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\tconst std::size_t ROWS = mat.size1();\n\tconst std::size_t COLS = mat.size2();\n\n\tfor(std::size_t row=0; row\nstd::ostream& niceprint(std::ostream& ostr, const t_mat& mat)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\tconst std::size_t ROWS = mat.size1();\n\tconst std::size_t COLS = mat.size2();\n\n\tfor(std::size_t i=0; i\nt_vec operator*(const t_mat& mat, const t_vec& vec)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n\t&& tl2::is_basic_vec && tl2::is_dyn_vec\n{\n\tif constexpr(tl2::is_dyn_mat)\n\t\tassert((mat.size2() == vec.size()));\n\telse\n\t\tstatic_assert(t_mat::size2() == t_vec::size());\n\n\n\tt_vec vecRet(mat.size1());\n\n\tfor(std::size_t row=0; row class t_cont = std::vector>\nrequires is_basic_vec> && is_dyn_vec>\nclass vec : public t_cont\n{\npublic:\n\tusing value_type = T;\n\tusing container_type = t_cont;\n\n\tusing container_type::container_type;\n\tusing container_type::size;\n\tusing container_type::operator[];\n\n\tusing typename container_type::iterator;\n\tusing typename container_type::const_iterator;\n\tusing typename container_type::size_type;\n\tusing typename container_type::difference_type;\n\tusing typename container_type::allocator_type;\n\n\t~vec() = default;\n\n\tvec(const vec& other) : container_type{other}\n\t{}\n\n\ttemplate class t_cont_other>\n\tvec(const vec& other)\n\t{\n\t\tthis->operator=(other);\n\t}\n\n\tvec& operator=(const vec& other)\n\t{\n\t\t*static_cast(this) = other;\n\t\treturn *this;\n\t}\n\n\tconst vec& operator=(const vec& other) const\n\t{\n\t\t*static_cast(this) = other;\n\t\treturn *this;\n\t}\n\n\ttemplate class t_cont_other>\n\tvec& operator=(const vec& other)\n\t{\n\t\t*this = convert, vec>(other);\n\t\treturn *this;\n\t}\n\n\ttemplate class t_cont_other>\n\tconst vec& operator=(const vec& other) const\n\t{\n\t\t*this = convert, vec>(other);\n\t\treturn *this;\n\t}\n\n\tvec(std::size_t SIZE, const T* arr = nullptr) : container_type(SIZE)\n\t{\n\t\tif(arr)\n\t\t\tfrom_array(arr);\n\t}\n\n\n\tconst value_type& operator()(std::size_t i) const { return this->operator[](i); }\n\tvalue_type& operator()(std::size_t i) { return this->operator[](i); }\n\n\n\tvoid from_array(const T* arr)\n\t{\n\t\t// initialise from given array data\n\t\tfor(std::size_t i=0; ioperator[](i) = arr[i];\n\t}\n\n\tvoid to_array(T* arr) const\n\t{\n\t\t// write elements to array\n\t\tfor(std::size_t i=0; ioperator[](i);\n\t}\n\n\tfriend vec operator+(const vec& vec1, const vec& vec2) { return tl2_ops::operator+(vec1, vec2); }\n\tfriend vec operator-(const vec& vec1, const vec& vec2) { return tl2_ops::operator-(vec1, vec2); }\n\tfriend const vec& operator+(const vec& vec1) { return tl2_ops::operator+(vec1); }\n\tfriend vec operator-(const vec& vec1) { return tl2_ops::operator-(vec1); }\n\n\tfriend vec operator*(value_type d, const vec& vec1) { return tl2_ops::operator*(d, vec1); }\n\tfriend vec operator*(const vec& vec1, value_type d) { return tl2_ops::operator*(vec1, d); }\n\tfriend vec operator/(const vec& vec1, value_type d) { return tl2_ops::operator/(vec1, d); }\n\n\tvec& operator*=(const vec& vec2) { return tl2_ops::operator*=(*this, vec2); }\n\tvec& operator+=(const vec& vec2) { return tl2_ops::operator+=(*this, vec2); }\n\tvec& operator-=(const vec& vec2) { return tl2_ops::operator-=(*this, vec2); }\n\tvec& operator*=(value_type d) { return tl2_ops::operator*=(*this, d); }\n\tvec& operator/=(value_type d) { return tl2_ops::operator/=(*this, d); }\n};\n\n\ntemplate class t_cont = std::vector>\nrequires is_basic_vec> && is_dyn_vec>\nclass mat\n{\npublic:\n\tusing value_type = T;\n\tusing container_type = t_cont;\n\n\tmat() = default;\n\t~mat() = default;\n\n\tmat(std::size_t ROWS, std::size_t COLS, const T* arr = nullptr)\n\t\t: m_data(ROWS*COLS), m_rowsize{ROWS}, m_colsize{COLS}\n\t{\n\t\tif(arr)\n\t\t\tfrom_array(arr);\n\t}\n\n\n\ttemplate class t_cont_other>\n\tmat(const mat& other)\n\t{\n\t\tthis->operator=(other);\n\t}\n\n\ttemplate class t_cont_other>\n\tmat& operator=(const vec& other)\n\t{\n\t\t*this = convert, mat>(other);\n\n\t\tthis->m_rowsize = other.m_rowsize;\n\t\tthis->m_colsize = other.m_colsize;\n\n\t\treturn *this;\n\t}\n\n\ttemplate class t_cont_other>\n\tconst mat& operator=(const vec& other) const\n\t{\n\t\t*this = convert, mat>(other);\n\n\t\tthis->m_rowsize = other.m_rowsize;\n\t\tthis->m_colsize = other.m_colsize;\n\n\t\treturn *this;\n\t}\n\n\n\tstd::size_t size1() const { return m_rowsize; }\n\tstd::size_t size2() const { return m_colsize; }\n\n\n\t// element access\n\tconst T& operator()(std::size_t row, std::size_t col) const { return m_data[row*m_colsize + col]; }\n\tT& operator()(std::size_t row, std::size_t col) { return m_data[row*m_colsize + col]; }\n\n\n\tvoid from_array(const T* arr)\n\t{\n\t\t// initialise from given array data\n\t\tfor(std::size_t i=0; ioperator()(i,j) = arr[i*m_colsize + j];\n\t}\n\n\tvoid to_array(T* arr) const\n\t{\n\t\t// write elements to array\n\t\tfor(std::size_t i=0; ioperator()(i,j);\n\t}\n\n\tfriend mat operator+(const mat& mat1, const mat& mat2) { return tl2_ops::operator+(mat1, mat2); }\n\tfriend mat operator-(const mat& mat1, const mat& mat2) { return tl2_ops::operator-(mat1, mat2); }\n\tfriend const mat& operator+(const mat& mat1) { return tl2_ops::operator+(mat1); }\n\tfriend mat operator-(const mat& mat1) { return tl2_ops::operator-(mat1); }\n\n\tfriend mat operator*(const mat& mat1, const mat& mat2) { return tl2_ops::operator*(mat1, mat2); }\n\tfriend mat operator*(const mat& mat1, value_type d) { return tl2_ops::operator*(mat1, d); }\n\tfriend mat operator*(value_type d, const mat& mat1) { return tl2_ops::operator*(d, mat1); }\n\tfriend mat operator/(const mat& mat1, value_type d) { return tl2_ops::operator/(mat1, d); }\n\n\ttemplate requires is_basic_vec> && is_dyn_vec>\n\tfriend t_vec operator*(const mat& mat1, const t_vec& vec2) { return tl2_ops::operator*(mat1, vec2); }\n\n\tmat& operator*=(const mat& mat2) { return tl2_ops::operator*=(*this, mat2); }\n\tmat& operator+=(const mat& mat2) { return tl2_ops::operator+=(*this, mat2); }\n\tmat& operator-=(const mat& mat2) { return tl2_ops::operator-=(*this, mat2); }\n\tmat& operator*=(value_type d) { return tl2_ops::operator*=(*this, d); }\n\tmat& operator/=(value_type d) { return tl2_ops::operator/=(*this, d); }\n\nprivate:\n\tcontainer_type m_data{};\n\tstd::size_t m_rowsize{0};\n\tstd::size_t m_colsize{0};\n};\n\n// ----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n// scalar algos\n// ----------------------------------------------------------------------------\n\n/**\n * are two scalars equal within an epsilon range?\n */\ntemplate\nbool equals(T t1, T t2, T eps = std::numeric_limits::epsilon())\nrequires is_scalar\n{\n\treturn std::abs(t1 - t2) <= eps;\n}\n\n\n/**\n * get next multiple of the given granularity\n */\ntemplate\nt_num next_multiple(t_num num, t_num granularity)\nrequires is_scalar\n{\n\tt_num div = num / granularity;\n\tbool rest_is_0 = 1;\n\n\tif constexpr(std::is_floating_point_v)\n\t{\n\t\tdiv = std::floor(div);\n\t\tt_num rest = std::fmod(num, granularity);\n\t\trest_is_0 = equals(rest, t_num{0});\n\t}\n\telse\n\t{\n\t\tt_num rest = num % granularity;\n\t\trest_is_0 = (rest==0);\n\t}\n\n\treturn rest_is_0 ? num : (div+1) * granularity;\n}\n\n\n/**\n * mod operation, keeping result positive\n */\ntemplate\nt_real mod_pos(t_real val, t_real tomod=t_real{2}*pi)\nrequires is_scalar\n{\n\tval = std::fmod(val, tomod);\n\tif(val < t_real(0))\n\t\tval += tomod;\n\n\treturn val;\n}\n\n/**\n * are two angles equal within an epsilon range?\n */\ntemplate\nbool angle_equals(T t1, T t2, T eps = std::numeric_limits::epsilon(), T tomod=T{2}*pi)\nrequires is_scalar\n{\n\tt1 = mod_pos(t1, tomod);\n\tt2 = mod_pos(t2, tomod);\n\n\treturn std::abs(t1 - t2) <= eps;\n}\n\n\n/**\n * are two complex numbers equal within an epsilon range?\n */\ntemplate\nbool equals(const T& t1, const T& t2,\n\ttypename T::value_type eps = std::numeric_limits::epsilon())\nrequires is_complex\n{\n\treturn (std::abs(t1.real() - t2.real()) <= eps) &&\n\t(std::abs(t1.imag() - t2.imag()) <= eps);\n}\n\n// ----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n// n-dim algos\n// ----------------------------------------------------------------------------\n\n/**\n * are two vectors equal within an epsilon range?\n */\ntemplate\nbool equals(const t_vec& vec1, const t_vec& vec2,\n\tt_real eps = std::numeric_limits::epsilon(),\n\tint _maxSize = -1)\nrequires is_basic_vec\n{\n\t// size has to be equal\n\tif(vec1.size() != vec2.size())\n\t\treturn false;\n\n\tstd::size_t maxSize = vec1.size();\n\tif(_maxSize >= 0)\n\t\tmaxSize = std::min(std::size_t(_maxSize), maxSize);\n\n\t// check each element\n\tfor(std::size_t i=0; i)\n\t\t{\n\t\t\tif(!equals(vec1[i], vec2[i], eps.real()))\n\t\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(!equals(vec1[i], vec2[i], eps))\n\t\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\n/**\n * are two matrices equal within an epsilon range?\n */\ntemplate\nbool equals(const t_mat& mat1, const t_mat& mat2,\n\tt_real eps = std::numeric_limits::epsilon(),\n\tint _maxSize = -1)\nrequires is_mat\n{\n\tusing T = typename t_mat::value_type;\n\n\tif(mat1.size1() != mat2.size1() || mat1.size2() != mat2.size2())\n\t\treturn false;\n\n\tstd::size_t maxSize1 = mat1.size1();\n\tstd::size_t maxSize2 = mat1.size2();\n\tif(_maxSize >= 0)\n\t{\n\t\tmaxSize1 = std::min(std::size_t(_maxSize), maxSize1);\n\t\tmaxSize2 = std::min(std::size_t(_maxSize), maxSize2);\n\t}\n\n\tfor(std::size_t i=0; i)\n\t\t\t{\n\t\t\t\tif(!equals(mat1(i,j), mat2(i,j), eps.real()))\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(!equals(mat1(i,j), mat2(i,j), eps))\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\n/**\n * check if two collections of matrices or vectors are equal\n */\ntemplate class t_vec = std::vector>\nbool equals_all(const t_vec& vec1, const t_vec& _vec2,\n\ttypename t_obj::value_type eps = std::numeric_limits::epsilon(),\n\tint maxSize=-1)\n{\n\tauto vec2 = _vec2;\n\tif(vec1.size() != vec2.size())\n\t\treturn false;\n\n\tfor(const auto& obj1 : vec1)\n\t{\n\t\t// find obj1 in vec2\n\t\tauto iter = std::find_if(vec2.crbegin(), vec2.crend(),\n\t\t[&obj1, eps, maxSize](const t_obj& obj2) -> bool\n\t\t{\n\t\t\treturn tl2::equals(obj1, obj2, eps, maxSize);\n\t\t});\n\n\t\t// not found\n\t\tif(iter == vec2.crend())\n\t\t\treturn false;\n\n\t\t// remove already checked element\n\t\tvec2.erase(iter.base()-1);\n\t}\n\n\treturn true;\n}\n\n\n/**\n * remove duplicate vectors or matrices in the container\n */\ntemplate class t_cont = std::vector>\nt_cont remove_duplicates(const t_cont& objs,\n\ttypename t_obj::value_type eps = std::numeric_limits::epsilon())\n{\n\tt_cont newobjs = objs;\n\n\tfor(const auto& elem : objs)\n\t{\n\t\t// find obj in container\n\t\tauto iter = std::find_if(newobjs.cbegin(), newobjs.cend(),\n\t\t[&elem, eps](const t_obj& elem2) -> bool\n\t\t{\n\t\t\treturn tl2::equals(elem, elem2, eps);\n\t\t});\n\n\t\t// not found\n\t\tif(iter == newobjs.cend())\n\t\t\tnewobjs.push_back(elem);\n\t}\n\n\treturn newobjs;\n}\n\n\n/**\n * set submatrix to unit\n */\ntemplate\nvoid unit(t_mat& mat, std::size_t rows_begin, std::size_t cols_begin, std::size_t rows_end, std::size_t cols_end)\nrequires is_basic_mat\n{\n\tfor(std::size_t i=rows_begin; i\nt_mat unit(std::size_t N1, std::size_t N2)\nrequires is_basic_mat\n{\n\tt_mat mat;\n\tif constexpr(is_dyn_mat)\n\t\tmat = t_mat(N1, N2);\n\n\tunit(mat, 0,0, mat.size1(),mat.size2());\n\treturn mat;\n}\n\n\n/**\n * unit matrix\n */\ntemplate\nt_mat unit(std::size_t N=0)\nrequires is_basic_mat\n{\n\treturn unit(N,N);\n}\n\n\n/**\n * zero matrix\n */\ntemplate\nt_mat zero(std::size_t N1, std::size_t N2)\nrequires is_basic_mat\n{\n\tt_mat mat;\n\tif constexpr(is_dyn_mat)\n\t\tmat = t_mat(N1, N2);\n\n\tfor(std::size_t i=0; i\nt_mat zero(std::size_t N=0)\nrequires is_basic_mat\n{\n\treturn zero(N, N);\n}\n\n\n/**\n * zero vector\n */\ntemplate\nt_vec zero(std::size_t N /* = 0*/)\nrequires is_basic_vec\n{\n\tusing size_t = decltype(t_vec{}.size());\n\n\tt_vec vec;\n\tif constexpr(is_dyn_vec)\n\t\tvec = t_vec(N);\n\n\tfor(size_t i=0; i\nt_mat perm(std::size_t N1, std::size_t N2, std::size_t from, std::size_t to)\nrequires is_basic_mat\n{\n\tt_mat mat;\n\tif constexpr(is_dyn_mat)\n\t\tmat = t_mat(N1, N2);\n\n\tunit(mat, 0,0, mat.size1(),mat.size2());\n\n\tmat(from, from) = mat(to, to) = 0;\n\tmat(from, to) = mat(to, from) = 1;\n\n\treturn mat;\n}\n\n\n/**\n * diagonal matrix\n */\ntemplate>\nt_mat diag(const t_vec& vals)\nrequires is_basic_mat && is_basic_vec\n{\n\tconst std::size_t N = vals.size();\n\tt_mat mat = zero(N);\n\n\t// static matrix does not necessarily have the required size!\n\tif constexpr(!tl2::is_dyn_mat)\n\t\tassert(mat.size1() == mat.size1() && mat.size1() == N);\n\n\tfor(std::size_t i=0; i\nt_vec diag_vec(const t_mat& mat)\nrequires is_vec && is_mat\n{\n\tstd::size_t N = std::min(mat.size1(), mat.size2());\n\n\tt_vec vec = zero(N);\n\tfor(std::size_t i=0; i\nbool equals_0(t_real val, t_real eps = std::numeric_limits::epsilon())\nrequires is_scalar\n{\n\treturn equals(val, t_real(0), eps);\n}\n\n\n/**\n * tests for zero vector\n */\ntemplate\nbool equals_0(const t_vec& vec,\n\ttypename t_vec::value_type eps = std::numeric_limits::epsilon())\nrequires is_basic_vec\n{\n\treturn equals(vec, zero(vec.size()), eps);\n}\n\n\n/**\n * tests for zero matrix\n */\ntemplate\nbool equals_0(const t_mat& mat,\n\ttypename t_mat::value_type eps = std::numeric_limits::epsilon())\nrequires is_mat\n{\n\treturn equals(mat, zero(mat.size1(), mat.size2()), eps);\n}\n\n\n/**\n * tests for symmetric or hermitian matrix\n */\ntemplate\nbool is_symm_or_herm(const t_mat& mat,\n\ttypename t_mat::value_type eps = std::numeric_limits::epsilon())\nrequires is_mat\n{\n\tusing t_elem = typename t_mat::value_type;\n\tif(mat.size1() != mat.size2())\n\t\treturn false;\n\n\tfor(std::size_t i=0; i)\n\t\t\t{\n\t\t\t\t// not hermitian?\n\t\t\t\tif(!equals(mat(i,j), std::conj(mat(j,i)), eps))\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// not symmetric?\n\t\t\t\tif(!equals(mat(i,j), mat(j,i), eps))\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\n/**\n * transpose matrix\n * WARNING: not possible for static non-square matrix!\n */\ntemplate\nt_mat trans(const t_mat& mat)\nrequires is_mat\n{\n\tusing t_idxtype = decltype(mat.size1());\n\n\tt_mat mat2;\n\tif constexpr(is_dyn_mat)\n\t\tmat2 = t_mat(mat.size2(), mat.size1());\n\n\tfor(t_idxtype i=0; i\nvoid set_eps_0(t_real& d, t_real eps = std::numeric_limits::epsilon())\nrequires is_scalar\n{\n\tif(std::abs(d) < eps)\n\t\td = t_real(0);\n};\n\n\n/**\n * set values lower than epsilon to zero\n * vector version\n */\ntemplate\nvoid set_eps_0(t_vec& vec, t_real eps = std::numeric_limits::epsilon())\nrequires is_basic_vec\n{\n\tfor(t_real& d : vec)\n\t\tset_eps_0(d, eps);\n};\n\n\n/**\n * set values lower than epsilon to zero\n * matrix version\n */\ntemplate\nvoid set_eps_0(t_mat& mat, t_real eps = std::numeric_limits::epsilon())\nrequires is_basic_mat\n{\n\tfor(std::size_t i=0; i(mat(i,j), eps);\n};\n// -----------------------------------------------------------------------------\n\n\n/**\n * create a vector with given size if it is dynamic\n */\ntemplate\nt_vec create(std::size_t size=3)\nrequires is_basic_vec\n{\n\tt_vec vec;\n\tif constexpr(is_dyn_vec)\n\t\tvec = t_vec(size);\n\n\treturn vec;\n}\n\n\n/**\n * create a matrix with given sizes if it is dynamic\n */\ntemplate\nt_mat create(std::size_t size1, std::size_t size2)\nrequires is_basic_mat\n{\n\tt_mat mat;\n\tif constexpr(is_dyn_mat)\n\t\tmat = t_mat{size1, size2};\n\n\treturn mat;\n}\n\n\n/**\n * create vector from initializer_list\n */\ntemplate class t_cont = std::initializer_list>\nt_vec create(const t_cont& lst)\nrequires is_basic_vec\n{\n\tt_vec vec;\n\tif constexpr(is_dyn_vec)\n\t\tvec = t_vec(lst.size());\n\n\tauto iterLst = lst.begin();\n\tauto size = vec.size();\n\tusing local_size_t = std::decay_t;\n\tfor(local_size_t i=0; i class t_cont_outer = std::initializer_list,\n\ttemplate class t_cont = std::initializer_list>\nt_mat create_mat(const t_cont_outer>& lst)\nrequires is_mat\n{\n\tconst std::size_t iCols = lst.size();\n\tconst std::size_t iRows = lst.begin()->size();\n\n\tt_mat mat = unit(iRows, iCols);\n\n\tauto iterCol = lst.begin();\n\tfor(std::size_t iCol=0; iColbegin();\n\t\tfor(std::size_t iRow=0; iRow class t_cont_outer = std::initializer_list,\n\ttemplate class t_cont = std::initializer_list>\nt_mat create(const t_cont_outer>& lst)\nrequires is_mat\n{\n\treturn create_mat(lst);\n}\n\n\n/**\n * create matrix from column (or row) vectors\n */\ntemplate class t_cont_outer = std::initializer_list>\nt_mat create(const t_cont_outer& lst, bool bRow = false)\nrequires is_mat && is_basic_vec\n{\n\tconst std::size_t iCols = lst.size();\n\tconst std::size_t iRows = lst.begin()->size();\n\n\tt_mat mat = unit(iRows, iCols);\n\n\tauto iterCol = lst.begin();\n\tfor(std::size_t iCol=0; iCol(mat);\n\treturn mat;\n}\n\n\n/**\n * create matrix from initializer_list in column/row order\n */\ntemplate\nt_mat create_mat(const std::initializer_list& lst)\nrequires is_mat\n{\n\tconst std::size_t N = std::sqrt(lst.size());\n\n\tt_mat mat = unit(N, N);\n\n\tauto iter = lst.begin();\n\tfor(std::size_t iRow=0; iRow\nt_mat create(const std::initializer_list& lst)\nrequires is_mat\n{\n\treturn create_mat(lst);\n}\n\n\n/**\n * linearise a matrix to a vector container\n */\ntemplate\nt_vec convert(const t_mat& mat)\nrequires is_basic_vec && is_mat\n{\n\tusing T_dst = typename t_vec::value_type;\n\tusing t_idx = decltype(mat.size1());\n\n\tt_vec vec;\n\tvec.reserve(mat.size1()*mat.size2());\n\n\tfor(t_idx iRow=0; iRow\nt_mat_dst convert(const t_mat_src& mat)\nrequires is_mat && is_mat\n{\n\tusing T_dst = typename t_mat_dst::value_type;\n\tusing t_idx = decltype(mat.size1());\n\n\t// in case the static size of the destination vector is larger than the source's\n\tt_idx maxRows = std::max(mat.size1(), t_idx(t_mat_dst{}.size1()));\n\tt_idx maxCols = std::max(mat.size2(), t_idx(t_mat_dst{}.size2()));\n\n\tt_mat_dst matdst = unit(maxRows, maxCols);\n\n\tfor(t_idx iRow=0; iRow\nt_vec_dst convert(const t_vec_src& vec)\nrequires is_vec && is_vec\n{\n\tusing T_dst = typename t_vec_dst::value_type;\n\tusing t_idx = decltype(vec.size());\n\n\tt_vec_dst vecdst = create(vec.size());\n\n\tfor(t_idx i=0; i class t_cont>\nt_cont convert(const t_cont& src_objs)\nrequires (is_vec || is_mat) && (is_vec || is_mat)\n{\n\tt_cont dst_objs;\n\tdst_objs.reserve(src_objs.size());\n\n\tfor(const t_obj_src& src_obj : src_objs)\n\t\tdst_objs.emplace_back(convert(src_obj));\n\n\treturn dst_objs;\n}\n\n\n/**\n * get a column vector from a matrix\n */\ntemplate\nt_vec col(const t_mat& mat, std::size_t col)\nrequires is_mat && is_basic_vec\n{\n\tt_vec vec;\n\tif constexpr(is_dyn_vec)\n\t\tvec = t_vec(mat.size1());\n\n\tfor(std::size_t i=0; i\nt_vec row(const t_mat& mat, std::size_t row)\nrequires is_mat && is_basic_vec\n{\n\tt_vec vec;\n\tif constexpr(is_dyn_vec)\n\t\tvec = t_vec(mat.size2());\n\n\tfor(std::size_t i=0; i\nvoid set_col(t_mat& mat, const t_vec& vec, std::size_t col)\nrequires is_mat && is_basic_vec\n{\n\tfor(std::size_t i=0; i(mat.size1(), vec.size()); ++i)\n\t\tmat(i, col) = vec[i];\n}\n\n\n/**\n * set a row vector in a matrix\n */\ntemplate\nvoid set_row(t_mat& mat, const t_vec& vec, std::size_t row)\nrequires is_mat && is_basic_vec\n{\n\tfor(std::size_t i=0; i(mat.size1(), vec.size()); ++i)\n\t\tmat(row, i) = vec[i];\n}\n\n\n/**\n * inner product \n */\ntemplate\ntypename t_vec::value_type inner(const t_vec& vec1, const t_vec& vec2)\nrequires is_basic_vec\n{\n\ttypename t_vec::value_type val{0};\n\tauto size = vec1.size();\n\tusing local_size_t = std::decay_t;\n\n\tfor(local_size_t i=0; i)\n\t\t\tval += std::conj(vec1[i]) * vec2[i];\n\t\telse\n\t\t\tval += vec1[i] * vec2[i];\n\t}\n\n\treturn val;\n}\n\n\n/**\n * inner product between two vectors of different type\n */\ntemplate\ntypename t_vec1::value_type inner(const t_vec1& vec1, const t_vec2& vec2)\nrequires is_basic_vec && is_basic_vec\n{\n\tif(vec1.size()==0 || vec2.size()==0)\n\t\treturn typename t_vec1::value_type{};\n\n\t// first element\n\tauto val = vec1[0]*vec2[0];\n\n\t// remaining elements\n\tfor(std::size_t i=1; i)\n\t\t{\n\t\t\tauto prod = std::conj(vec1[i]) * vec2[i];\n\t\t\tval = val + prod;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto prod = vec1[i]*vec2[i];\n\t\t\tval = val + prod;\n\t\t}\n\t}\n\n\treturn val;\n}\n\n\n/**\n * matrix-matrix product: c_ij = a_ik b_kj\n */\ntemplate\nt_mat prod(const t_mat& mat1, const t_mat& mat2, bool assert_sizes/*=true*/)\nrequires tl2::is_basic_mat && tl2::is_dyn_mat\n{\n\t// if not asserting sizes, the inner size will use the minimum of the two matrix sizes\n\tif(assert_sizes)\n\t{\n\t\tif constexpr(tl2::is_dyn_mat)\n\t\t\tassert((mat1.size2() == mat2.size1()));\n\t\telse\n\t\t\tstatic_assert(t_mat::size2() == t_mat::size1());\n\t}\n\n\n\tt_mat matRet(mat1.size1(), mat2.size2());\n\tconst std::size_t innersize = std::min(mat1.size2(), mat2.size1());\n\n\tfor(std::size_t row=0; row\nt_mat div_perelem(const t_mat& mat1, const t_mat& mat2, bool assert_sizes=true)\nrequires tl2::is_basic_mat\n{\n\tif(assert_sizes)\n\t{\n\t\tif constexpr(tl2::is_dyn_mat)\n\t\t\tassert(mat1.size1() == mat2.size1() && mat1.size2() == mat2.size2());\n\t}\n\n\n\tt_mat matRet = zero(mat1.size1(), mat1.size2());\n\n\tfor(std::size_t row=0; row\nt_real norm(const t_vec& vec)\nrequires is_basic_vec\n{\n\tt_real d = static_cast(inner(vec, vec));\n\treturn std::sqrt(d);\n}\n\n\n/**\n * n-norm\n */\ntemplate\ntypename t_vec::value_type norm(const t_vec& vec, t_real n)\nrequires is_basic_vec\n{\n\tt_real d = t_real{0};\n\tfor(std::size_t i=0; i\nt_mat outer(const t_vec& vec1, const t_vec& vec2)\nrequires is_basic_vec && is_mat\n{\n\tconst std::size_t N1 = vec1.size();\n\tconst std::size_t N2 = vec2.size();\n\n\tt_mat mat;\n\tif constexpr(is_dyn_mat)\n\t\tmat = t_mat(N1, N2);\n\n\tfor(std::size_t n1=0; n1)\n\t\t\t\tmat(n1, n2) = std::conj(vec1[n1]) * vec2[n2];\n\t\t\telse\n\t\t\t\tmat(n1, n2) = vec1[n1]*vec2[n2];\n\t\t}\n\t}\n\n\treturn mat;\n}\n\n\n\n// ----------------------------------------------------------------------------\n// operations with metric\n// ----------------------------------------------------------------------------\n\n/**\n * covariant metric tensor: g_{i,j} = e_i * e_j\n * @see (Arens 2015), p. 808\n */\ntemplate class t_cont=std::initializer_list>\nt_mat metric(const t_cont& basis_co)\nrequires is_basic_mat && is_basic_vec\n{\n\tconst std::size_t N = basis_co.size();\n\n\tt_mat g_co;\n\tif constexpr(is_dyn_mat)\n\t\tg_co = t_mat(N, N);\n\n\tauto iter_i = basis_co.begin();\n\tfor(std::size_t i=0; i(*iter_i, *iter_j);\n\t\t\tstd::advance(iter_j, 1);\n\t\t}\n\t\tstd::advance(iter_i, 1);\n\t}\n\n\treturn g_co;\n}\n\n\n/**\n * covariant metric tensor: g_{i,j} = e_i * e_j\n * @see (Arens 2015), p. 815\n */\ntemplate\nt_mat metric(const t_mat& basis_co)\nrequires is_basic_mat\n{\n\tt_mat basis_trans = trans(basis_co);\n\treturn basis_trans * basis_co;\n}\n\n\n/**\n * get levi-civita symbol in fractional coordinates\n * @see (Arens 2015), p. 815\n */\ntemplate\ntypename t_mat::value_type levi(const t_mat& basis_co,\n\tconst std::initializer_list& indices)\nrequires is_basic_mat\n{\n\tusing size_t = decltype(basis_co.size1());\n\tusing t_vec = vec;\n\tt_mat mat = create(basis_co.size1(), basis_co.size2());\n\n\tauto iter = indices.begin();\n\tsize_t maxcols = std::min(indices.size(), basis_co.size2());\n\tfor(size_t i=0; i(\n\t\t\tmat, col(basis_co, *iter), i);\n\t\tstd::advance(iter, 1);\n\t}\n\n\treturn det(mat);\n}\n\n\n/**\n * cross product in fractional coordinates: c^l = eps_ijk g^li a^j b^k\n * @see (Arens 2015), p. 815\n */\ntemplate\nt_vec cross(const t_mat& B, const t_vec& a, const t_vec& b)\nrequires is_basic_mat && is_basic_vec\n{\n\tusing size_t = decltype(B.size1());\n\tusing t_real = typename t_mat::value_type;\n\n\t// metric and its inverse\n\tauto G = metric(B);\n\tauto [G_inv, ok] = inv(G);\n\n\t// maximum indices\n\tconst size_t i_max = G_inv.size1();\n\tconst size_t j_max = a.size();\n\tconst size_t k_max = b.size();\n\tconst size_t l_max = G_inv.size2();\n\n\t// cross product result vector\n\tt_vec c = zero(l_max);\n\n\tfor(size_t i=0; i(B, {i,j,k});\n\t\t\t\tfor(size_t l=0; l\nt_vec lower_index(const t_mat& metric_co, const t_vec& vec_contra)\nrequires is_basic_mat && is_basic_vec\n{\n\tconst std::size_t N = vec_contra.size();\n\tt_vec vec_co = zero(N);\n\n\tfor(std::size_t i=0; i\nt_vec raise_index(const t_mat& metric_contra, const t_vec& vec_co)\nrequires is_basic_mat && is_basic_vec\n{\n\tconst std::size_t N = vec_co.size();\n\tt_vec vec_contra = zero(N);\n\n\tfor(std::size_t i=0; i\ntypename t_vec::value_type inner(const t_mat& metric_co,\n\tconst t_vec& vec1_contra, const t_vec& vec2_contra)\nrequires is_basic_mat && is_basic_vec\n{\n\tt_vec vec2_co = lower_index(metric_co, vec2_contra);\n\treturn inner(vec1_contra, vec2_co);\n}\n\n\n/**\n * 2-norm using metric\n * @see (Arens 2015), p. 808\n */\ntemplate\ntypename t_vec::value_type norm(const t_mat& metric_co, const t_vec& vec_contra)\nrequires is_basic_vec\n{\n\treturn std::sqrt(inner(metric_co, vec_contra, vec_contra));\n}\n\n\n/**\n * angle between vectors under a given metric\n * @see (Arens 2015), p. 808\n */\ntemplate\ntypename t_vec::value_type angle(const t_mat& metric_co,\n\tconst t_vec& vec1_contra, const t_vec& vec2_contra)\nrequires is_basic_mat && is_basic_vec\n{\n\tusing t_real = typename t_mat::value_type;\n\n\tt_real len1 = norm(metric_co, vec1_contra);\n\tt_real len2 = norm(metric_co, vec2_contra);\n\n\tt_real c = inner(metric_co, vec1_contra, vec2_contra);\n\tc /= len1 * len2;\n\tc = clamp(c, -1, 1);\n\n\treturn std::acos(c);\n}\n// ----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n// tas calculations\n// @see M. D. Lumsden, J. L. Robertson, and M. Yethiraj, J. Appl. Crystallogr. 38(3), pp. 405–411 (2005), doi: 10.1107/S0021889805004875.\n// @see (Shirane 2002)\n// ----------------------------------------------------------------------------\n\n/**\n * angle between ki and kf in the scattering triangle\n * @returns nullopt if the angle can't be reached\n *\n * |Q> = |ki> - |kf>\n * Q^2 = ki^2 + kf^2 - 2*\n * 2* = ki^2 + kf^2 - Q^2\n * cos phi = (ki^2 + kf^2 - Q^2) / (2 ki*kf)\n */\ntemplate\nstd::optional calc_tas_angle_ki_kf(\n\tt_real ki, t_real kf, t_real Q, t_real sense=1)\n{\n\tt_real c = (ki*ki + kf*kf - Q*Q) / (t_real(2)*ki*kf);\n\tif(std::abs(c) > t_real(1))\n\t\treturn std::nullopt;\n\treturn sense*std::acos(c);\n}\n\n\n/**\n * angle between ki and Q in the scattering triangle\n * @returns nullopt if the angle can't be reached\n *\n * |Q> = |ki> - |kf>\n * |kf> = |ki> + |Q>\n * kf^2 = ki^2 + Q^2 - 2*\n * 2* = ki^2 + Q^2 - kf^2\n * cos phi = (ki^2 + Q^2 - kf^2) / (2 ki*Q)\n */\ntemplate\nstd::optional calc_tas_angle_ki_Q(\n\tt_real ki, t_real kf, t_real Q, t_real sense=1)\n{\n\tt_real c = (ki*ki + Q*Q - kf*kf) / (t_real(2)*ki*Q);\n\tif(std::abs(c) > t_real(1))\n\t\treturn std::nullopt;\n\treturn sense*std::acos(c);\n}\n\n\n/**\n * get length of Q\n * |Q> = |ki> - |kf>\n * Q^2 = ki^2 + kf^2 - 2*\n * Q^2 = ki^2 + kf^2 - 2*ki*kf*cos(a4)\n */\ntemplate\nt_real calc_tas_Q_len(t_real ki, t_real kf, t_real a4)\n{\n\tt_real Qsq = ki*ki + kf*kf - t_real(2)*ki*kf*std::cos(a4);\n\treturn std::sqrt(Qsq);\n}\n\n\n/**\n * get tas a3 and a4 angles\n * @return [a3, a4, distance of Q to the scattering plane]\n// @see M. D. Lumsden, et al., doi: 10.1107/S0021889805004875.\n */\ntemplate\nstd::tuple calc_tas_a3a4(\n\tconst t_mat& B, t_real ki_lab, t_real kf_lab,\n\tconst t_vec& Q_rlu, const t_vec& orient_rlu, const t_vec& orient_up_rlu,\n\tt_real sample_sense = 1, t_real a3_offs = pi)\nrequires is_basic_mat && is_basic_vec\n{\n\t// metric from crystal B matrix\n\tt_mat G = tl2::metric(B);\n\n\t// length of Q vector\n\tt_real Q_len_lab = norm(G, Q_rlu);\n\n\t// angle xi between Q and orientation reflex\n\tt_real xi = angle(G, Q_rlu, orient_rlu);\n\n\t// sign/direction of xi\n\tt_vec xivec = cross(G, orient_rlu, Q_rlu);\n\tt_real xidir = inner(G, xivec, orient_up_rlu);\n\tif(xidir < t_real(0))\n\t\txi = -xi;\n\n\t// angle psi between ki and Q\n\tstd::optional psi =\n\t\tcalc_tas_angle_ki_Q(ki_lab, kf_lab, Q_len_lab, sample_sense);\n\tif(!psi)\n\t\treturn std::make_tuple(false, 0, 0, 0);\n\n\t// crystal and scattering angle\n\tt_real a3 = - *psi - xi + a3_offs;\n\tstd::optional a4 =\n\t\tcalc_tas_angle_ki_kf(ki_lab, kf_lab, Q_len_lab);\n\tif(!a4)\n\t\treturn std::make_tuple(false, a3, 0, 0);\n\t*a4 *= sample_sense;\n\n\t// distance of Q to the scattering plane\n\tt_real dist_Q_plane = inner(G, Q_rlu, orient_up_rlu);\n\tdist_Q_plane /= norm(G, orient_up_rlu);\n\n\treturn std::make_tuple(true, a3, *a4, dist_Q_plane);\n}\n\n\n/**\n * get hkl position of a tas\n * @return Q_rlu\n// @see M. D. Lumsden, et al., doi: 10.1107/S0021889805004875.\n */\ntemplate\nstd::optional calc_tas_hkl(\n\tconst t_mat& B, t_real ki_lab, t_real kf_lab, t_real Q_len_lab, t_real a3,\n\tconst t_vec& orient_rlu, const t_vec& orient_up_rlu,\n\tt_real sample_sense = 1, t_real a3_offs = pi)\nrequires is_basic_mat && is_basic_vec\n{\n\tauto [Binv, ok] = inv(B);\n\tif(!ok)\n\t\treturn std::nullopt;\n\n\t// angle psi between ki and Q\n\tstd::optional psi =\n\t\tcalc_tas_angle_ki_Q(ki_lab, kf_lab, Q_len_lab, sample_sense);\n\tif(!psi)\n\t\treturn std::nullopt;\n\n\t// angle xi between Q and orientation reflex\n\tt_real xi = a3_offs - a3 - *psi;\n\n\tt_vec rotaxis_lab = B * orient_up_rlu;\n\tt_mat rotmat = rotation(rotaxis_lab, xi, false);\n\n\tt_vec orient_lab = B * orient_rlu;\n\tt_vec Q_lab = rotmat * orient_lab;\n\tQ_lab /= norm(Q_lab);\n\tQ_lab *= Q_len_lab;\n\n\tt_vec Q_rlu = Binv * Q_lab;\n\treturn Q_rlu;\n}\n\n\n/**\n * get a1 or a5 angle\n * @returns nullopt of the angle can't be reached\n * @see https://en.wikipedia.org/wiki/Bragg's_law\n *\n * Bragg: n lam = 2d sin(theta)\n * n 2pi / k = 2d sin(theta)\n * n pi / k = d sin(theta)\n * theta = asin(n pi / (k d))\n */\ntemplate\nstd::optional calc_tas_a1(t_real k, t_real d)\n{\n\tt_real sintheta = pi / (k*d);\n\tif(std::abs(sintheta) > t_real(1))\n\t\treturn std::nullopt;\n\treturn std::asin(sintheta);\n}\n\n\n/**\n * get k from crystal angle\n * @see https://en.wikipedia.org/wiki/Bragg's_law\n *\n * k = n pi / (d sin(theta))\n */\ntemplate\nt_real calc_tas_k(t_real theta, t_real d)\n{\n\tt_real sintheta = std::abs(std::sin(theta));\n\treturn pi / (d * sintheta);\n}\n\n\n/**\n * get ki from kf and energy transfer\n */\ntemplate\nt_real calc_tas_ki(t_real kf, t_real E)\n{\n\treturn std::sqrt(kf*kf + E_to_k2*E);\n}\n\n\n/**\n * get kf from ki and energy transfer\n */\ntemplate\nt_real calc_tas_kf(t_real ki, t_real E)\n{\n\treturn std::sqrt(ki*ki - E_to_k2*E);\n}\n\n\n/**\n * get energy transfer from ki and kf\n */\ntemplate\nt_real calc_tas_E(t_real ki, t_real kf)\n{\n\treturn (ki*ki - kf*kf) / E_to_k2;\n}\n\n// ----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n// projection operators\n// ----------------------------------------------------------------------------\n\n/**\n * matrix to project onto vector: P = |v> = * |v> = |v> = |v>\n * @see (Arens 2015), p. 814 for the projection tensor\n */\ntemplate\nt_mat projector(const t_vec& vec, bool bIsNormalised = true)\nrequires is_vec && is_mat\n{\n\tif(bIsNormalised)\n\t{\n\t\treturn outer(vec, vec);\n\t}\n\telse\n\t{\n\t\tconst auto len = norm(vec);\n\t\tt_vec _vec = vec / len;\n\t\treturn outer(_vec, _vec);\n\t}\n}\n\n\n/**\n * project vec1 onto vec2\n *\n * proj_op = |vec2>)\n * proj = proj_op * vec1 = |vec2> * / \n *\n * @see (Arens 2015), p. 814 for the projection tensor\n */\ntemplate\nt_vec project(const t_vec& vec, const t_vec& vecProj, bool bIsNormalised = true)\nrequires is_vec\n{\n\tif(bIsNormalised)\n\t{\n\t\treturn inner(vec, vecProj) * vecProj;\n\t}\n\telse\n\t{\n\t\tconst auto len = norm(vecProj);\n\t\tconst t_vec _vecProj = vecProj / len;\n\t\treturn inner(vec, _vecProj) * _vecProj;\n\t}\n}\n\n\n/**\n * project vector vec onto another vector vecProj\n * don't multiply with direction vector\n *\n * @see (Arens 2015), p. 814 for the projection tensor\n */\ntemplate\nt_real project_scalar(const t_vec& vec, const t_vec& vecProj, bool bIsNormalised = true)\nrequires is_vec\n{\n\tif(bIsNormalised)\n\t{\n\t\treturn inner(vec, vecProj);\n\t}\n\telse\n\t{\n\t\tconst auto len = norm(vecProj);\n\t\tconst t_vec _vecProj = vecProj / len;\n\t\treturn inner(vec, _vecProj);\n\t}\n}\n\n\n/**\n * project vector vec onto the line lineOrigin + lam*lineDir\n * (shifts line to go through origin, calculate projection and shift back)\n * @returns [closest point, distance, projection parameter]\n *\n * @see https://de.wikipedia.org/wiki/Lot_(Mathematik)\n */\ntemplate\nstd::tuple project_line(const t_vec& vec,\n\tconst t_vec& lineOrigin, const t_vec& _lineDir, bool bIsNormalised = true)\nrequires is_vec\n{\n\tconst t_real lenDir = bIsNormalised ? 1 : norm(_lineDir);\n\tconst t_vec lineDir = _lineDir / lenDir;\n\tconst t_vec ptShifted = vec - lineOrigin;\n\n\tconst t_real paramProj = project_scalar(ptShifted, lineDir, true);\n\tconst t_vec ptProj = paramProj * lineDir;\n\n\tconst t_vec ptNearest = lineOrigin + ptProj;\n\tconst t_real dist = norm(vec - ptNearest);\n\treturn std::make_tuple(ptNearest, dist, paramProj);\n}\n\n\n/**\n * distance between point and line\n * @see (Arens 2015), p. 711\n */\ntemplate\nt_real dist_pt_line(const t_vec& pt,\n\tconst t_vec& linePt1, const t_vec& linePt2,\n\tbool bLineIsInfinite = true)\nrequires is_vec\n{\n\tconst std::size_t dim = linePt1.size();\n\n\tconst t_vec lineDir = linePt2 - linePt1;\n\tconst auto [nearestPt, dist, paramProj] =\n\t\tproject_line(pt, linePt1, lineDir, false);\n\n\n\t// get point component with max. difference\n\tt_real diff = -1.;\n\tstd::size_t compidx = 0;\n\tfor(std::size_t i=0; i diff)\n\t\t{\n\t\t\tdiff = newdiff;\n\t\t\tcompidx = i;\n\t\t}\n\t}\n\n\n\tt_real t = (nearestPt[compidx]-linePt1[compidx]) / (linePt2[compidx]-linePt1[compidx]);\n\tif(bLineIsInfinite || (t>=t_real{0} && t<=t_real{1}))\n\t{\n\t\t// projection is on line -> use distance between point and projection\n\t\treturn dist;\n\t}\n\telse\n\t{\n\t\t// projection is not on line -> use distance between point and closest line end point\n\t\tif(std::abs(t-t_real{0}) < std::abs(t-t_real{1}))\n\t\t\treturn norm(linePt1 - pt);\n\t\telse\n\t\t\treturn norm(linePt2 - pt);\n\t}\n}\n\n\n/**\n * matrix to project onto orthogonal complement (plane perpendicular to vector): P = 1-|v>\nt_mat ortho_projector(const t_vec& vec, bool bIsNormalised = true)\nrequires is_vec && is_mat\n{\n\tconst std::size_t iSize = vec.size();\n\treturn unit(iSize) -\n\t\tprojector(vec, bIsNormalised);\n}\n\n\n/**\n * matrix to mirror on plane perpendicular to vector: P = 1 - 2*|v>\nt_mat ortho_mirror_op(const t_vec& vec, bool bIsNormalised = true)\nrequires is_vec && is_mat\n{\n\tusing T = typename t_vec::value_type;\n\tconst std::size_t iSize = vec.size();\n\n\treturn unit(iSize) -\n\t\tT(2)*projector(vec, bIsNormalised);\n}\n\n\n/**\n * matrix to mirror [a, b, c, ...] into, e.g., [a, b', 0, 0]\n * @see (Scarpino 2011), p. 268\n */\ntemplate\nt_mat ortho_mirror_zero_op(const t_vec& vec, std::size_t row)\nrequires is_vec && is_mat\n{\n\tusing T = typename t_vec::value_type;\n\tconst std::size_t N = vec.size();\n\n\tt_vec vecSub = zero(N);\n\tfor(std::size_t i=0; i return unit matrix\n\tif(equals_0(vecOp))\n\t\treturn unit(vecOp.size(), vecOp.size());\n\n\treturn ortho_mirror_op(vecOp, false);\n}\n\n\n/**\n * project vector vec onto plane through the origin and perpendicular to vector vecNorm\n * (e.g. used to calculate magnetic interaction vector M_perp)\n */\ntemplate\nt_vec ortho_project(const t_vec& vec, const t_vec& vecNorm, bool bIsNormalised = true)\nrequires is_vec\n{\n\treturn vec - project(vec, vecNorm, bIsNormalised);\n}\n\n\n/**\n * project vector vec onto plane perpendicular to vector vecNorm with distance d\n * vecNorm has to be normalised and plane in Hessian form: x*vecNorm = d\n */\ntemplate\nt_vec ortho_project_plane(const t_vec& vec,\n\tconst t_vec& vecNorm, typename t_vec::value_type d)\nrequires is_vec\n{\n\t// project onto plane through origin\n\tt_vec vecProj0 = ortho_project(vec, vecNorm, 1);\n\t// add distance of plane to origin\n\treturn vecProj0 + d*vecNorm;\n}\n\n\n/**\n * mirror a vector on a plane perpendicular to vector vecNorm with distance d\n * vecNorm has to be normalised and plane in Hessian form: x*vecNorm = d\n * @see (Arens 2015), p. 710\n */\ntemplate\nt_vec ortho_mirror_plane(const t_vec& vec,\n\tconst t_vec& vecNorm, typename t_vec::value_type d)\nrequires is_vec\n{\n\tusing T = typename t_vec::value_type;\n\n\tt_vec vecProj = ortho_project_plane(vec, vecNorm, d);\n\treturn vec - T(2)*(vec - vecProj);\n}\n\n\n/**\n * find orthonormal substitute basis for vector space (Gram-Schmidt algo)\n * remove orthogonal projections to all other base vectors: |i'> = (1 - sum_{j\n *\n * @see https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process\n * @see (Arens 2015), p. 744\n */\ntemplate class t_cont_in = std::initializer_list,\n\ttemplate class t_cont_out = std::vector>\nt_cont_out orthonorm_sys(const t_cont_in& sys)\nrequires is_vec\n{\n\tt_cont_out newsys;\n\tnewsys.reserve(sys.size());\n\n\tfor(const t_vec& vecSys : sys)\n\t{\n\t\tt_vec vecOrthoProj = vecSys;\n\n\t\t// subtract projections to other basis vectors\n\t\tfor(const t_vec& vecNewSys : newsys)\n\t\t\tvecOrthoProj -= project(vecSys, vecNewSys, true);\n\n\t\t// normalise\n\t\tvecOrthoProj /= norm(vecOrthoProj);\n\t\tnewsys.emplace_back(std::move(vecOrthoProj));\n\t}\n\n\treturn newsys;\n}\n// ----------------------------------------------------------------------------\n\n\n/**\n * submatrix removing a column/row from a matrix stored in a vector container\n */\ntemplate\nt_vec flat_submat(const t_vec& mat,\n\tstd::size_t iNumRows, std::size_t iNumCols,\n\tstd::size_t iRemRow, std::size_t iRemCol)\nrequires is_basic_vec\n{\n\tt_vec vec;\n\tvec.reserve(mat.size());\n\n\tfor(std::size_t iRow=0; iRow\nt_mat submat(const t_mat& mat, decltype(mat.size1()) iRemRow, decltype(mat.size2()) iRemCol)\nrequires is_basic_mat && is_dyn_mat\n{\n\tusing size_t = decltype(mat.size1());\n\tt_mat matRet = create(mat.size1()-1, mat.size2()-1);\n\n\tsize_t iResRow = 0;\n\tfor(size_t iRow=0; iRow\ntypename t_vec::value_type flat_det(const t_vec& mat, std::size_t iN)\nrequires is_basic_vec\n{\n\tusing T = typename t_vec::value_type;\n\n\t// special cases\n\tif(iN == 0)\n\t\treturn 0;\n\telse if(iN == 1)\n\t\treturn mat[0];\n\telse if(iN == 2)\n\t\treturn mat[0]*mat[3] - mat[1]*mat[2];\n\n\t// recursively expand determiant along a row\n\tT fullDet = T(0);\n\tstd::size_t iRow = 0;\n\n\t// get row with maximum number of zeros\n\tstd::size_t iMaxNumZeros = 0;\n\tfor(std::size_t iCurRow=0; iCurRow(mat[iCurRow*iN + iCurCol], T(0)))\n\t\t\t\t++iNumZeros;\n\t\t}\n\n\t\tif(iNumZeros > iMaxNumZeros)\n\t\t{\n\t\t\tiRow = iCurRow;\n\t\t\tiMaxNumZeros = iNumZeros;\n\t\t}\n\t}\n\n\tfor(std::size_t iCol=0; iCol(elem, 0))\n\t\t\tcontinue;\n\n\t\tconst T sgn = ((iRow+iCol) % 2) == 0 ? T(1) : T(-1);\n\t\tconst t_vec subMat = flat_submat(mat, iN, iN, iRow, iCol);\n\t\tconst T subDet = flat_det(subMat, iN-1) * sgn;\n\n\t\tfullDet += elem * subDet;\n\t}\n\n\treturn fullDet;\n}\n\n\n/**\n * trace\n */\ntemplate\ntypename t_mat::value_type trace(const t_mat& mat)\nrequires is_mat\n{\n\tusing T = typename t_mat::value_type;\n\tT _tr = T(0);\n\n\tstd::size_t N = std::min(mat.size1(), mat.size2());\n\tfor(std::size_t i=0; i from real basis vectors |a_i> (and vice versa)\n * c: multiplicative constant (c=2*pi for physical lattices, c=1 for mathematics)\n *\n * Def.: = c * delta(i,j) =>\n *\n * e.g. 2d case:\n * ( a_1x a_2x )\n * ( a_1y a_2y )\n *\n * ( b_1x b_1y ) ( 1 0 )\n * ( b_2x b_2y ) ( 0 1 )\n *\n * B^t * A = I\n * A = B^(-t)\n */\ntemplate class t_cont_in = std::initializer_list,\n\ttemplate class t_cont_out = std::vector>\nt_cont_out recip(const t_cont_in& lstReal, typename t_vec::value_type c=1)\nrequires is_mat && is_basic_vec\n{\n\tconst t_mat basis = create(lstReal);\n\tauto [basis_inv, bOk] = inv(basis);\n\tbasis_inv *= c;\n\n\tt_cont_out lstRecip;\n\tlstRecip.reserve(basis_inv.size1());\n\n\tfor(std::size_t currow=0; currow(basis_inv, currow);\n\t\tlstRecip.emplace_back(std::move(rowvec));\n\t}\n\n\treturn lstRecip;\n}\n\n\n/**\n * general n-dim cross product using determinant definition\n */\ntemplate class t_cont = std::initializer_list>\nt_vec cross(const t_cont& vecs)\nrequires is_basic_vec\n{\n\tusing T = typename t_vec::value_type;\n\t// N also has to be equal to the vector size!\n\tconst std::size_t N = vecs.size()+1;\n\tt_vec vec = zero(N);\n\n\tfor(std::size_t iComp=0; iComp mat = zero>(N*N);\n\t\tmat[0*N + iComp] = T(1);\n\n\t\tstd::size_t iRow = 0;\n\t\tfor(const t_vec& vec : vecs)\n\t\t{\n\t\t\tfor(std::size_t iCol=0; iCol(mat, N);\n\t}\n\n\treturn vec;\n}\n\n\n/**\n * intersection of plane = d and line |org> + lam*|dir>\n * @returns [position of intersection, 0: no intersection, 1: intersection, 2: line on plane, line parameter lambda]\n *\n * insert |x> = |org> + lam*|dir> in plane equation:\n * + lam* = d\n * lam = (d - ) / \n *\n * @see http://mathworld.wolfram.com/Line-PlaneIntersection.html\n */\ntemplate\nstd::tuple\nintersect_line_plane(\n\tconst t_vec& lineOrg, const t_vec& lineDir,\n\tconst t_vec& planeNorm, typename t_vec::value_type plane_d)\nrequires is_vec\n{\n\tusing T = typename t_vec::value_type;\n\n\t// are line and plane parallel?\n\tconst T dir_n = inner(lineDir, planeNorm);\n\tif(equals(dir_n, 0))\n\t{\n\t\tconst T org_n = inner(lineOrg, planeNorm);\n\t\t// line on plane?\n\t\tif(equals(org_n, plane_d))\n\t\t\treturn std::make_tuple(t_vec(), 2, T(0));\n\t\t// no intersection\n\t\treturn std::make_tuple(t_vec(), 0, T(0));\n\t}\n\n\tconst T org_n = inner(lineOrg, planeNorm);\n\tconst T lam = (plane_d - org_n) / dir_n;\n\n\tconst t_vec vecInters = lineOrg + lam*lineDir;\n\treturn std::make_tuple(vecInters, 1, lam);\n}\n\n\n/**\n * intersection of a sphere and a line |org> + lam*|dir>\n * @returns vector of intersections\n * insert |x> = |org> + lam*|dir> in sphere equation = r^2\n *\n * @see https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection for the solution.\n */\ntemplate class t_cont = std::vector>\nrequires is_vec\nt_cont intersect_line_sphere(\n\tconst t_vec& lineOrg, const t_vec& _lineDir,\n\tconst t_vec& sphereOrg, typename t_vec::value_type sphereRad,\n\tbool linedir_normalised = false, bool only_segment = false,\n\ttypename t_vec::value_type eps = std::numeric_limits::epsilon())\n{\n\tusing T = typename t_vec::value_type;\n\n\tt_vec lineDir = _lineDir;\n\tT lenDir = linedir_normalised ? T(1) : norm(lineDir);\n\n\tif(!linedir_normalised)\n\t\tlineDir /= lenDir;\n\n\tauto vecDiff = sphereOrg - lineOrg;\n\tauto proj = project_scalar(vecDiff, lineDir, true);\n\tauto rt = proj*proj + sphereRad*sphereRad - inner(vecDiff, vecDiff);\n\n\t// no intersection\n\tif(rt < T(0))\n\t\treturn t_cont{};\n\n\t// one intersection\n\tif(equals(rt, T(0), eps))\n\t{\n\t\tT lam = proj/lenDir;\n\t\tif(!only_segment || (only_segment && lam >= T(0) && lam < T(1)))\n\t\t\treturn t_cont{{ lineOrg + proj*lineDir }};\n\t\treturn t_cont{};\n\t}\n\n\t// two intersections\n\tauto val = std::sqrt(rt);\n\tt_cont inters;\n\tinters.reserve(2);\n\n\tT lam1 = (proj + val)/lenDir;\n\tT lam2 = (proj - val)/lenDir;\n\n\tif(!only_segment || (only_segment && lam1 >= T(0) && lam1 < T(1)))\n\t\tinters.emplace_back(lineOrg + (proj + val)*lineDir);\n\tif(!only_segment || (only_segment && lam2 >= T(0) && lam2 < T(1)))\n\t\tinters.emplace_back(lineOrg + (proj - val)*lineDir);\n\n\t// sort intersections by x\n\tstd::sort(inters.begin(), inters.end(), \n\t\t[](const t_vec& vec1, const t_vec& vec2) -> bool\n\t\t{ return vec1[0] < vec2[0]; });\n\n\treturn inters;\n}\n\n\n/**\n * average vector or matrix\n */\ntemplate class t_cont = std::vector>\nty avg(const t_cont& vecs)\nrequires is_vec || is_mat\n{\n\tif(vecs.size() == 0)\n\t\treturn ty();\n\n\ttypename ty::value_type num = 1;\n\tty vec = *vecs.begin();\n\n\tauto iter = vecs.begin();\n\tstd::advance(iter, 1);\n\n\tfor(; iter!=vecs.end(); std::advance(iter, 1))\n\t{\n\t\tvec += *iter;\n\t\t++num;\n\t}\n\tvec /= num;\n\n\treturn vec;\n}\n\n\n/**\n * intersection of a polygon and a line\n * @returns [position of intersection, intersects?, line parameter lambda]\n */\ntemplate class t_cont = std::vector>\nstd::tuple\nintersect_line_poly(\n\tconst t_vec& lineOrg, const t_vec& lineDir,\n\tconst t_cont& poly)\nrequires is_vec\n{\n\tusing T = typename t_vec::value_type;\n\n\t// middle point\n\tconst t_vec mid = avg(poly);\n\n\t// calculate polygon plane\n\tconst t_vec vec0 = poly[0] - mid;\n\tconst t_vec vec1 = poly[1] - mid;\n\tt_vec planeNorm = cross({vec0, vec1});\n\tplaneNorm /= norm(planeNorm);\n\tconst T planeD = inner(poly[0], planeNorm);\n\n\t// intersection with plane\n\tauto [vec, intersects, lam] = \n\t\tintersect_line_plane(lineOrg, lineDir, planeNorm, planeD);\n\tif(intersects != 1)\n\t\treturn std::make_tuple(t_vec(), false, T(0));\n\n\t// is intersection point contained in polygon?\n\tconst t_vec* vecFirst = &(*poly.rbegin());\n\tfor(auto iter=poly.begin(); iter!=poly.end(); std::advance(iter, 1))\n\t{\n\t\tconst t_vec* vecSecond = &(*iter);\n\t\tconst t_vec edge = *vecSecond - *vecFirst;\n\n\t\t// plane through edge\n\t\tt_vec edgeNorm = cross({edge, planeNorm});\n\t\tedgeNorm /= norm(edgeNorm);\n\t\tconst T edgePlaneD = inner(*vecFirst, edgeNorm);\n\n\t\t// side of intersection\n\t\tconst T ptEdgeD = inner(vec, edgeNorm);\n\n\t\t// outside polygon?\n\t\tif(ptEdgeD > edgePlaneD)\n\t\t\treturn std::make_tuple(t_vec(), false, T(0));\n\n\t\tvecFirst = vecSecond;\n\t}\n\n\t// intersects with polygon\n\treturn std::make_tuple(vec, true, lam);\n}\n\n\n/**\n * intersection of a polygon (transformed with a matrix) and a line\n * @returns [position of intersection, intersects?, line parameter lambda]\n */\ntemplate class t_cont = std::vector>\nstd::tuple\nintersect_line_poly(\n\tconst t_vec& lineOrg, const t_vec& lineDir,\n\tconst t_cont& _poly, const t_mat& mat)\nrequires is_vec && is_mat\n{\n\tauto poly = _poly;\n\n\t// transform each vertex of the polygon\n\t// TODO: check for homogeneous coordinates!\n\tfor(t_vec& vec : poly)\n\t\tvec = mat * vec;\n\n\treturn intersect_line_poly(lineOrg, lineDir, poly);\n}\n\n\n/**\n * intersection or closest points of lines |org1> + lam1*|dir1> and |org2> + lam2*|dir2>\n * @returns [nearest position 1, nearest position 2, dist, valid?, line parameter 1, line parameter 2]\n *\n * |org1> + lam1*|dir1> = |org2> + lam2*|dir2>\n * |org1> - |org2> = lam2*|dir2> - lam1*|dir1>\n * |org1> - |org2> = (dir2 | -dir1) * |lam2 lam1>\n * (dir2 | -dir1)^T * (|org1> - |org2>) = (dir2 | -dir1)^T * (dir2 | -dir1) * |lam2 lam1>\n * |lam2 lam1> = ((dir2 | -dir1)^T * (dir2 | -dir1))^(-1) * (dir2 | -dir1)^T * (|org1> - |org2>)\n *\n * @see https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection\n */\ntemplate\nstd::tuple\nintersect_line_line(\n\tconst t_vec& line1Org, const t_vec& line1Dir,\n\tconst t_vec& line2Org, const t_vec& line2Dir,\n\tt_real eps = std::numeric_limits::epsilon())\nrequires is_vec\n{\n\tconst t_vec orgdiff = line1Org - line2Org;\n\n\t// direction matrix (symmetric)\n\tconst t_real d11 = inner(line2Dir, line2Dir);\n\tconst t_real d12 = -inner(line2Dir, line1Dir);\n\tconst t_real d22 = inner(line1Dir, line1Dir);\n\n\tconst t_real d_det = d11*d22 - d12*d12;\n\n\t// check if matrix is invertible\n\tif(equals(d_det, 0, eps))\n\t\treturn std::make_tuple(t_vec(), t_vec(), false, 0, 0, 0);\n\n\t// inverse (symmetric)\n\tconst t_real d11_i = d22 / d_det;\n\tconst t_real d12_i = -d12 / d_det;\n\tconst t_real d22_i = d11 / d_det;\n\n\tconst t_vec v1 = d11_i*line2Dir - d12_i*line1Dir;\n\tconst t_vec v2 = d12_i*line2Dir - d22_i*line1Dir;\n\n\tconst t_real lam2 = inner(v1, orgdiff);\n\tconst t_real lam1 = inner(v2, orgdiff);\n\n\tconst t_vec pos1 = line1Org + lam1*line1Dir;\n\tconst t_vec pos2 = line2Org + lam2*line2Dir;\n\tconst t_real dist = norm(pos2 - pos1);\n\n\treturn std::make_tuple(pos1, pos2, true, dist, lam1, lam2);\n}\n\n\n/**\n * intersection of planes = d1 and = d2\n * @returns line [org, dir, 0: no intersection, 1: intersection, 2: planes coincide]\n *\n * @see http://mathworld.wolfram.com/Plane-PlaneIntersection.html\n */\ntemplate\nstd::tuple\n\tintersect_plane_plane(\n\tconst t_vec& plane1Norm, typename t_vec::value_type plane1_d,\n\tconst t_vec& plane2Norm, typename t_vec::value_type plane2_d)\nrequires is_vec\n{\n\tusing T = typename t_vec::value_type;\n\n\tt_vec lineDir = cross({plane1Norm, plane2Norm});\n\tconst T lenCross = norm(lineDir);\n\n\t// planes parallel or coinciding\n\tif(equals(lenCross, 0))\n\t{\n\t\tconst bool bCoincide = equals(plane1_d, plane2_d);\n\t\treturn std::make_tuple(t_vec(), t_vec(), bCoincide ? 2 : 0);\n\t}\n\n\tlineDir /= lenCross;\n\n\tt_vec lineOrg = - cross({plane1Norm, lineDir}) * plane2_d\n\t\t+ cross({plane2Norm, lineDir}) * plane1_d;\n\tlineOrg /= lenCross;\n\n\treturn std::make_tuple(lineOrg, lineDir, 1);\n}\n\n\n/**\n * uv coordinates of a point inside a polygon defined by three vertices\n */\ntemplate\nt_vec poly_uv_ortho(const t_vec& vert1, const t_vec& vert2, const t_vec& vert3,\n\tconst t_vec& uv1, const t_vec& uv2, const t_vec& uv3,\n\tconst t_vec& _pt)\nrequires is_vec\n{\n\tusing T = typename t_vec::value_type;\n\n\tt_vec vec12 = vert2 - vert1;\n\tt_vec vec13 = vert3 - vert1;\n\n\tt_vec uv12 = uv2 - uv1;\n\tt_vec uv13 = uv3 - uv1;\n\n\n\t// ----------------------------------------------------\n\t// orthonormalisation\n\tconst T len12 = norm(vec12);\n\tconst T len13 = norm(vec13);\n\tconst T lenuv12 = norm(uv12);\n\tconst T lenuv13 = norm(uv13);\n\tauto vecBasis = orthonorm_sys({vec12, vec13});\n\tauto uvBasis = orthonorm_sys({uv12, uv13});\n\tvec12 = vecBasis[0]*len12; vec13 = vecBasis[1]*len13;\n\tuv12 = uvBasis[0]*lenuv12; uv13 = uvBasis[1]*lenuv13;\n\t// ----------------------------------------------------\n\n\n\tconst t_vec pt = _pt - vert1;\n\n\t// project a point onto a vector and return the fraction along that vector\n\tauto project_lam = [](const t_vec& vec, const t_vec& vecProj) -> T\n\t{\n\t\tconst T len = norm(vecProj);\n\t\tconst t_vec _vecProj = vecProj / len;\n\t\tT lam = inner(vec, _vecProj);\n\t\treturn lam / len;\n\t};\n\n\tT lam12 = project_lam(pt, vec12);\n\tT lam13 = project_lam(pt, vec13);\n\n\t// uv coordinates at specified point\n\tconst t_vec uv_pt = uv1 + lam12*uv12 + lam13*uv13;\n\treturn uv_pt;\n}\n\n\n/**\n * uv coordinates of a point inside a polygon defined by three vertices\n * (more general version than poly_uv_ortho)\n */\ntemplate\nt_vec poly_uv(const t_vec& vert1, const t_vec& vert2, const t_vec& vert3,\n\tconst t_vec& uv1, const t_vec& uv2, const t_vec& uv3,\n\tconst t_vec& _pt)\nrequires is_mat && is_vec\n{\n\tt_vec vec12 = vert2 - vert1;\n\tt_vec vec13 = vert3 - vert1;\n\tt_vec vecnorm = cross({vec12, vec13});\n\n\t// basis\n\tconst t_mat basis = create({vec12, vec13, vecnorm}, false);\n\n\t// reciprocal basis, RECI = REAL^(-T)\n\tconst auto [basisInv, bOk] = inv(basis);\n\tif(!bOk) return zero(uv1.size());\n\n\tt_vec pt = _pt - vert1;\t\t// real pt\n\tpt = basisInv * pt;\t\t// reciprocal pt\n\n\t// uv coordinates at specified point\n\tt_vec uv12 = uv2 - uv1;\n\tt_vec uv13 = uv3 - uv1;\n\n\t// pt has components in common reciprocal basis\n\t// assumes that both vector and uv coordinates have the same reciprocal basis\n\treturn uv1 + pt[0]*uv12 + pt[1]*uv13;\n}\n// ----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n// Statistical functions\n// ----------------------------------------------------------------------------\n\n/**\n * mean value\n */\ntemplate class t_cont = std::vector>\nt_elem mean(const t_cont& vec)\nrequires is_basic_vec>\n{\n\tif(vec.size()==0) return t_elem{};\n\telse if(vec.size()==1) return *vec.begin();\n\n\tusing namespace tl2_ops;\n\n\t//t_elem meanvec = std::accumulate(std::next(vec.begin(), 1), vec.end(), *vec.begin());\n\n\tt_elem meanvec = *vec.begin();\n\tauto iter = std::next(vec.begin(), 1);\n\tfor(; iter!=vec.end(); iter=std::next(iter, 1))\n\t\tmeanvec += *iter;\n\n\tmeanvec /= vec.size();\n\treturn meanvec;\n}\n\n\n/**\n * mean value with given probability\n */\ntemplate\ntypename t_vec::value_type mean(const t_vec_prob& vecP, const t_vec& vec)\nrequires is_basic_vec && is_basic_vec\n{\n\ttypedef typename t_vec::value_type T;\n\ttypedef typename t_vec_prob::value_type Tprob;\n\tstd::size_t iSize = std::min(vecP.size(), vec.size());\n\n\tif(iSize==0) return T(0);\n\n\tT tMean = vecP[0]*vec[0];\n\tTprob tProbTotal = vecP[0];\n\tfor(std::size_t i=1; i\ntypename t_vec::value_type std_dev(const t_vec& vec, bool bCorr=1)\nrequires is_basic_vec\n{\n\ttypedef typename t_vec::value_type T;\n\tif(vec.size()<=1) return T(0);\n\n\tT tProb = T(vec.size());\n\tif(bCorr) tProb -= T(1);\n\n\tT tMean = mean(vec);\n\tT t = T(0);\n\tfor(const T& tval : vec)\n\t\tt += (tval-tMean) * (tval-tMean);\n\tt /= tProb;\n\n\treturn std::sqrt(t);\n}\n\n\n/**\n * standard deviation with given probability\n * @see https://en.wikipedia.org/wiki/Standard_deviation\n */\ntemplate\ntypename t_vec::value_type std_dev(const t_vec_prob& vecP, const t_vec& vec)\nrequires is_basic_vec && is_basic_vec\n{\n\ttypedef typename t_vec::value_type T;\n\tstd::size_t iSize = std::min(vecP.size(), vec.size());\n\tif(iSize<=1) return T(0);\n\n\tT tMean = mean(vecP, vec);\n\tT t = T(0);\n\tT tProbTotal = T(0);\n\n\tfor(std::size_t iIdx = 0; iIdx class t_cont = std::vector>\nstd::tuple minmax(const t_cont& verts)\nrequires is_vec\n{\n\tusing namespace tl2_ops;\n\tusing t_real = typename t_vec::value_type;\n\n\tif(!verts.size())\n\t\treturn std::make_tuple(t_vec{}, t_vec{});\n\n\t// set to limit values\n\tt_vec vecmin = zero(verts.begin()->size());\n\tt_vec vecmax = zero(verts.begin()->size());\n\tfor(std::size_t i=0; i::max();\n\t\tvecmax[i] = -std::numeric_limits::max();\n\t}\n\n\t// iterate components\n\tfor(std::size_t i=0; i) * (X_j - ) >\n * correlation: K_ij = C_ij / (sigma_i sigma_j)\n *\n * @see http://www.itl.nist.gov/div898/handbook/pmc/section5/pmc541.htm\n * @see (Arfken 2013) pp. 1142-1144\n * @see (Arens 2015), p. 795 and p. 1372\n */\ntemplate\nstd::tuple\ncovariance(const std::vector& vecVals, const std::vector* pProb = 0)\nrequires is_mat && is_vec\n{\n\tusing t_vecvec = typename std::remove_reference::type;\n\tusing t_innervec_org = decltype(vecVals[0]);\n\tusing t_innervec = typename std::remove_const<\n\t\ttypename std::remove_reference::type>::type;\n\n\tif(vecVals.size() == 0)\n\t\treturn std::make_tuple(t_mat(), t_mat());\n\n\t// mean vector \n\tt_innervec vecMean;\n\tif(pProb)\n\t\tvecMean = mean, t_vecvec>(*pProb, vecVals);\n\telse\n\t\tvecMean = mean(vecVals);\n\n\tt_mat matCov = zero(vecVals[0].size(), vecVals[0].size());\n\tT tSum = T{0};\n\tconst std::size_t N = vecVals.size();\n\n\tfor(std::size_t i=0; i\n\t\tt_innervec vec = vecVals[i] - vecMean;\n\n\t\t// matrix elements, AA^t\n\t\tt_mat matOuter = outer(vec, vec);\n\n\t\t// probabilities for final averaging, <...>\n\t\tif(pProb)\n\t\t{\n\t\t\ttprob = (*pProb)[i];\n\t\t\tmatOuter *= tprob;\n\t\t}\n\n\t\tmatCov += matOuter;\n\t\ttSum += tprob;\n\t}\n\n\t// average, sometimes defined as C /= (N-1)\n\tmatCov /= tSum /*-T(1)*/;\n\n\n\t// --------------------------------------------------------------------------------\n\t// correlation matrix\n\tt_innervec vecVar = diag_vec(matCov);\n\tt_innervec vecStdDev(vecVar.size());\n\n\tstd::transform(vecVar.begin(), vecVar.end(), vecStdDev.begin(),\n\t\t[](typename t_innervec::value_type d) -> typename t_innervec::value_type\n\t\t{ return std::sqrt(d); });\n\n\tt_mat matStdDev = outer(vecStdDev, vecStdDev);\n\tt_mat matCorr = div_perelem(matCov, matStdDev);\n\t// --------------------------------------------------------------------------------\n\n\treturn std::make_tuple(matCov, matCorr);\n}\n\n\n/**\n * calculates chi^2 distance of a function model to data points\n * chi^2 = sum( (y_i - f(x_i))^2 / sigma_i^2 )\n *\n * @see (Arfken 2013), p. 1170\n */\ntemplate\nT chi2(const t_func& func, std::size_t N,\n\tconst t_iter_dat x, const t_iter_dat y, const t_iter_dat dy)\n{\n\tusing t_dat = typename std::remove_pointer::type;\n\tT tchi2 = T{0};\n\n\tfor(std::size_t i=0; i::min())\n\t\t\ttdy = std::numeric_limits::min();\n\n\t\tT tchi = T(td) / T(tdy);\n\t\ttchi2 += tchi*tchi;\n\t}\n\n\treturn tchi2;\n}\n\n\n/**\n * chi^2 for vector types\n *\n * @see (Merziger 2006), p. 185\n */\ntemplate\ntypename t_vec::value_type chi2(const t_func& func,\n\tconst t_vec& x, const t_vec& y, const t_vec& dy)\nrequires is_vec\n{\n\tusing T = typename t_vec::value_type;\n\treturn chi2(func, x.size(), x.data(), y.data(),\n\t\tdy.size() ? dy.data() : nullptr);\n}\n\n\n/**\n * chi^2 which doesn't use an x value, but an index instead: y[idx] - func(idx)\n * @see (Arfken 2013), p. 1170\n */\ntemplate\nT chi2_idx(const t_func& func, std::size_t N, const t_iter_dat y, const t_iter_dat dy)\n{\n\tusing t_dat = typename std::remove_pointer::type;\n\tT tchi2 = T(0);\n\n\tfor(std::size_t i=0; i::min())\n\t\t\ttdy = std::numeric_limits::min();\n\n\t\tT tchi = T(td) / T(tdy);\n\t\ttchi2 += tchi*tchi;\n\t}\n\n\treturn tchi2;\n}\n\n\n/**\n * direct chi^2 calculation with a model array instead of a model function\n * @see (Arfken 2013), p. 1170\n */\ntemplate\nT chi2_direct(std::size_t N, const t_iter_dat func_y, const t_iter_dat y, const t_iter_dat dy)\n{\n\tusing t_dat = typename std::remove_pointer::type;\n\tT tchi2 = T(0);\n\n\tfor(std::size_t i=0; i::min())\n\t\t\ttdy = std::numeric_limits::min();\n\n\t\tT tchi = T(td) / T(tdy);\n\t\ttchi2 += tchi*tchi;\n\t}\n\n\treturn tchi2;\n}\n\n\n\n/**\n * multi-dimensional chi^2 function\n * @see (Arfken 2013), p. 1170\n */\ntemplate class t_vec=std::vector>\nT chi2_nd(const t_func& func,\n\tconst t_vec>& vecvecX, const t_vec& vecY, const t_vec& vecDY)\n{\n\tT tchi2 = T(0);\n\n\tfor(std::size_t i=0; i::min())\n\t\t\ttdy = std::numeric_limits::min();\n\n\t\tT tchi = T(td) / T(tdy);\n\t\ttchi2 += tchi*tchi;\n\t}\n\n\treturn tchi2;\n}\n// ----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n// 3-dim algos\n// ----------------------------------------------------------------------------\n\n/**\n * 3-dim cross product\n */\ntemplate\nt_vec cross(const t_vec& vec1, const t_vec& vec2)\nrequires is_basic_vec\n{\n\tt_vec vec;\n\n\t// only valid for 3-vectors -> use first three components\n\tif(vec1.size() < 3 || vec2.size() < 3)\n\t\treturn vec;\n\n\tif constexpr(is_dyn_vec)\n\t\tvec = t_vec(3);\n\n\tfor(int i=0; i<3; ++i)\n\t\tvec[i] = vec1[(i+1)%3]*vec2[(i+2)%3] - vec1[(i+2)%3]*vec2[(i+1)%3];\n\n\treturn vec;\n}\n\n\n/**\n * cross product matrix (3x3)\n * @see https://en.wikipedia.org/wiki/Skew-symmetric_matrix\n */\ntemplate\nt_mat skewsymmetric(const t_vec& vec)\nrequires is_basic_vec && is_mat\n{\n\tt_mat mat;\n\tif constexpr(is_dyn_mat)\n\t\tmat = t_mat(3,3);\n\n\t// if static matrix is larger than 3x3 (e.g. for homogeneous coordinates), initialise as identity\n\tif(mat.size1() > 3 || mat.size2() > 3)\n\t\tmat = unit(mat.size1(), mat.size2());\n\n\tmat(0,0) = 0; \t\tmat(0,1) = -vec[2]; \tmat(0,2) = vec[1];\n\tmat(1,0) = vec[2]; \tmat(1,1) = 0; \t\tmat(1,2) = -vec[0];\n\tmat(2,0) = -vec[1]; \tmat(2,1) = vec[0]; \tmat(2,2) = 0;\n\n\treturn mat;\n}\n\n\n/**\n * SO(2) rotation matrix\n */\ntemplate\nt_mat rotation_2d(const typename t_mat::value_type angle)\nrequires tl2::is_mat\n{\n\tusing t_real = typename t_mat::value_type;\n\n\tconst t_real c = std::cos(angle);\n\tconst t_real s = std::sin(angle);\n\n\treturn create({{c,s}, {-s,c}});\n}\n\n\n/**\n * SO(3) matrix to rotate around an axis (Rodrigues' formula)\n * @see (Arens 2015), p. 718 and p. 816\n * @see (Merziger 2006), p. 208\n * @see https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula\n */\ntemplate\nt_mat rotation(const t_vec& axis, const typename t_vec::value_type angle, bool bIsNormalised=1)\nrequires is_vec && is_mat\n{\n\tusing t_real = typename t_vec::value_type;\n\n\tconst t_real c = std::cos(angle);\n\tconst t_real s = std::sin(angle);\n\n\tt_real len = 1;\n\tif(!bIsNormalised)\n\t\tlen = norm(axis);\n\n\t// ----------------------------------------------------\n\t// special cases: rotations around [100], [010], [001]\n\tif(equals(axis, create({ len, 0, 0 })))\n\t\treturn create({{1,0,0}, {0,c,s}, {0,-s,c}});\n\telse if(equals(axis, create({ 0, len, 0 })))\n\t\treturn create({{c,0,-s}, {0,1,0}, {s,0,c}});\n\telse if(equals(axis, create({ 0, 0, len })))\n\t\treturn create({{c,s,0}, {-s,c,0}, {0,0,1}});\n\n\t// ----------------------------------------------------\n\t// general case\n\t// project along rotation axis\n\tt_mat matProj1 = projector(axis, bIsNormalised);\n\n\t// project along axis 2 in plane perpendicular to rotation axis\n\tt_mat matProj2 = ortho_projector(axis, bIsNormalised) * c;\n\n\t// project along axis 3 in plane perpendicular to rotation axis and axis 2\n\tt_mat matProj3 = skewsymmetric(axis/len) * s;\n\n\t//std::cout << matProj1(3,3) << \" \" << matProj2(3,3) << \" \" << matProj3(3,3) << std::endl;\n\tt_mat matProj = matProj1 + matProj2 + matProj3;\n\n\t// if matrix is larger than 3x3 (e.g. for homogeneous cooridnates), fill up with identity\n\tunit(matProj, 3,3, matProj.size1(), matProj.size2());\n\treturn matProj;\n}\n\n\n/**\n * matrix to rotate vector vec1 into vec2\n */\ntemplate\nt_mat rotation(const t_vec& vec1, const t_vec& vec2,\n\tconst t_vec& normal_vec = create({0, 0, 1}))\nrequires is_vec && is_mat\n{\n\tusing t_real = typename t_vec::value_type;\n\tconstexpr t_real eps = 1e-6;\n\n\t// get rotation axis from cross product\n\tt_vec axis = cross({ vec1, vec2 });\n\tt_real lenaxis = norm(axis);\n\n\t// rotation angle\n\tconst t_real angle = std::atan2(lenaxis, inner(vec1, vec2));\n\n\t// collinear vectors?\n\tif(equals(angle, 0, eps))\n\t\treturn unit(vec1.size());\n\n\t// antiparallel vectors?\n\tif(equals(std::abs(angle), pi, eps))\n\t{\n\t\taxis = normal_vec;\n\t\tlenaxis = norm(axis);\n\t}\n\n\taxis /= lenaxis;\n\tt_mat mat = rotation(axis, angle, true);\n\treturn mat;\n}\n\n\n/**\n * extracts lines from polygon object, takes input from e.g. create_cube()\n * @returns [point pairs]\n */\ntemplate class t_cont = std::vector>\nt_cont create_lines(const t_cont& vertices, const t_cont>& faces)\nrequires is_vec\n{\n\tt_cont lineverts;\n\n\tauto line_already_seen = [&lineverts](const t_vec& vec1, const t_vec& vec2) -> bool\n\t{\n\t\tauto iter = lineverts.begin();\n\n\t\twhile(1)\n\t\t{\n\t\t\tconst t_vec& linevec1 = *iter;\n\t\t\tstd::advance(iter, 1); if(iter == lineverts.end()) break;\n\t\t\tconst t_vec& linevec2 = *iter;\n\n\t\t\tif(equals(vec1, linevec1) && equals(vec2, linevec2))\n\t\t\t\treturn true;\n\t\t\tif(equals(vec1, linevec2) && equals(vec2, linevec1))\n\t\t\t\treturn true;\n\n\t\t\tstd::advance(iter, 1); if(iter == lineverts.end()) break;\n\t\t}\n\n\t\treturn false;\n\t};\n\n\tfor(const auto& face : faces)\n\t{\n\t\t// iterator to last point\n\t\tauto iter1 = face.begin();\n\t\tstd::advance(iter1, face.size()-1);\n\n\t\tfor(auto iter2 = face.begin(); iter2 != face.end(); std::advance(iter2, 1))\n\t\t{\n\t\t\tconst t_vec& vec1 = vertices[*iter1];\n\t\t\tconst t_vec& vec2 = vertices[*iter2];\n\n\t\t\t//if(!line_already_seen(vec1, vec2))\n\t\t\t{\n\t\t\t\tlineverts.push_back(vec1);\n\t\t\t\tlineverts.push_back(vec2);\n\t\t\t}\n\n\t\t\titer1 = iter2;\n\t\t}\n\t}\n\n\treturn lineverts;\n}\n\n\n/**\n * triangulates polygon object, takes input from e.g. create_cube()\n * @returns [triangles, face normals, vertex uvs]\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont, t_cont>\ncreate_triangles(const std::tuple, t_cont>, \n\tt_cont, t_cont>>& tup)\nrequires is_vec\n{\n\tconst t_cont& vertices = std::get<0>(tup);\n\tconst t_cont>& faces = std::get<1>(tup);\n\tconst t_cont& normals = std::get<2>(tup);\n\tconst t_cont>& uvs = std::get<3>(tup);\n\n\tt_cont triangles;\n\tt_cont triag_normals;\n\tt_cont vert_uvs;\n\n\tauto iterFaces = faces.begin();\n\tauto iterNorms = normals.begin();\n\tauto iterUVs = uvs.begin();\n\n\t// iterate over faces\n\twhile(iterFaces != faces.end())\n\t{\n\t\t// triangulate faces\n\t\tauto iterFaceVertIdx = iterFaces->begin();\n\t\tstd::size_t vert1Idx = *iterFaceVertIdx;\n\t\tstd::advance(iterFaceVertIdx, 1);\n\t\tstd::size_t vert2Idx = *iterFaceVertIdx;\n\n\t\tconst t_vec *puv1 = nullptr;\n\t\tconst t_vec *puv2 = nullptr;\n\t\tconst t_vec *puv3 = nullptr;\n\n\t\ttypename t_cont::const_iterator iterFaceUVIdx;\n\t\tif(iterUVs != uvs.end() && iterFaceUVIdx != iterUVs->end())\n\t\t{\n\t\t\titerFaceUVIdx = iterUVs->begin();\n\n\t\t\tpuv1 = &(*iterFaceUVIdx);\n\t\t\tstd::advance(iterFaceUVIdx, 1);\n\t\t\tpuv2 = &(*iterFaceUVIdx);\n\t\t}\n\n\t\t// iterate over face vertices\n\t\twhile(1)\n\t\t{\n\t\t\tstd::advance(iterFaceVertIdx, 1);\n\t\t\tif(iterFaceVertIdx == iterFaces->end())\n\t\t\t\tbreak;\n\t\t\tstd::size_t vert3Idx = *iterFaceVertIdx;\n\n\t\t\tif(iterUVs != uvs.end() && iterFaceUVIdx != iterUVs->end())\n\t\t\t{\n\t\t\t\tstd::advance(iterFaceUVIdx, 1);\n\t\t\t\tpuv3 = &(*iterFaceUVIdx);\n\t\t\t}\n\n\t\t\t// create triangle\n\t\t\ttriangles.push_back(vertices[vert1Idx]);\n\t\t\ttriangles.push_back(vertices[vert2Idx]);\n\t\t\ttriangles.push_back(vertices[vert3Idx]);\n\n\t\t\t// triangle normal\n\t\t\ttriag_normals.push_back(*iterNorms);\n\t\t\t//triag_normals.push_back(*iterNorms);\n\t\t\t//triag_normals.push_back(*iterNorms);\n\n\t\t\t// triangle vertex uvs\n\t\t\tif(puv1 && puv2 && puv3)\n\t\t\t{\n\t\t\t\tvert_uvs.push_back(*puv1);\n\t\t\t\tvert_uvs.push_back(*puv2);\n\t\t\t\tvert_uvs.push_back(*puv3);\n\t\t\t}\n\n\n\t\t\t// next vertex\n\t\t\tvert2Idx = vert3Idx;\n\t\t\tpuv2 = puv3;\n\t\t}\n\n\n\t\tstd::advance(iterFaces, 1);\n\t\tif(iterNorms != normals.end()) std::advance(iterNorms, 1);\n\t\tif(iterUVs != uvs.end()) std::advance(iterUVs, 1);\n\t}\n\n\treturn std::make_tuple(triangles, triag_normals, vert_uvs);\n}\n\n\n/**\n * subdivides triangles\n * input: [triangle vertices, normals, uvs]\n * @returns [triangles, face normals, vertex uvs]\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont, t_cont>\nsubdivide_triangles(const std::tuple, t_cont, t_cont>& tup)\nrequires is_vec\n{\n\tconst t_cont& vertices = std::get<0>(tup);\n\tconst t_cont& normals = std::get<1>(tup);\n\tconst t_cont& uvs = std::get<2>(tup);\n\n\tt_cont vertices_new;\n\tt_cont normals_new;\n\tt_cont uvs_new;\n\n\n\t// iterate over triplets forming triangles\n\tauto itervert = vertices.begin();\n\tauto iternorm = normals.begin();\n\tauto iteruv = uvs.begin();\n\n\twhile(itervert != vertices.end())\n\t{\n\t\tconst t_vec& vec1 = *itervert;\n\t\tstd::advance(itervert, 1); if(itervert == vertices.end()) break;\n\t\tconst t_vec& vec2 = *itervert;\n\t\tstd::advance(itervert, 1); if(itervert == vertices.end()) break;\n\t\tconst t_vec& vec3 = *itervert;\n\t\tstd::advance(itervert, 1);\n\n\t\tconst t_vec vec12mid = avg({ vec1, vec2 });\n\t\tconst t_vec vec23mid = avg({ vec2, vec3 });\n\t\tconst t_vec vec31mid = avg({ vec3, vec1 });\n\n\t\t// triangle 1\n\t\tvertices_new.push_back(vec1);\n\t\tvertices_new.push_back(vec12mid);\n\t\tvertices_new.push_back(vec31mid);\n\n\t\t// triangle 2\n\t\tvertices_new.push_back(vec12mid);\n\t\tvertices_new.push_back(vec2);\n\t\tvertices_new.push_back(vec23mid);\n\n\t\t// triangle 3\n\t\tvertices_new.push_back(vec31mid);\n\t\tvertices_new.push_back(vec23mid);\n\t\tvertices_new.push_back(vec3);\n\n\t\t// triangle 4\n\t\tvertices_new.push_back(vec12mid);\n\t\tvertices_new.push_back(vec23mid);\n\t\tvertices_new.push_back(vec31mid);\n\n\n\t\t// duplicate normals for the four sub-triangles\n\t\tif(iternorm != normals.end())\n\t\t{\n\t\t\tnormals_new.push_back(*iternorm);\n\t\t\tnormals_new.push_back(*iternorm);\n\t\t\tnormals_new.push_back(*iternorm);\n\t\t\tnormals_new.push_back(*iternorm);\n\n\t\t\tstd::advance(iternorm, 1);\n\t\t}\n\n\n\t\t// uv coords\n\t\tif(iteruv != uvs.end())\n\t\t{\n\t\t\t// uv coords at vertices\n\t\t\tconst t_vec& uv1 = *iteruv;\n\t\t\tstd::advance(iteruv, 1); if(iteruv == uvs.end()) break;\n\t\t\tconst t_vec& uv2 = *iteruv;\n\t\t\tstd::advance(iteruv, 1); if(iteruv == uvs.end()) break;\n\t\t\tconst t_vec& uv3 = *iteruv;\n\t\t\tstd::advance(iteruv, 1);\n\n\t\t\tconst t_vec uv12mid = avg({ uv1, uv2 });\n\t\t\tconst t_vec uv23mid = avg({ uv2, uv3 });\n\t\t\tconst t_vec uv31mid = avg({ uv3, uv1 });\n\n\t\t\t// uvs of triangle 1\n\t\t\tuvs_new.push_back(uv1);\n\t\t\tuvs_new.push_back(uv12mid);\n\t\t\tuvs_new.push_back(uv31mid);\n\n\t\t\t// uvs of triangle 2\n\t\t\tuvs_new.push_back(uv12mid);\n\t\t\tuvs_new.push_back(uv2);\n\t\t\tuvs_new.push_back(uv23mid);\n\n\t\t\t// uvs of triangle 3\n\t\t\tuvs_new.push_back(uv31mid);\n\t\t\tuvs_new.push_back(uv23mid);\n\t\t\tuvs_new.push_back(uv3);\n\n\t\t\t// uvs of triangle 4\n\t\t\tuvs_new.push_back(uv12mid);\n\t\t\tuvs_new.push_back(uv23mid);\n\t\t\tuvs_new.push_back(uv31mid);\n\t\t}\n\t}\n\n\treturn std::make_tuple(vertices_new, normals_new, uvs_new);\n}\n\n\n/**\n * subdivides triangles (with specified number of iterations)\n * input: [triangle vertices, normals, uvs]\n * @returns [triangles, face normals, vertex uvs]\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont, t_cont>\nsubdivide_triangles(const std::tuple, t_cont, t_cont>& tup, std::size_t iters)\nrequires is_vec\n{\n\tauto tupDiv = tup;\n\tfor(std::size_t i=0; i(tupDiv);\n\treturn tupDiv;\n}\n\n\n/**\n * create the faces of a sphere\n * input: [triangle vertices, normals, uvs] (like subdivide_triangles)\n * @returns [triangles, face normals, vertex uvs]\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont, t_cont>\nspherify(const std::tuple, t_cont, t_cont>& tup,\n\ttypename t_vec::value_type rad = 1)\nrequires is_vec\n{\n\tconst t_cont& vertices = std::get<0>(tup);\n\t//const t_cont& normals = std::get<1>(tup);\n\tconst t_cont& uvs = std::get<2>(tup);\n\n\tt_cont vertices_new;\n\tt_cont normals_new;\n\tvertices_new.reserve(vertices.size());\n\tnormals_new.reserve(vertices.size());\n\n\n\t// vertices\n\tfor(t_vec vec : vertices)\n\t{\n\t\tvec /= norm(vec);\n\t\tvec *= rad;\n\t\tvertices_new.emplace_back(std::move(vec));\n\t}\n\n\n\t// face normals\n\tauto itervert = vertices.begin();\n\t// iterate over triplets forming triangles\n\twhile(itervert != vertices.end())\n\t{\n\t\tconst t_vec& vec1 = *itervert;\n\t\tstd::advance(itervert, 1); if(itervert == vertices.end()) break;\n\t\tconst t_vec& vec2 = *itervert;\n\t\tstd::advance(itervert, 1); if(itervert == vertices.end()) break;\n\t\tconst t_vec& vec3 = *itervert;\n\t\tstd::advance(itervert, 1);\n\n\t\tt_vec vecmid = avg({ vec1, vec2, vec3 });\n\t\tvecmid /= norm(vecmid);\n\t\tnormals_new.emplace_back(std::move(vecmid));\n\t}\n\n\treturn std::make_tuple(vertices_new, normals_new, uvs);\n}\n\n// ----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n// 3-dim solids\n// ----------------------------------------------------------------------------\n\n/**\n * transforms vertices and normals using a matrix\n */\ntemplate class t_cont = std::vector>\nvoid transform_obj(t_cont& verts, t_cont& norms, const t_mat& mat, bool is_3dhom=false)\nrequires is_vec && is_mat\n{\n\tusing size_t = decltype(mat.size1());\n\n\t// make sure a 3-vector and a 4-matrix are handled correctly in homogeneous coordinates\n\tif(is_3dhom && mat.size1()==4)\n\t{\n\t\tt_mat mat3 = mat;\n\t\tfor(size_t i=0; i<3; ++i)\n\t\t{\n\t\t\tmat3(3,i) = 0;\n\t\t\tmat3(i,3) = 0;\n\t\t}\n\t\tmat3(3,3) = 1;\n\n\t\tfor(auto& vert : verts)\n\t\t{\n\t\t\tvert = mat3 * vert;\n\n\t\t\t// add translation and normalise\n\t\t\tfor(size_t i=0; i<3; ++i)\n\t\t\t{\n\t\t\t\tvert[i] += mat(i,3);\n\t\t\t\tvert[i] /= mat(3,3);\n\t\t\t}\n\t\t}\n\n\t\tfor(auto& norm : norms)\n\t\t\tnorm = mat3 * norm;\n\t}\n\n\t// standard case: just multiply\n\telse\n\t{\n\t\tfor(auto& vert : verts)\n\t\t\tvert = mat * vert;\n\n\t\tfor(auto& norm : norms)\n\t\t\tnorm = mat * norm;\n\t}\n}\n\n\n/**\n * create a plane\n * @returns [vertices, face vertex indices, face normals, face uvs]\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont>, t_cont, t_cont>>\ncreate_plane(const t_vec& norm, typename t_vec::value_type lx=1, typename t_vec::value_type ly=1)\nrequires is_vec\n{\n\tt_vec norm_old = create({ 0, 0, -1 });\n\tt_vec rot_vec = create({ 1, 0, 0 });\n\tt_mat rot = rotation(norm_old, norm, rot_vec);\n\n\tt_cont vertices =\n\t{\n\t\tcreate({ -lx, -ly, 0. }),\t// vertex 0\n\t\tcreate({ -lx, +ly, 0. }),\t// vertex 1\n\t\tcreate({ +lx, +ly, 0. }),\t// vertex 2\n\t\tcreate({ +lx, -ly, 0. }),\t// vertex 3\n\t};\n\n\t// rotate according to given normal\n\tfor(t_vec& vec : vertices)\n\t\tvec = rot * vec;\n\n\tt_cont> faces = { { 0, 1, 2, 3 } };\n\tt_cont normals = { norm };\n\n\tt_cont> uvs =\n\t{{\n\t\tcreate({0, 0}),\n\t\tcreate({0, 1}),\n\t\tcreate({1, 1}),\n\t\tcreate({1, 0}),\n\t}};\n\n\treturn std::make_tuple(vertices, faces, normals, uvs);\n}\n\n\n/**\n * create a disk\n * @returns [vertices, face vertex indices, face normals, face uvs]\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont>, t_cont, t_cont>>\ncreate_disk(typename t_vec::value_type r = 1, std::size_t num_points=32)\nrequires is_vec\n{\n\tusing t_real = typename t_vec::value_type;\n\n\t// vertices\n\tt_cont vertices;\n\tvertices.reserve(num_points);\n\n\t// inner vertex\n\tfor(std::size_t pt=0; pt;\n\t\tconst t_real c = std::cos(phi);\n\t\tconst t_real s = std::sin(phi);\n\n\t\t// outer vertices\n\t\tt_vec vert = create({ r*c, r*s, 0 });\n\t\tvertices.emplace_back(std::move(vert));\n\t}\n\n\t// faces, normals & uvs\n\tt_cont> faces;\n\tt_cont normals;\n\tt_cont> uvs;\t// TODO\n\n\tt_cont face(num_points);\n\tstd::iota(face.begin(), face.end(), 0);\n\tfaces.push_back(face);\n\tnormals.push_back(create({0,0,1}));\n\n\treturn std::make_tuple(vertices, faces, normals, uvs);\n}\n\n\n/**\n * create a cone\n * @returns [vertices, face vertex indices, face normals, face uvs]\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont>, t_cont, t_cont>>\ncreate_cone(typename t_vec::value_type r = 1, typename t_vec::value_type h = 1,\n\tbool bWithCap = true, std::size_t num_points = 32)\nrequires is_vec\n{\n\tusing t_real = typename t_vec::value_type;\n\n\t// vertices\n\tt_cont vertices;\n\n\t// inner vertex\n\tvertices.push_back(create({ 0, 0, h }));\n\n\tfor(std::size_t pt=0; pt;\n\t\tconst t_real c = std::cos(phi);\n\t\tconst t_real s = std::sin(phi);\n\n\t\t// outer vertices\n\t\tt_vec vert = create({ r*c, r*s, 0 });\n\t\tvertices.emplace_back(std::move(vert));\n\t}\n\n\t// faces, normals & uvs\n\tt_cont> faces;\n\tt_cont normals;\n\tt_cont> uvs;\t// TODO\n\n\tfor(std::size_t face=0; face({vertices[idx2]-vertices[idx0], vertices[idx1]-vertices[idx0]});\n\t\t\tn /= norm(n);\n\n\t\t\tnormals.push_back(n);\n\t}\n\n\n\tif(bWithCap)\n\t{\n\t\tconst auto [disk_vertices, disk_faces, disk_normals, disk_uvs] = create_disk(r, num_points);\n\n\t\t// vertex indices have to be adapted for merging\n\t\tconst std::size_t vert_start_idx = vertices.size();\n\t\tvertices.insert(vertices.end(), disk_vertices.begin(), disk_vertices.end());\n\n\t\tauto disk_faces_bottom = disk_faces;\n\t\tfor(auto& disk_face : disk_faces_bottom)\n\t\t{\n\t\t\tfor(auto& disk_face_idx : disk_face)\n\t\t\t\tdisk_face_idx += vert_start_idx;\n\t\t\tstd::reverse(disk_face.begin(), disk_face.end());\n\t\t}\n\t\tfaces.insert(faces.end(), disk_faces_bottom.begin(), disk_faces_bottom.end());\n\n\t\tfor(const auto& normal : disk_normals)\n\t\t\tnormals.push_back(-normal);\n\n\t\tuvs.insert(uvs.end(), disk_uvs.begin(), disk_uvs.end());\n\t}\n\n\treturn std::make_tuple(vertices, faces, normals, uvs);\n}\n\n\n/**\n * create a cylinder\n * cyltype: 0 (no caps), 1 (with caps), 2 (arrow)\n * @returns [vertices, face vertex indices, face normals, face uvs]\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont>, t_cont, t_cont>>\ncreate_cylinder(typename t_vec::value_type r = 1, typename t_vec::value_type h = 1,\n\tint cyltype = 0, std::size_t num_points = 32,\n\ttypename t_vec::value_type arrow_r = 1.5, typename t_vec::value_type arrow_h = 0.5)\nrequires is_vec\n{\n\tusing t_real = typename t_vec::value_type;\n\n\t// vertices\n\tt_cont vertices;\n\tt_cont vertices_u;\n\n\tfor(std::size_t pt=0; pt;\n\t\tconst t_real c = std::cos(phi);\n\t\tconst t_real s = std::sin(phi);\n\n\t\tt_vec top = create({ r*c, r*s, h*t_real(0.5) });\n\t\tt_vec bottom = create({ r*c, r*s, -h*t_real(0.5) });\n\n\t\tvertices.emplace_back(std::move(top));\n\t\tvertices.emplace_back(std::move(bottom));\n\n\t\tvertices_u.push_back(u);\n\t}\n\n\t// faces, normals & uvs\n\tt_cont> faces;\n\tt_cont normals;\n\tt_cont> uvs;\n\n\tfor(std::size_t face=0; face= num_points-1 ? 1 : face*2 + 3);\t// bottom 2\n\t\tstd::size_t idx3 = (face >= num_points-1 ? 0 : face*2 + 2);\t// top 2\n\n\t\tt_vec n = cross({vertices[idx1]-vertices[idx0], vertices[idx3]-vertices[idx0]});\n\t\tn /= norm(n);\n\n\t\tfaces.push_back({ idx0, idx1, idx2, idx3 });\n\t\tnormals.emplace_back(std::move(n));\n\n\n\t\tt_real u1 = vertices_u[idx0];\n\t\tt_real u2 = (face >= num_points-1 ? 1 : vertices_u[idx3]);\n\t\tuvs.push_back({ create({u1,1}), create({u1,0}),\n\t\t\tcreate({u2,0}), create({u2,1}) });\n\t}\n\n\n\tif(cyltype > 0)\n\t{\n\t\tconst auto [disk_vertices, disk_faces, disk_normals, disk_uvs] = create_disk(r, num_points);\n\n\t\t// bottom lid\n\t\t// vertex indices have to be adapted for merging\n\t\tstd::size_t vert_start_idx = vertices.size();\n\t\tconst t_vec top = create({ 0, 0, h*t_real(0.5) });\n\n\t\tfor(const auto& disk_vert : disk_vertices)\n\t\t\tvertices.push_back(disk_vert - top);\n\n\t\tauto disk_faces_bottom = disk_faces;\n\t\tfor(auto& disk_face : disk_faces_bottom)\n\t\t{\n\t\t\tfor(auto& disk_face_idx : disk_face)\n\t\t\t\tdisk_face_idx += vert_start_idx;\n\t\t\tstd::reverse(disk_face.begin(), disk_face.end());\n\t\t}\n\t\tfaces.insert(faces.end(), disk_faces_bottom.begin(), disk_faces_bottom.end());\n\n\t\tfor(const auto& normal : disk_normals)\n\t\t\tnormals.push_back(-normal);\n\n\t\tuvs.insert(uvs.end(), disk_uvs.begin(), disk_uvs.end());\n\n\n\t\tvert_start_idx = vertices.size();\n\n\t\tif(cyltype == 1)\t// top lid\n\t\t{\n\t\t\tfor(const auto& disk_vert : disk_vertices)\n\t\t\t\tvertices.push_back(disk_vert + top);\n\n\t\t\tauto disk_faces_top = disk_faces;\n\t\t\tfor(auto& disk_face : disk_faces_top)\n\t\t\t\tfor(auto& disk_face_idx : disk_face)\n\t\t\t\t\tdisk_face_idx += vert_start_idx;\n\t\t\tfaces.insert(faces.end(), disk_faces_top.begin(), disk_faces_top.end());\n\n\t\t\tfor(const auto& normal : disk_normals)\n\t\t\t\tnormals.push_back(normal);\n\n\t\t\tuvs.insert(uvs.end(), disk_uvs.begin(), disk_uvs.end());\n\t\t}\n\t\telse if(cyltype == 2)\t// arrow top\n\t\t{\n\t\t\t// no need to cap the arrow if the radii are equal\n\t\t\tbool bConeCap = !equals(r, arrow_r);\n\n\t\t\tconst auto [cone_vertices, cone_faces, cone_normals, cone_uvs] =\n\t\t\t\tcreate_cone(arrow_r, arrow_h, bConeCap, num_points);\n\n\t\t\tfor(const auto& cone_vert : cone_vertices)\n\t\t\t\tvertices.push_back(cone_vert + top);\n\n\t\t\tauto cone_faces_top = cone_faces;\n\t\t\tfor(auto& cone_face : cone_faces_top)\n\t\t\t\tfor(auto& cone_face_idx : cone_face)\n\t\t\t\t\tcone_face_idx += vert_start_idx;\n\t\t\tfaces.insert(faces.end(), cone_faces_top.begin(), cone_faces_top.end());\n\n\t\t\tfor(const auto& normal : cone_normals)\n\t\t\t\tnormals.push_back(normal);\n\n\t\t\tuvs.insert(uvs.end(), cone_uvs.begin(), cone_uvs.end());\n\t\t}\n\t}\n\n\treturn std::make_tuple(vertices, faces, normals, uvs);\n}\n\n\n/**\n * create the faces of a cuboid\n * @returns [vertices, face vertex indices, face normals, face uvs]\n * @see https://en.wikipedia.org/wiki/Platonic_solid\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont>, t_cont, t_cont>>\ncreate_cuboid(typename t_vec::value_type lx=1, typename t_vec::value_type ly=1, typename t_vec::value_type lz=1)\nrequires is_vec\n{\n\tt_cont vertices =\n\t{\n\t\tcreate({ +lx, -ly, -lz }),\t// vertex 0\n\t\tcreate({ -lx, -ly, -lz }),\t// vertex 1\n\t\tcreate({ -lx, +ly, -lz }),\t// vertex 2\n\t\tcreate({ +lx, +ly, -lz }),\t// vertex 3\n\n\t\tcreate({ -lx, -ly, +lz }),\t// vertex 4\n\t\tcreate({ +lx, -ly, +lz }),\t// vertex 5\n\t\tcreate({ +lx, +ly, +lz }),\t// vertex 6\n\t\tcreate({ -lx, +ly, +lz }),\t// vertex 7\n\t};\n\n\tt_cont> faces =\n\t{\n\t\t{ 0, 1, 2, 3 },\t// -z face\n\t\t{ 4, 5, 6, 7 },\t// +z face\n\t\t{ 1, 0, 5, 4 }, // -y face\n\t\t{ 7, 6, 3, 2 },\t// +y face\n\t\t{ 1, 4, 7, 2 },\t// -x face\n\t\t{ 5, 0, 3, 6 },\t// +x face\n\t};\n\n\tt_cont normals =\n\t{\n\t\tcreate({ 0, 0, -1 }),\t// -z face\n\t\tcreate({ 0, 0, +1 }),\t// +z face\n\t\tcreate({ 0, -1, 0 }),\t// -y face\n\t\tcreate({ 0, +1, 0 }),\t// +y face\n\t\tcreate({ -1, 0, 0 }),\t// -x face\n\t\tcreate({ +1, 0, 0 }),\t// +x face\n\t};\n\n\tt_cont> uvs =\n\t{\n\t\t{ create({0,0}), create({1,0}), create({1,1}), create({0,1}) },\t// -z face\n\t\t{ create({0,0}), create({1,0}), create({1,1}), create({0,1}) },\t// +z face\n\t\t{ create({0,0}), create({1,0}), create({1,1}), create({0,1}) },\t// -y face\n\t\t{ create({0,0}), create({1,0}), create({1,1}), create({0,1}) },\t// +y face\n\t\t{ create({0,0}), create({1,0}), create({1,1}), create({0,1}) },\t// -x face\n\t\t{ create({0,0}), create({1,0}), create({1,1}), create({0,1}) },\t// +x face\n\t};\n\n\treturn std::make_tuple(vertices, faces, normals, uvs);\n}\n\n\n/**\n * create the faces of a cube\n * @returns [vertices, face vertex indices, face normals, face uvs]\n * @see https://en.wikipedia.org/wiki/Platonic_solid\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont>, t_cont, t_cont>>\ncreate_cube(typename t_vec::value_type l = 1)\nrequires is_vec\n{\n\treturn create_cuboid(l, l, l);\n}\n\n\n/**\n * create the faces of a icosahedron\n * @returns [vertices, face vertex indices, face normals, face uvs]\n * @see https://en.wikipedia.org/wiki/Platonic_solid\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont>, t_cont, t_cont>>\ncreate_icosahedron(typename t_vec::value_type l = 1)\nrequires is_vec\n{\n\tusing T = typename t_vec::value_type;\n\tconst T g = golden;\n\n\tt_cont vertices =\n\t{\n\t\tcreate({ 0, -l, -g*l }), create({ 0, -l, +g*l }),\n\t\tcreate({ 0, +l, -g*l }), create({ 0, +l, +g*l }),\n\n\t\tcreate({ -g*l, 0, -l }), create({ -g*l, 0, +l }),\n\t\tcreate({ +g*l, 0, -l }), create({ +g*l, 0, +l }),\n\n\t\tcreate({ -l, -g*l, 0 }), create({ -l, +g*l, 0 }),\n\t\tcreate({ +l, -g*l, 0 }), create({ +l, +g*l, 0 }),\n\t};\n\n\tt_cont> faces =\n\t{\n\t\t{ 4, 2, 0 }, { 0, 6, 10 }, { 10, 7, 1 }, { 1, 3, 5 }, { 5, 9, 4 },\n\t\t{ 7, 10, 6 }, { 6, 0, 2 }, { 2, 4, 9 }, { 9, 5, 3 }, { 3, 1, 7 },\n\t\t{ 0, 10, 8 }, { 10, 1, 8 }, { 1, 5, 8 }, { 5, 4, 8 }, { 4, 0, 8 },\n\t\t{ 3, 7, 11 }, { 7, 6, 11 }, { 6, 2, 11 }, { 2, 9, 11 }, { 9, 3, 11 },\n\t};\n\n\n\tt_cont normals;\n\tnormals.reserve(faces.size());\n\n\tfor(const auto& face : faces)\n\t{\n\t\tauto iter = face.begin();\n\t\tconst t_vec& vec1 = *(vertices.begin() + *iter); std::advance(iter,1);\n\t\tconst t_vec& vec2 = *(vertices.begin() + *iter); std::advance(iter,1);\n\t\tconst t_vec& vec3 = *(vertices.begin() + *iter);\n\n\t\tconst t_vec vec12 = vec2 - vec1;\n\t\tconst t_vec vec13 = vec3 - vec1;\n\n\t\tt_vec n = cross({vec12, vec13});\n\t\tn /= norm(n);\n\t\tnormals.emplace_back(std::move(n));\n\t}\n\n\t// TODO\n\tt_cont> uvs =\n\t{\n\t};\n\n\treturn std::make_tuple(vertices, faces, normals, uvs);\n}\n\n\n/**\n * create the faces of a dodecahedron\n * @returns [vertices, face vertex indices, face normals, face uvs]\n * @see https://en.wikipedia.org/wiki/Platonic_solid\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont>, t_cont, t_cont>>\ncreate_dodecahedron(typename t_vec::value_type l = 1)\nrequires is_vec\n{\n\tusing T = typename t_vec::value_type;\n\tconst T g = golden;\n\n\tt_cont vertices =\n\t{\n\t\tcreate({ l, l, l }), create({ l, l, -l }),\n\t\tcreate({ l, -l, l }), create({ l, -l, -l }),\n\n\t\tcreate({ -l, l, l }), create({ -l, l, -l }),\n\t\tcreate({ -l, -l, l }), create({ -l, -l, -l }),\n\n\t\tcreate({ 0, T{l}/g, g }), create({ 0, T{l}/g, -g }),\n\t\tcreate({ 0, -T{l}/g, g }), create({ 0, -T{l}/g, -g }),\n\n\t\tcreate({ g, 0, T{l}/g }), create({ g, 0, -T{l}/g }),\n\t\tcreate({ -g, 0, T{l}/g }), create({ -g, 0, -T{l}/g }),\n\n\t\tcreate({ T{l}/g, g, 0 }), create({ T{l}/g, -g, 0 }),\n\t\tcreate({ -T{l}/g, g, 0 }), create({ -T{l}/g, -g, 0 }),\n\t};\n\n\tt_cont> faces =\n\t{\n\t\t{ 0, 16, 18, 4, 8 }, { 0, 8, 10, 2, 12 }, { 0, 12, 13, 1, 16 },\n\t\t{ 1, 9, 5, 18, 16 }, { 1, 13, 3, 11, 9 }, { 2, 17, 3, 13, 12 },\n\t\t{ 3, 17, 19, 7, 11 }, { 2, 10, 6, 19, 17 }, { 4, 14, 6, 10, 8 },\n\t\t{ 4, 18, 5, 15, 14 }, { 5, 9, 11, 7, 15 }, { 6, 14, 15, 7, 19 },\n\t};\n\n\n\tt_cont normals;\n\tnormals.reserve(faces.size());\n\n\tfor(const auto& face : faces)\n\t{\n\t\tauto iter = face.begin();\n\t\tconst t_vec& vec1 = *(vertices.begin() + *iter); std::advance(iter,1);\n\t\tconst t_vec& vec2 = *(vertices.begin() + *iter); std::advance(iter,1);\n\t\tconst t_vec& vec3 = *(vertices.begin() + *iter);\n\n\t\tconst t_vec vec12 = vec2 - vec1;\n\t\tconst t_vec vec13 = vec3 - vec1;\n\n\t\tt_vec n = cross({vec12, vec13});\n\t\tn /= norm(n);\n\t\tnormals.emplace_back(std::move(n));\n\t}\n\n\t// TODO\n\tt_cont> uvs =\n\t{\n\t};\n\n\treturn std::make_tuple(vertices, faces, normals, uvs);\n}\n\n\n/**\n * create the faces of a octahedron\n * @returns [vertices, face vertex indices, face normals, face uvs]\n * @see https://en.wikipedia.org/wiki/Platonic_solid\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont>, t_cont, t_cont>>\ncreate_octahedron(typename t_vec::value_type l = 1)\nrequires is_vec\n{\n\tusing T = typename t_vec::value_type;\n\n\tt_cont vertices =\n\t{\n\t\tcreate({ +l, 0, 0 }),\t// vertex 0\n\t\tcreate({ 0, +l, 0 }),\t// vertex 1\n\t\tcreate({ 0, 0, +l }),\t// vertex 2\n\n\t\tcreate({ -l, 0, 0 }),\t// vertex 3\n\t\tcreate({ 0, -l, 0 }),\t// vertex 4\n\t\tcreate({ 0, 0, -l }),\t// vertex 5\n\t};\n\n\tt_cont> faces =\n\t{\n\t\t{ 2, 0, 1 }, { 0, 5, 1 }, { 5, 3, 1 }, { 3, 2, 1 },\t// upper half\n\t\t{ 0, 2, 4 }, { 5, 0, 4 }, { 3, 5, 4 }, { 2, 3, 4 },\t// lower half\n\t};\n\n\n\tconst T len = std::sqrt(3);\n\n\tt_cont normals =\n\t{\n\t\tcreate({ +1/len, +1/len, +1/len }),\n\t\tcreate({ +1/len, +1/len, -1/len }),\n\t\tcreate({ -1/len, +1/len, -1/len }),\n\t\tcreate({ -1/len, +1/len, +1/len }),\n\n\t\tcreate({ +1/len, -1/len, +1/len }),\n\t\tcreate({ +1/len, -1/len, -1/len }),\n\t\tcreate({ -1/len, -1/len, -1/len }),\n\t\tcreate({ -1/len, -1/len, +1/len }),\n\t};\n\n\tt_cont> uvs =\n\t{\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\t};\n\n\treturn std::make_tuple(vertices, faces, normals, uvs);\n}\n\n\n/**\n * create the faces of a tetrahedron\n * @returns [vertices, face vertex indices, face normals, face uvs]\n * @see https://en.wikipedia.org/wiki/Platonic_solid\n */\ntemplate class t_cont = std::vector>\nstd::tuple, t_cont>, t_cont, t_cont>>\ncreate_tetrahedron(typename t_vec::value_type l = 1)\nrequires is_vec\n{\n\tusing T = typename t_vec::value_type;\n\n\tt_cont vertices =\n\t{\n\t\tcreate({ -l, -l, +l }),\t// vertex 0\n\t\tcreate({ +l, +l, +l }),\t// vertex 1\n\t\tcreate({ -l, +l, -l }),\t// vertex 2\n\t\tcreate({ +l, -l, -l }),\t// vertex 3\n\t};\n\n\tt_cont> faces =\n\t{\n\t\t{ 1, 2, 0 }, { 2, 1, 3 },\t// connected to upper edge\n\t\t{ 0, 3, 1 }, { 3, 0, 2 },\t// connected to lower edge\n\t};\n\n\n\tconst T len = std::sqrt(3);\n\n\tt_cont normals =\n\t{\n\t\tcreate({ -1/len, +1/len, +1/len }),\n\t\tcreate({ +1/len, +1/len, -1/len }),\n\t\tcreate({ +1/len, -1/len, +1/len }),\n\t\tcreate({ -1/len, -1/len, -1/len }),\n\t};\n\n\tt_cont> uvs =\n\t{\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\t\t{ create({0,0}), create({1,0}), create({0.5,1}) },\n\t};\n\n\treturn std::make_tuple(vertices, faces, normals, uvs);\n}\n\n\n/**\n * calculates the bounding sphere of a collection of vertices\n */\ntemplate class t_cont = std::vector>\nstd::tuple bounding_sphere(\n\tconst t_cont& verts)\nrequires is_vec\n{\n\tusing t_real = typename t_vec::value_type;\n\n\tt_real rad{};\n\tt_vec center = mean(verts);\n\n\tfor(const t_vec& vec : verts)\n\t{\n\t\tt_vec vecCur = vec-center;\n\n\t\tt_real dot = inner(vecCur, vecCur);\n\t\trad = std::max(rad, dot);\n\t}\n\n\trad = std::sqrt(rad);\n\treturn std::make_tuple(center, rad);\n}\n\n\n/**\n * calculates the bounding box of a collection of vertices\n */\ntemplate class t_cont = std::vector>\nstd::tuple bounding_box(\n\tconst t_cont& verts,\n\tconst t_vec* oldmin = nullptr, const t_vec* oldmax = nullptr)\nrequires is_vec\n{\n\tif(verts.size() == 0)\n\t\treturn std::make_tuple(t_vec{}, t_vec{});\n\n\tusing t_real = typename t_vec::value_type;\n\tconst std::size_t dim = verts[0].size();\n\tif(dim == 0)\n\t\treturn std::make_tuple(t_vec{}, t_vec{});\n\n\tt_vec min, max;\n\tif(oldmin && oldmax)\n\t{\n\t\tmin = *oldmin;\n\t\tmax = *oldmax;\n\t}\n\telse\n\t{\n\t\tmin = create(dim);\n\t\tfor(std::size_t i=0; i::max();\n\t\tmax = -min;\n\t}\n\n\tfor(const t_vec& vert : verts)\n\t{\n\t\tfor(std::size_t i=0; i class t_cont = std::vector>\nstd::tuple bounding_box(\n\tconst t_cont>& allverts, std::size_t dim = 3)\nrequires is_vec\n{\n\tusing t_real = typename t_vec::value_type;\n\n\tt_vec min, max;\n\tmin = create(dim);\n\tfor(std::size_t i=0; i::max();\n\tmax = -min;\n\n\tfor(const t_cont& verts : allverts)\n\t\tstd::tie(min, max) = bounding_box(verts, &min, &max);\n\n\treturn std::make_tuple(min, max);\n}\n\n\n/**\n * calculates the bounding box of a sphere\n */\ntemplate requires is_vec\nstd::tuple sphere_bounding_box(const t_vec& pos, t_real rad)\n{\n\tconst std::size_t dim = pos.size();\n\tif(dim == 0)\n\t\treturn std::make_tuple(t_vec{}, t_vec{});\n\n\tt_vec min = create(dim);\n\tt_vec max = create(dim);\n\n\tfor(std::size_t i=0; i class t_cont = std::vector,\n\tclass t_real = typename t_vec::value_type>\nstd::tuple sphere_bounding_box(\n\tconst t_cont>& spheres, std::size_t dim = 3)\nrequires is_vec\n{\n\tt_vec min = create(dim);\n\tfor(std::size_t i=0; i::max();\n\tt_vec max = -min;\n\n\tfor(const auto& sphere : spheres)\n\t{\n\t\tauto [spheremin, spheremax] = sphere_bounding_box(\n\t\t\tstd::get<0>(sphere), std::get<1>(sphere));\n\n\t\tfor(std::size_t i=0; i requires is_vec\nbool in_bounding_box(\n\tconst t_vec& pt, const std::tuple& bb)\n{\n\tconst std::size_t dim = pt.size();\n\n\tconst t_vec& min = std::get<0>(bb);\n\tconst t_vec& max = std::get<1>(bb);\n\n\tfor(std::size_t i=0; i max[i])\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\n/**\n * checks for bounding box intersection\n * @see https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_collision_detection\n */\ntemplate requires is_vec\nbool collide_bounding_boxes(\n\tconst std::tuple& bb1,\n\tconst std::tuple& bb2)\n{\n\t// invalid bounding boxes?\n\tif(std::get<0>(bb1).size()==0 || std::get<1>(bb1).size()==0 ||\n\t\tstd::get<0>(bb2).size()==0 || std::get<1>(bb2).size()==0)\n\t\treturn false;\n\n\tconst std::size_t dim = std::min(std::get<0>(bb1).size(), std::get<0>(bb2).size());\n\tfor(std::size_t i=0; i(bb1)[i] > std::get<1>(bb2)[i])\n\t\t\treturn false;\n\t\tif(std::get<0>(bb2)[i] > std::get<1>(bb1)[i])\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n// ----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n// 3-dim algos in homogeneous coordinates\n// ----------------------------------------------------------------------------\n\n/**\n * project a homogeneous vector to screen coordinates\n * @returns [vecPersp, vecScreen]\n * @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluProject.xml\n */\ntemplate\nstd::tuple hom_to_screen_coords(const t_vec& vec4,\n\tconst t_mat& matModelView, const t_mat& matProj, const t_mat& matViewport,\n\tbool bFlipY = false, bool bFlipX = false)\nrequires is_vec && is_mat\n{\n\t// perspective trafo and divide\n\tt_vec vecPersp = matProj * matModelView * vec4;\n\tvecPersp /= vecPersp[3];\n\n\t// viewport trafo\n\tt_vec vec = matViewport * vecPersp;\n\n\t// flip y coordinate\n\tif(bFlipY) vec[1] = matViewport(1,1)*2 - vec[1];\n\t// flip x coordinate\n\tif(bFlipX) vec[0] = matViewport(0,0)*2 - vec[0];\n\n\treturn std::make_tuple(vecPersp, vec);\n}\n\n\n/**\n * calculate world coordinates from screen coordinates\n * (vary zPlane to get the points of the z-line at constant (x,y))\n * @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluUnProject.xml\n */\ntemplate\nt_vec hom_from_screen_coords(\n\ttypename t_vec::value_type xScreen, typename t_vec::value_type yScreen, typename t_vec::value_type zPlane,\n\tconst t_mat& matModelView_inv, const t_mat& matProj_inv, const t_mat& matViewport_inv,\n\tconst t_mat* pmatViewport = nullptr, bool bFlipY = false, bool bFlipX = false)\nrequires is_vec && is_mat\n{\n\tt_vec vecScreen = create({xScreen, yScreen, zPlane, 1.});\n\n\t// flip y coordinate\n\tif(pmatViewport && bFlipY) vecScreen[1] = (*pmatViewport)(1,1)*2 - vecScreen[1];\n\t// flip x coordinate\n\tif(pmatViewport && bFlipX) vecScreen[0] = (*pmatViewport)(0,0)*2 - vecScreen[0];\n\n\tt_vec vecWorld = matModelView_inv * matProj_inv * matViewport_inv * vecScreen;\n\n\tvecWorld /= vecWorld[3];\n\treturn vecWorld;\n}\n\n\n/**\n * calculate line from screen coordinates\n * @returns [pos, dir]\n * @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluUnProject.xml\n */\ntemplate\nstd::tuple hom_line_from_screen_coords(\n\ttypename t_vec::value_type xScreen, typename t_vec::value_type yScreen,\n\ttypename t_vec::value_type z1, typename t_vec::value_type z2,\n\tconst t_mat& matModelView_inv, const t_mat& matProj_inv, const t_mat& matViewport_inv,\n\tconst t_mat* pmatViewport = nullptr, bool bFlipY = false, bool bFlipX = false)\nrequires is_vec && is_mat\n{\n\tconst t_vec lineOrg = hom_from_screen_coords(xScreen, yScreen, z1, matModelView_inv, matProj_inv,\n\t\tmatViewport_inv, pmatViewport, bFlipY, bFlipX);\n\tconst t_vec linePos2 = hom_from_screen_coords(xScreen, yScreen, z2, matModelView_inv, matProj_inv,\n\t\tmatViewport_inv, pmatViewport, bFlipY, bFlipX);\n\n\tt_vec lineDir = linePos2 - lineOrg;\n\tlineDir /= norm(lineDir);\n\n\treturn std::make_tuple(lineOrg, lineDir);\n}\n\n\n/**\n * perspective matrix (homogeneous 4x4)\n * @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluPerspective.xml\n */\ntemplate\nt_mat hom_perspective(\n\tt_scalar n = 0.01, t_scalar f = 100.,\n\tt_scalar fov = 0.5*pi, t_scalar ratio = 3./4.,\n\tbool bLHS = true, bool bZ01 = false)\nrequires is_mat\n{\n\tconst t_scalar c = 1./std::tan(0.5 * fov);\n\tconst t_scalar n0 = bZ01 ? t_scalar{0} : n;\n\tconst t_scalar sc = bZ01 ? t_scalar{1} : t_scalar{2};\n\tconst t_scalar zs = bLHS ? t_scalar{-1} : t_scalar{1};\n\tconst t_scalar range_nf = std::abs(f-n);\n\n\t// ( x*c*r ) ( -x*c*r/z )\n\t// ( y*c ) ( -y*c/z )\n\t// P * x = ( z*(n0+f)/(n-f) + w*sc*n*f/(n-f) ) => ( -(n0+f)/(n-f) - w/z*sc*n*f/(n-f) )\n\t// ( -z ) ( 1 )\n\treturn create({\n\t\tc*ratio, 0., 0., 0.,\n\t\t0, c, 0., 0.,\n\t\t0., 0., zs*(n0+f)/range_nf, -sc*n*f/range_nf,\n\t\t0., 0., zs, 0.\n\t});\n}\n\n\n/**\n * orthographic projection matrix (homogeneous 4x4)\n * @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glOrtho.xml\n * @see https://en.wikipedia.org/wiki/Orthographic_projection\n */\ntemplate\nt_mat hom_ortho_sym(\n\tt_scalar n = 0.01, t_scalar f = 100.,\n\tt_scalar range_lr = 2., t_scalar range_bt = 2.,\n\tbool bLHS = true, bool bMap05 = false)\nrequires is_mat\n{\n\t// map ranges into [-0.5, 0.5] or [-1, 1] else\n\tconst t_scalar sc = bMap05 ? t_scalar{1} : t_scalar{2};\n\tconst t_scalar zs = bLHS ? t_scalar{-1} : t_scalar{1};\n\n\tconst t_scalar range_nf = std::abs(f) + std::abs(n);\n\n\t// centring\n\tconst t_scalar tr_z = sc*t_scalar{0.5} * (n+f) / range_nf;\n\n\t// ( sc_x*x )\n\t// ( sc_y*y )\n\t// P * x = ( sc_z*z - tr_z )\n\t// ( 1 )\n\treturn create({\n\t\tsc/range_lr, 0., 0., 0.,\n\t\t0., sc/range_bt, 0., 0.,\n\t\t0., 0., zs*sc/range_nf, zs*tr_z,\n\t\t0., 0., 0., 1.\n\t});\n}\n\n\n/**\n * orthographic projection matrix (homogeneous 4x4)\n * @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glOrtho.xml\n * @see https://en.wikipedia.org/wiki/Orthographic_projection\n */\ntemplate\nt_mat hom_ortho(\n\tt_scalar n = 0.01, t_scalar f = 100.,\n\tt_scalar l = -1., t_scalar r = 1.,\n\tt_scalar b = -1., t_scalar t = 1.,\n\tbool bLHS = true, bool bMap05 = false)\nrequires is_mat\n{\n\t// map ranges into [-0.5, 0.5] or [-1, 1] else\n\tconst t_scalar sc = bMap05 ? t_scalar{1} : t_scalar{2};\n\tconst t_scalar zs = bLHS ? t_scalar{-1} : t_scalar{1};\n\n\tconst t_scalar range_lr = r - l;\n\tconst t_scalar range_bt = t - b;\n\tconst t_scalar range_nf = f - n;\n\n\t// centring\n\tconst t_scalar tr_x = sc*t_scalar{0.5} * (l+r) / range_lr;\n\tconst t_scalar tr_y = sc*t_scalar{0.5} * (b+t) / range_bt;\n\tconst t_scalar tr_z = sc*t_scalar{0.5} * (n+f) / range_nf;\n\n\t// ( sc_x*x - tr_x )\n\t// ( sc_y*y - tr_y )\n\t// P * x = ( sc_z*z - tr_z )\n\t// ( 1 )\n\treturn create({\n\t\tsc/range_lr, 0., 0., -tr_x,\n\t\t0., sc/range_bt, 0., -tr_y,\n\t\t0., 0., zs*sc/range_nf, zs*tr_z,\n\t\t0., 0., 0., 1.\n\t});\n}\n\n\n/**\n * viewport matrix (homogeneous 4x4)\n * @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glViewport.xml\n */\ntemplate\nt_mat hom_viewport(t_scalar w, t_scalar h, t_scalar n = 0, t_scalar f = 1)\nrequires is_mat\n{\n\tt_scalar sc{0.5};\n\n\treturn create({\n\t\tsc*w, 0., 0., sc*w,\n\t\t0, sc*h, 0., sc*h,\n\t\t0., 0., sc*(f-n), sc*(f+n),\n\t\t0., 0., 0., 1.\n\t});\n}\n\n\n/**\n * translation matrix in homogeneous coordinates\n */\ntemplate\nt_mat hom_translation(t_real x, t_real y, t_real z)\nrequires is_mat\n{\n\treturn create({\n\t\t1., 0., 0., x,\n\t\t0., 1., 0., y,\n\t\t0., 0., 1., z,\n\t\t0., 0., 0., 1.\n\t});\n}\n\n\n/**\n * scaling matrix in homogeneous coordinates\n */\ntemplate\nt_mat hom_scaling(t_real x, t_real y, t_real z)\nrequires is_mat\n{\n\treturn create({\n\t\tx, 0., 0., 0.,\n\t\t0., y, 0., 0.,\n\t\t0., 0., z, 0.,\n\t\t0., 0., 0., 1.\n\t});\n}\n\n\n/**\n * \"look at\" matrix in homogeneous coordinates\n * @see (Sellers 2014), pp. 78-79\n * @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluLookAt.xml\n */\ntemplate\nt_mat hom_lookat(const t_vec& pos, const t_vec& target, const t_vec& _up)\nrequires is_vec && is_mat\n{\n\tusing t_real = typename t_mat::value_type;\n\n\t// create orthonormal system\n\tt_vec dir = -(target - pos);\n\tdir = dir / norm(dir);\n\n\tt_vec side = cross({_up, dir});\n\tside = side / norm(side);\n\n\tt_vec up = cross({dir, side});\n\t//up = up / norm(up);\n\n\t// inverted/transposed rotation matrix\n\tt_mat rot_inv = unit(4);\n\tset_row(rot_inv, side, 0);\n\tset_row(rot_inv, up, 1);\n\tset_row(rot_inv, dir, 2);\n\n\t// inverted translation matrix\n\tt_mat trans_inv = hom_translation(\n\t\t-pos[0], -pos[1], -pos[2]);\n\n\treturn rot_inv * trans_inv;\n}\n\n\n/**\n * shear matrix\n * @see https://en.wikipedia.org/wiki/Shear_matrix\n */\ntemplate\nt_mat shear(std::size_t ROWS, std::size_t COLS, std::size_t i, std::size_t j, t_real s)\nrequires is_mat\n{\n\tt_mat mat = unit(ROWS, COLS);\n\tmat(i,j) = s;\n\treturn mat;\n}\n\n\n/**\n * rotation matrix in homogeneous coordinates\n */\ntemplate\nt_mat hom_rotation(const t_vec& vec1, const t_vec& vec2,\n\tconst t_vec& vec_normal = create({0, 0, 1}))\nrequires is_vec && is_mat\n{\n\tt_mat rot = rotation(vec1, vec2, vec_normal);\n\n\treturn create({\n\t\trot(0,0), rot(0,1), rot(0,2), 0.,\n\t\trot(1,0), rot(1,1), rot(1,2), 0.,\n\t\trot(2,0), rot(2,1), rot(2,2), 0.,\n\t\t0., 0., 0., 1.\n\t});\n}\n\n\n/**\n * rotation matrix in homogeneous coordinates\n */\ntemplate\nt_mat hom_rotation(const t_vec& axis, typename t_vec::value_type angle, bool bIsNormalised=1)\nrequires is_vec && is_mat\n{\n\tt_mat rot = rotation(axis, angle, bIsNormalised);\n\n\treturn create({\n\t\trot(0,0), rot(0,1), rot(0,2), 0.,\n\t\trot(1,0), rot(1,1), rot(1,2), 0.,\n\t\trot(2,0), rot(2,1), rot(2,2), 0.,\n\t\t0., 0., 0., 1.\n\t});\n}\n\n// ----------------------------------------------------------------------------\n\n\n\n/**\n * arrow matrix\n */\ntemplate\nt_mat get_arrow_matrix(\n\tconst t_vec& vecTo,\n\tt_real postscale = 1, const t_vec& vecPostTrans = create({0,0,0.5}),\n\tconst t_vec& vecFrom = create({0,0,1}),\n\tt_real prescale = 1, const t_vec& vecPreTrans = create({0,0,0}),\n\tconst t_vec& vecNormal = create({0,0,1}))\nrequires is_vec && is_mat\n{\n\tt_mat mat = unit(4);\n\n\tmat *= hom_translation(vecPreTrans[0], vecPreTrans[1], vecPreTrans[2]);\n\tmat *= hom_scaling(prescale, prescale, prescale);\n\n\tmat *= hom_rotation(vecFrom, vecTo, vecNormal);\n\n\tmat *= hom_scaling(postscale, postscale, postscale);\n\tmat *= hom_translation(vecPostTrans[0], vecPostTrans[1], vecPostTrans[2]);\n\n\treturn mat;\n}\n\n\n\n// ----------------------------------------------------------------------------\n// complex algos\n// ----------------------------------------------------------------------------\n\n/**\n * split a complex vector into two vectors with the real and imag parts\n */\ntemplate\nstd::tuple split_cplx(const t_vec_cplx& vec)\nrequires is_complex && is_vec && is_vec\n{\n\tusing t_real = typename t_vec_real::value_type;\n\n\tt_vec_real vecRe = zero(vec.size());\n\tt_vec_real vecIm = zero(vec.size());\n\n\tauto iter = vec.begin();\n\tauto iterRe = vecRe.begin();\n\tauto iterIm = vecIm.begin();\n\n\tfor(; iter!=vec.end(); )\n\t{\n\t\t*iterRe = t_real{iter->real()};\n\t\t*iterIm = t_real{iter->imag()};\n\n\t\tstd::advance(iter, 1);\n\t\tstd::advance(iterRe, 1);\n\t\tstd::advance(iterIm, 1);\n\t}\n\n\treturn std::make_tuple(vecRe, vecIm);\n}\n\n\n/**\n * split a complex matrix into two matrices with the real and imag parts\n */\ntemplate\nstd::tuple split_cplx(const t_mat_cplx& mat)\nrequires is_complex && is_mat && is_mat\n{\n\tt_mat_real matRe = zero(mat.size1(), mat.size2());\n\tt_mat_real matIm = zero(mat.size1(), mat.size2());\n\n\tfor(std::size_t i=0; i\nconst t_mat& su2_matrix(std::size_t which)\nrequires is_mat && is_complex\n{\n\tusing t_cplx = typename t_mat::value_type;\n\tconstexpr t_cplx c0(0,0);\n\tconstexpr t_cplx c1(1,0);\n\tconstexpr t_cplx cI(0,1);\n\n\tstatic const t_mat mat[] =\n\t{\n\t\tcreate({{c0, c1}, { c1, c0}}),\t// x\n\t\tcreate({{c0, cI}, {-cI, c0}}),\t// y\n\t\tcreate({{c1, c0}, { c0, -c1}}),\t// z\n\t};\n\n\treturn mat[which];\n}\n\n\n/**\n * get a vector of pauli matrices\n * @see (Arfken 2013), p. 110\n */\ntemplate\nt_vec su2_matrices(bool bIncludeUnit = false)\nrequires is_basic_vec && is_mat\n\t&& is_complex\n{\n\tusing t_mat = typename t_vec::value_type;\n\n\tt_vec vec;\n\tvec.reserve(4);\n\n\tif(bIncludeUnit)\n\t\tvec.emplace_back(unit(2));\n\tfor(std::size_t i=0; i<3; ++i)\n\t\tvec.emplace_back(su2_matrix(i));\n\n\treturn vec;\n}\n\n\n/**\n * project the vector of SU(2) matrices onto a vector\n * proj = \n */\ntemplate\nt_mat proj_su2(const t_vec& vec, bool bIsNormalised=1)\nrequires is_vec && is_mat\n{\n\ttypename t_vec::value_type len = 1;\n\tif(!bIsNormalised)\n\t\tlen = norm(vec);\n\n\tconst auto sigma = su2_matrices>(false);\n\treturn inner, t_vec>(sigma, vec);\n}\n\n\n/**\n * SU(2) ladders\n * @see https://en.wikipedia.org/wiki/Ladder_operator\n */\ntemplate\nconst t_mat& su2_ladder(std::size_t which)\nrequires is_mat && is_complex\n{\n\tusing t_cplx = typename t_mat::value_type;\n\tconstexpr t_cplx cI(0,1);\n\tconstexpr t_cplx c05(0.5, 0);\n\n\tstatic const t_mat mat[] =\n\t{\n\t\tc05*su2_matrix(0) + c05*cI*su2_matrix(1),\t// up\n\t\tc05*su2_matrix(0) - c05*cI*su2_matrix(1),\t// down\n\t};\n\n\treturn mat[which];\n}\n\n\n/**\n * SU(3) generators, Gell-Mann matrices\n * @see https://de.wikipedia.org/wiki/Gell-Mann-Matrizen\n */\ntemplate\nconst t_mat& su3_matrix(std::size_t which)\nrequires is_mat && is_complex\n{\n\tusing t_cplx = typename t_mat::value_type;\n\tusing t_real = typename t_cplx::value_type;\n\tconstexpr t_cplx c0(0,0);\n\tconstexpr t_cplx c1(1,0);\n\tconstexpr t_cplx c2(2,0);\n\tconstexpr t_cplx cI(0,1);\n\tconstexpr t_real s3 = std::sqrt(3.);\n\n\tstatic const t_mat mat[] =\n\t{\n\t\tcreate({{c0,c1,c0}, {c1,c0,c0}, {c0,c0,c0}}),\t\t\t// 1\n\t\tcreate({{c0,cI,c0}, {-cI,c0,c0}, {c0,c0,c0}}),\t\t\t// 2\n\t\tcreate({{c1,c0,c0}, {c0,-c1,c0}, {c0,c0,c0}}),\t\t\t// 3\n\t\tcreate({{c0,c0,c1}, {c0,c0,c0}, {c1,c0,c0}}),\t\t\t// 4\n\t\tcreate({{c0,c0,cI}, {c0,c0,c0}, {-cI,c0,c0}}),\t\t\t// 5\n\t\tcreate({{c0,c0,c0}, {c0,c0,c1}, {c0,c1,c0}}),\t\t\t// 6\n\t\tcreate({{c0,c0,c0}, {c0,c0,cI}, {c0,-cI,c0}}),\t\t\t// 7\n\t\tcreate({{c1/s3,c0,c0}, {c0,c1/s3,c0}, {c0,c0,-c2/s3*c1}}),\t// 8\n\t};\n\n\treturn mat[which];\n}\n\n\n\n/**\n * real crystallographic A matrix\n * @see https://en.wikipedia.org/wiki/Fractional_coordinates\n */\ntemplate\nt_mat A_matrix(t_real a, t_real b, t_real c, t_real _aa, t_real _bb, t_real _cc)\nrequires is_mat\n{\n\tconst t_real ca = std::cos(_aa);\n\tconst t_real cb = std::cos(_bb);\n\tconst t_real cc = std::cos(_cc);\n\tconst t_real sc = std::sin(_cc);\n\tconst t_real sb = std::sin(_bb);\n\n\treturn create({\n\t\ta, b*cc, c*cb,\n\t\tt_real{0}, b*sc, c*(ca - cc*cb)/sc,\n\t\tt_real{0}, t_real{0}, c*std::sqrt(sb*sb - std::pow((ca - cc*cb)/sc, t_real{2}))\n\t});\n}\n\n\n/**\n * reciprocal crystallographic B matrix, B = 2pi * A^(-T)\n * @see https://en.wikipedia.org/wiki/Fractional_coordinates\n */\ntemplate\nt_mat B_matrix(t_real a, t_real b, t_real c, t_real _aa, t_real _bb, t_real _cc)\nrequires is_mat\n{\n\tconst t_real sc = std::sin(_cc);\n\tconst t_real ca = std::cos(_aa);\n\tconst t_real cb = std::cos(_bb);\n\tconst t_real cc = std::cos(_cc);\n\tconst t_real rr = std::sqrt(1. + 2.*ca*cb*cc - (ca*ca + cb*cb + cc*cc));\n\n\treturn t_real{2}*pi * create({\n\t\tt_real{1}/a, t_real{0}, t_real{0},\n\t\t-t_real{1}/a * cc/sc, t_real{1}/b * t_real{1}/sc, t_real{0},\n\t\t(cc*ca - cb)/(a*sc*rr), (cb*cc-ca)/(b*sc*rr), sc/(c*rr)\n\t});\n}\n\n\n/**\n * UB orientation matrix\n * @see https://dx.doi.org/10.1107/S0021889805004875\n */\ntemplate\nt_mat UB_matrix(const t_mat& B, \n\tconst t_vec& vec1_rlu, const t_vec& vec2_rlu, const t_vec& vec3_rlu)\nrequires is_mat && is_vec\n{\n\tt_vec vec1_lab = B * vec1_rlu;\n\tt_vec vec2_lab = B * vec2_rlu;\n\tt_vec vec3_lab = B * vec3_rlu;\n\n\tvec1_lab /= norm(vec1_lab);\n\tvec2_lab /= norm(vec2_lab);\n\tvec3_lab /= norm(vec3_lab);\n\n\tt_mat U_lab = unit(B.size1(), B.size2());\n\tset_row(U_lab, vec1_lab, 0);\n\tset_row(U_lab, vec2_lab, 1);\n\tset_row(U_lab, vec3_lab, 2);\n\n\treturn U_lab * B;\n}\n\n\n/**\n * get correct distance in unit cell, considering wrapping-around\n */\ntemplate\nt_real get_dist_uc(const t_mat& matA, const t_vec& vec1, const t_vec& vec2)\nrequires is_mat && is_vec\n{\n\tt_vec vec1A = matA * vec1;\n\n\t// all supercell position to try\n\tstd::vector vecSCs\n\t{{\n\t\tcreate({0, 0, 0}),\n\n\t\tcreate({+1, 0, 0}), create({ 0, +1, 0}), create({ 0, 0, +1}),\n\n\t\tcreate({ 0, +1, +1}), create({ 0, +1, -1}),\n\t\tcreate({+1, 0, +1}), create({+1, 0, -1}),\n\t\tcreate({+1, +1, 0}), create({+1, -1, 0}),\n\n\t\tcreate({+1, +1, +1}), create({+1, +1, -1}),\n\t\tcreate({+1, -1, +1}), create({+1, -1, -1}),\n\t}};\n\n\tt_real thedist = std::numeric_limits::max();\n\n\tfor(const t_vec& _vecSC : vecSCs)\n\t{\n\t\tfor(const t_vec& vecSC : { _vecSC, -_vecSC, t_real{2}*_vecSC, t_real{-2}*_vecSC })\n\t\t{\n\t\t\tt_vec vec2A = matA * (vec2 + vecSC);\n\t\t\tt_real dist = norm(vec1A - vec2A);\n\n\t\t\tthedist = std::min(thedist, dist);\n\t\t}\n\t}\n\n\treturn thedist;\n}\n\n\n\n/**\n * general structure factor calculation\n * e.g. type T as vector (complex number) for magnetic (nuclear) structure factor\n * Ms_or_bs:\n\t- nuclear scattering lengths for nuclear neutron scattering or\n\t- atomic form factors for x-ray scattering\n\t- magnetisation (* magnetic form factor) for magnetic neutron scattering\n * Rs: atomic positions\n * Q: scattering vector G for nuclear scattering or G+k for magnetic scattering with propagation vector k\n * fs: optional magnetic form factors\n *\n * @see (Shirane 2002), p. 25, equ. 2.26 for nuclear structure factor\n * @see (Shirane 2002), p. 40, equ. 2.81 for magnetic structure factor\n * @see https://doi.org/10.1016/B978-044451050-1/50002-1\n */\ntemplate class t_cont = std::vector,\n\tclass t_cplx = std::complex>\nT structure_factor(const t_cont& Ms_or_bs, const t_cont& Rs, const t_vec& Q, const t_vec* fs=nullptr)\nrequires is_basic_vec\n{\n\tusing t_real = typename t_cplx::value_type;\n\tconstexpr t_cplx cI{0,1};\n\tconstexpr t_real twopi = pi * t_real{2};\n\tconstexpr t_real expsign = -1;\n\n\tT F{};\n\tif(Rs.size() == 0)\n\t\treturn F;\n\tif constexpr(is_vec)\n\t\tF = zero(Rs.begin()->size());\t// always 3 dims...\n\telse if constexpr(is_complex)\n\t\tF = T(0);\n\n\tauto iterM_or_b = Ms_or_bs.begin();\n\tauto iterR = Rs.begin();\n\ttypename t_vec::const_iterator iterf;\n\tif(fs) iterf = fs->begin();\n\n\twhile(iterM_or_b != Ms_or_bs.end() && iterR != Rs.end())\n\t{\n\t\t// if form factors are given, use them, otherwise set to 1\n\t\tt_real f = t_real(1);\n\t\tif(fs)\n\t\t{\n\t\t\tauto fval = *iterf;\n\t\t\tif constexpr(is_complex)\n\t\t\t\tf = fval.real();\n\t\t\telse\n\t\t\t\tf = fval;\n\t\t}\n\n\t\t// structure factor\n\t\tF += (*iterM_or_b) * f * std::exp(expsign * cI * twopi * inner(Q, *iterR));\n\n\t\t// next M or b if available (otherwise keep current)\n\t\tauto iterM_or_b_next = std::next(iterM_or_b, 1);\n\t\tif(iterM_or_b_next != Ms_or_bs.end())\n\t\t\titerM_or_b = iterM_or_b_next;\n\n\t\tif(fs)\n\t\t{\n\t\t\t// next form factor if available (otherwise keep current)\n\t\t\tauto iterf_next = std::next(iterf, 1);\n\t\t\tif(iterf_next != fs->end())\n\t\t\t\titerf = iterf_next;\n\t\t}\n\n\t\t// next atomic position\n\t\tstd::advance(iterR, 1);\n\t}\n\n\treturn F;\n}\n// ----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n/**\n * wrap atom positions back to unit cell\n */\ntemplate\nt_vec keep_atom_in_uc(const t_vec& _atom)\nrequires is_vec\n{\n\tauto newatom = _atom;\n\n\tfor(std::size_t i=0; i= t_real{0.5})\n\t\t\tnewatom[i] -= std::abs(std::ceil(newatom[i]));\n\t}\n\n\treturn newatom;\n}\n\n\n\n/**\n * wrap collection of atom positions back to unit cell\n */\ntemplate class t_cont = std::vector>\nt_cont keep_atoms_in_uc(const t_cont& _atoms)\nrequires is_vec\n{\n\tt_cont newatoms;\n\tnewatoms.reserve(_atoms.size());\n\n\tfor(const auto& _atom : _atoms)\n\t\tnewatoms.emplace_back(keep_atom_in_uc(_atom));\n\n\treturn newatoms;\n}\n\n\n\n/**\n * create positions using the given symmetry operations\n */\ntemplate class t_cont = std::vector>\nt_cont apply_ops_hom(const t_vec& _atom, const t_cont& ops,\n\tt_real eps=std::numeric_limits::epsilon(), bool bKeepInUnitCell=true)\nrequires is_vec && is_mat\n{\n\t// in homogeneous coordinates\n\tt_vec atom = _atom;\n\tif(atom.size() == 3)\n\t\tatom = create({atom[0], atom[1], atom[2], 1});\n\n\tt_cont newatoms;\n\tnewatoms.reserve(ops.size());\n\n\tfor(const auto& op : ops)\n\t{\n\t\tauto newatom = op*atom;\n\t\tnewatom.resize(3);\n\n\t\tif(bKeepInUnitCell)\n\t\t\tnewatom = keep_atom_in_uc(newatom);\n\n\t\t// position already occupied?\n\t\tif(std::find_if(newatoms.begin(), newatoms.end(), [&newatom, eps](const t_vec& vec)->bool\n\t\t{\n\t\t\treturn tl2::equals(vec, newatom, eps);\n\t\t}) == newatoms.end())\n\t\t{\n\t\t\tnewatoms.emplace_back(std::move(newatom));\n\t\t}\n\t}\n\n\treturn newatoms;\n}\n// ----------------------------------------------------------------------------\n\n\n\n\n// ----------------------------------------------------------------------------\n// polarisation\n// ----------------------------------------------------------------------------\n\n/**\n * conjugate complex vector\n */\ntemplate\nt_vec conj(const t_vec& vec)\nrequires is_basic_vec\n{\n\tconst std::size_t N = vec.size();\n\tt_vec vecConj = zero(N);\n\n\tfor(std::size_t iComp=0; iComp)\n\t\t\tvecConj[iComp] = std::conj(vec[iComp]);\n\t\telse\t// simply copy non-complex vector\n\t\t\tvecConj[iComp] = vec[iComp];\n\t}\n\n\treturn vecConj;\n}\n\n\n/**\n * hermitian conjugate complex matrix\n */\ntemplate\nt_mat herm(const t_mat& mat)\nrequires is_basic_mat\n{\n\tt_mat mat2;\n\tif constexpr(is_dyn_mat)\n\t\tmat2 = t_mat(mat.size2(), mat.size1());\n\n\tfor(std::size_t i=0; i)\n\t\t\t\tmat2(j,i) = std::conj(mat(i,j));\n\t\t\telse\t// simply transpose non-complex matrix\n\t\t\t\tmat2(j,i) = mat(i,j);\n\t\t}\n\t}\n\n\treturn mat2;\n}\n\n\n/**\n * polarisation density matrix\n * (based on a proof from a lecture by P. J. Brown, 2006)\n *\n * eigenvector expansion of a state: |psi> = a_i |xi_i>\n * mean value of operator with mixed states:\n * = p_i * \n * = tr( A * p_i * |a_i> = tr( A * rho )\n * polarisation density matrix: rho = 0.5 * (1 + )\n *\n * @see https://doi.org/10.1016/B978-044451050-1/50006-9\n * @see (Desktop Bronstein 2008), Ch. 21 (Zusatzkapitel.pdf), pp. 11-12 and p. 24\n */\ntemplate\nt_mat pol_density_mat(const t_vec& P, typename t_vec::value_type c=0.5)\nrequires is_vec && is_mat\n{\n\treturn (unit(2,2) + proj_su2(P, true)) * c;\n}\n\n\n/**\n * Blume-Maleev equation\n * @returns scattering intensity and final polarisation vector\n *\n * @see https://doi.org/10.1016/B978-044451050-1/50006-9 - p. 225-226\n */\ntemplate\nstd::tuple blume_maleev(const t_vec& P_i, const t_vec& Mperp, const t_cplx& N)\nrequires is_vec\n{\n\tconst t_vec MperpConj = conj(Mperp);\n\tconst t_cplx NConj = std::conj(N);\n\tconstexpr t_cplx imag(0, 1);\n\n\t// ------------------------------------------------------------------------\n\t// intensity\n\t// nuclear\n\tt_cplx I = NConj*N;\n\n\t// nuclear-magnetic\n\tI += NConj*inner(P_i, Mperp);\n\tI += N*inner(Mperp, P_i);\n\n\t// magnetic, non-chiral\n\tI += inner(Mperp, Mperp);\n\n\t// magnetic, chiral\n\tI += imag * inner(P_i, cross({ MperpConj, Mperp }));\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t// polarisation vector\n\t// nuclear\n\tt_vec P_f = P_i * N*NConj;\n\n\t// nuclear-magnetic\n\tP_f += NConj * Mperp;\n\tP_f += N * MperpConj;\n\tP_f += imag * N * cross({ P_i, MperpConj });\n\tP_f += -imag * NConj * cross({ P_i, Mperp });\n\n\t// magnetic, non-chiral\n\tP_f += Mperp * inner(Mperp, P_i);\n\tP_f += MperpConj * inner(P_i, Mperp);\n\tP_f += -P_i * inner(Mperp, Mperp);\n\n\t// magnetic, chiral\n\tP_f += imag * cross({ Mperp, MperpConj });\n\t// ------------------------------------------------------------------------\n\n\treturn std::make_tuple(I, P_f/I);\n}\n\n\n/**\n * Blume-Maleev equation\n * calculate equation indirectly with density matrix\n * (based on a proof from a lecture by P. J. Brown, 2006)\n *\n * V = N*1 + \n * I = tr( rho )\n * P_f = tr( rho ) / I\n *\n * @returns scattering intensity and final polarisation vector\n *\n * @see https://doi.org/10.1016/B978-044451050-1/50006-9 - p. 225-226\n */\ntemplate\nstd::tuple blume_maleev_indir(const t_vec& P_i, const t_vec& Mperp, const t_cplx& N)\nrequires is_mat && is_vec\n{\n\t// spin-1/2\n\tconstexpr t_cplx c = 0.5;\n\n\t// vector of pauli matrices\n\tconst auto sigma = su2_matrices>(false);\n\n\t// density matrix\n\tconst auto density = pol_density_mat(P_i, c);\n\n\t// potential\n\tconst auto V_mag = proj_su2(Mperp, true);\n\tconst auto V_nuc = N * unit(2);\n\tconst auto V = V_nuc + V_mag;\n\tconst auto VConj = herm(V);\n\n\t// scattering intensity\n\tt_cplx I = trace(VConj*V * density);\n\n\t// ------------------------------------------------------------------------\n\t// scattered polarisation vector\n\tconst auto m0 = (VConj * sigma[0]) * V * density;\n\tconst auto m1 = (VConj * sigma[1]) * V * density;\n\tconst auto m2 = (VConj * sigma[2]) * V * density;\n\n\tt_vec P_f = create({ trace(m0), trace(m1), trace(m2) });\n\t// ------------------------------------------------------------------------\n\n\treturn std::make_tuple(I, P_f/I);\n}\n\n\n// ----------------------------------------------------------------------------\n}\n\n\n\n// ----------------------------------------------------------------------------\n// lapack wrappers\n// ----------------------------------------------------------------------------\n#ifdef __TLIBS2_USE_LAPACK__\n\nnamespace tl2_la {\n\n/**\n * LU decomposition of a matrix, mat = P * L * U, returning raw results\n * @returns [ok, LU, perm]\n * @see http://www.math.utah.edu/software/lapack/lapack-d/dgetrf.html\n */\ntemplate class t_vec = std::vector>\nstd::tuple, t_vec> _lu_raw(const t_mat& mat)\nrequires tl2::is_mat\n{\n\tusing namespace tl2_ops;\n\tusing t_scalar = typename t_mat::value_type;\n\tusing t_real = tl2::underlying_value_type;\n\n\tconst std::size_t rows = mat.size1();\n\tconst std::size_t cols = mat.size2();\n\tconst std::size_t minor = std::min(rows, cols);\n\n\n\tt_vec outmat(rows*cols);\n\tt_vec outpivots(minor);\n\n\tfor(std::size_t i=0; i)\n\t{\n\t\tif constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_cgetrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outpivots.data());\n\t\telse if constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_zgetrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outpivots.data());\n\t}\n\telse\n\t{\n\t\tif constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_sgetrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outpivots.data());\n\t\telse if constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outpivots.data());\n\t}\n\n\treturn std::make_tuple(err == 0, outmat, outpivots);\n}\n\n\n/**\n * LU decomposition of a matrix, mat = P * L * U\n * @returns [ok, P, L, U]\n * @see http://www.math.utah.edu/software/lapack/lapack-d/dgetrf.html\n */\ntemplate class t_vec = std::vector>\nstd::tuple lu(const t_mat& mat)\nrequires tl2::is_mat\n{\n\tusing namespace tl2_ops;\n\n\tconst std::size_t rows = mat.size1();\n\tconst std::size_t cols = mat.size2();\n\n\n\tauto [ ok, lumat, pivots ] = _lu_raw(mat);\n\n\tt_mat P = tl2::unit(rows, cols);\n\tt_mat L = tl2::unit(rows, cols);\n\tt_mat U = tl2::unit(rows, cols);\n\n\t// L and U\n\tfor(std::size_t i=0; i=i)\n\t\t\t\tU(i, j) = lumat[i*cols + j];\n\t\t\telse\n\t\t\t\tL(i, j) = lumat[i*cols + j];\n\t\t}\n\t}\n\n\t// permutation matrix P\n\tfor(std::size_t i=0; i(P, tl2::perm(rows, cols, i, pivots[i]-1));\n\n\treturn std::make_tuple(ok, P, L, U);\n}\n\n\n/**\n * inverted matrix\n */\ntemplate\nstd::tuple inv(const t_mat& mat)\nrequires tl2::is_mat\n{\n\t// fail if matrix is not square\n\tif constexpr(tl2::is_dyn_mat)\n\t\tassert((mat.size1() == mat.size2()));\n\telse\n\t\tstatic_assert(t_mat::size1() == t_mat::size2());\n\n\tusing t_scalar = typename t_mat::value_type;\n\tusing t_real = tl2::underlying_value_type;\n\n\tconst std::size_t rows = mat.size1();\n\tconst std::size_t cols = mat.size2();\n\n\tt_mat I = tl2::unit(rows, cols);\n\n\n\t// lu factorisation\n\tauto [ ok, lumat, pivots ] = _lu_raw(mat);\n\tif(!ok)\n\t\treturn std::make_tuple(I, false);\n\n\n\t// inversion\n\tint err = -1;\n\tif constexpr(tl2::is_complex)\n\t{\n\t\tif constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_cgetri(LAPACK_ROW_MAJOR, rows, lumat.data(), rows, pivots.data());\n\t\telse if constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_zgetri(LAPACK_ROW_MAJOR, rows, lumat.data(), rows, pivots.data());\n\t}\n\telse\n\t{\n\t\tif constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_sgetri(LAPACK_ROW_MAJOR, rows, lumat.data(), rows, pivots.data());\n\t\telse if constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_dgetri(LAPACK_ROW_MAJOR, rows, lumat.data(), rows, pivots.data());\n\t}\n\n\n\tfor(std::size_t i=0; i>\nstd::tuple qr(const t_mat& mat)\nrequires tl2::is_mat\n{\n\tusing namespace tl2_ops;\n\tusing t_scalar = typename t_mat::value_type;\n\tusing t_real = tl2::underlying_value_type;\n\n\tconst std::size_t rows = mat.size1();\n\tconst std::size_t cols = mat.size2();\n\tconst std::size_t minor = std::min(rows, cols);\n\n\tconst t_mat I = tl2::unit(minor);\n\tt_mat Q = I, R = mat;\n\n\n\tt_vec outmat(rows*cols), outvec(minor);\n\n\tfor(std::size_t i=0; i)\n\t{\n\t\tif constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_cgeqrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outvec.data());\n\t\telse if constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_zgeqrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outvec.data());\n\t}\n\telse\n\t{\n\t\tif constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_sgeqrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outvec.data());\n\t\telse if constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_dgeqrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outvec.data());\n\t}\n\n\tfor(std::size_t i=0; i=i ? outmat[i*cols + j] : t_real{0});\n\n\n\tt_vec v = tl2::zero(minor);\n\n\tfor(std::size_t k=1; k<=minor; ++k)\n\t{\n\t\tfor(std::size_t i=1; i<=k-1; ++i)\n\t\t\tv[i-1] = t_real{0};\n\t\tv[k-1] = t_real{1};\n\n\t\tfor(std::size_t i=k+1; i<=minor; ++i)\n\t\t\tv[i-1] = outmat[(i-1)*cols + (k-1)];\n\n\t\tQ = Q * (I - outvec[k-1]*tl2::outer(v, v));\n\t}\n\n\treturn std::make_tuple(err == 0, Q, R);\n}\n\n\n/**\n * eigenvectors and -values of a complex matrix\n * @returns [ok, evals, evecs]\n */\ntemplate\nstd::tuple, std::vector>\neigenvec(const t_mat_cplx& mat, bool only_evals=false, bool is_hermitian=false, bool normalise=false,\n\tt_real mineval=-1, t_real maxeval=-2, t_real eps=-1)\n\trequires tl2::is_mat && tl2::is_vec && tl2::is_complex\n{\n bool only_selected_evals = (mineval <= maxeval);\n\tbool use_selective_func = only_selected_evals;\n\t//use_selective_func = true;\n\n\tstd::vector evals;\n\tstd::vector evecs;\n\n\tif(mat.size1() != mat.size2() || mat.size1() == 0)\n\t\treturn std::make_tuple(0, evals, evecs);\n\n\tconst std::size_t N = mat.size1();\n\tevals.resize(N);\n\n\tif(!only_evals)\n\t\tevecs.resize(N, tl2::zero(N));\n\n\tstd::vector inmat(N*N, t_cplx{0,0}),\n\t\toutevecs(only_evals ? 0 : N*N, t_cplx{0,0});\n\n\tfor(std::size_t i=0; i=i ? mat(j,i) : t_real{0});\n\t\t\telse\n\t\t\t\tinmat[i*N + j] = mat(j,i);\n\t\t}\n\t}\n\n\n\tint err = -1;\n\n\tif(is_hermitian)\n\t{\n\t\t// evals of hermitian matrix are purely real\n\t\tstd::vector outevals_real(N, t_real{0});\n\n\t\t// all eigenvalues\n\t\tif(!use_selective_func)\n\t\t{\n\t\t\tif constexpr(std::is_same_v)\n\t\t\t\terr = LAPACKE_cheev(LAPACK_COL_MAJOR, only_evals ? 'N' : 'V', 'L', N, inmat.data(), N, outevals_real.data());\n\t\t\telse if constexpr(std::is_same_v)\n\t\t\t\terr = LAPACKE_zheev(LAPACK_COL_MAJOR, only_evals ? 'N' : 'V', 'L', N, inmat.data(), N, outevals_real.data());\n\t\t\telse\n\t\t\t\tthrow std::domain_error(\"Invalid real type.\");\n\t\t}\n\n\t\t// only selected eigenvalues\n\t\telse\n\t\t{\n\t\t\tint minidx = 1, maxidx = N;\n\t\t\tint iNumFound = 0;\n\n\t\t\tstd::unique_ptr>\n\t\t\tuptrIdxArr(new int[2*N]);\n\n\t\t\t// use maximum precision if none given\n\t\t\tif(eps < t_real{0})\n\t\t\t{\n\t\t\t\tif constexpr(std::is_same_v)\n\t\t\t\t\teps = LAPACKE_slamch('S');\n\t\t\t\telse if constexpr(std::is_same_v)\n\t\t\t\t\teps = LAPACKE_dlamch('S');\n\t\t\t\telse\n\t\t\t\t\tthrow std::domain_error(\"Invalid real type.\");\n\t\t\t}\n\n\t\t\tif constexpr(std::is_same_v)\n\t\t\t\terr = LAPACKE_cheevr(LAPACK_COL_MAJOR, (only_evals ? 'N' : 'V'), (only_selected_evals?'V':'A'), 'L',\n\t\t\t\t\tN, inmat.data(), N, mineval, maxeval, minidx, maxidx,\n\t\t\t\t\teps, &iNumFound, outevals_real.data(), outevecs.data(), N, uptrIdxArr.get());\n\t\t\telse if constexpr(std::is_same_v)\n\t\t\t\terr = LAPACKE_zheevr(LAPACK_COL_MAJOR, (only_evals ? 'N' : 'V'), (only_selected_evals?'V':'A'), 'L',\n\t\t\t\t\tN, inmat.data(), N, mineval, maxeval, minidx, maxidx,\n\t\t\t\t\teps, &iNumFound, outevals_real.data(), outevecs.data(), N, uptrIdxArr.get());\n\t\t\telse\n\t\t\t\tthrow std::domain_error(\"Invalid real type.\");\n\n\t\t\t// resize to actual number of eigenvalues and -vectors\n\t\t\tif(std::size_t(iNumFound) != N)\n\t\t\t{\n\t\t\t\tevals.resize(iNumFound, t_real{0});\n\t\t\t\tevecs.resize(iNumFound, tl2::zero(N));\n\t\t\t}\n\t\t}\n\n\t\t// copy to complex output vector\n\t\tfor(std::size_t i=0; i)\n\t\t{\n\t\t\terr = LAPACKE_cgeev(LAPACK_COL_MAJOR, 'N', only_evals ? 'N' : 'V', N,\n\t\t\t\tinmat.data(), N, evals.data(), nullptr, N,\n\t\t\t\tonly_evals ? nullptr : outevecs.data(), N);\n\t\t}\n\t\telse if constexpr(std::is_same_v)\n\t\t{\n\t\t\terr = LAPACKE_zgeev(LAPACK_COL_MAJOR, 'N', only_evals ? 'N' : 'V', N,\n\t\t\t\tinmat.data(), N, evals.data(), nullptr, N,\n\t\t\t\tonly_evals ? nullptr : outevecs.data(), N);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::domain_error(\"Invalid real type.\");\n\t\t}\n\t}\n\n\n\tif(!only_evals)\n\t{\n\t\tfor(std::size_t i=0; i(n, t_cplx{0,0}))\n\t\t\t\t\tevecs[i] /= n;\n\t\t\t}\n }\n\t}\n\n\treturn std::make_tuple(err == 0, evals, evecs);\n}\n\n\n/**\n * eigenvectors and -values of a real matrix\n * @returns [ok, evals_re, evals_im, evecs_re, evecs_im]\n */\ntemplate\nstd::tuple, std::vector, std::vector, std::vector>\neigenvec(const t_mat& mat, bool only_evals=false, bool is_symmetric=false, bool normalise=false,\n\tt_real mineval=-1, t_real maxeval=-2, t_real eps=-1)\n\trequires (tl2::is_mat && tl2::is_vec && !tl2::is_complex)\n{\n\tbool only_selected_evals = (mineval <= maxeval);\n\tbool use_selective_func = only_selected_evals;\n\t//use_selective_func = true;\n\n\tstd::vector evals_re, evals_im;\n\tstd::vector evecs_re, evecs_im;\n\n\tif(mat.size1() != mat.size2() || mat.size1() == 0)\n\t\treturn std::make_tuple(false, evals_re, evals_im, evecs_re, evecs_im);\n\n\tconst std::size_t N = mat.size1();\n\tevals_re.resize(N, t_real{0});\n\tevals_im.resize(N, t_real{0});\n\n\tif(!only_evals)\n\t{\n\t\tevecs_re.resize(N, tl2::zero(N));\n\t\tevecs_im.resize(N, tl2::zero(N));\n\t}\n\n\tstd::vector inmat(N*N, t_real{0}),\n\t\toutevecs(only_evals ? 0 : N*N, t_real{0});\n\n\tfor(std::size_t i=0; i=i ? mat(j,i) : t_real{0});\n\t\t\telse\n\t\t\t\tinmat[i*N + j] = mat(j,i);\n\t\t}\n\t}\n\n\tint err = -1;\n\n\tif(is_symmetric)\n\t{\n\t\t// all eigenvalues\n\t\tif(!use_selective_func)\n\t\t{\n\t\t\t// evals of symmetric matrix are purely real\n\t\t\tif constexpr(std::is_same_v)\n\t\t\t\terr = LAPACKE_ssyev(LAPACK_COL_MAJOR, (only_evals ? 'N' : 'V'), 'L', N, inmat.data(), N, evals_re.data());\n\t\t\telse if constexpr(std::is_same_v)\n\t\t\t\terr = LAPACKE_dsyev(LAPACK_COL_MAJOR, (only_evals ? 'N' : 'V'), 'L', N, inmat.data(), N, evals_re.data());\n\t\t\telse\n\t\t\t\tthrow std::domain_error(\"Invalid real type.\");\n\t\t}\n\n\t\t// only selected eigenvalues\n\t\telse\n\t\t{\n\t\t\tint minidx = 1, maxidx = N;\n\t\t\tint iNumFound = 0;\n\n\t\t\tstd::unique_ptr>\n\t\t\tuptrIdxArr(new int[2*N]);\n\n\t\t\t// use maximum precision if none given\n\t\t\tif(eps < t_real{0})\n\t\t\t{\n\t\t\t\tif constexpr(std::is_same_v)\n\t\t\t\t\teps = LAPACKE_slamch('S');\n\t\t\t\telse if constexpr(std::is_same_v)\n\t\t\t\t\teps = LAPACKE_dlamch('S');\n\t\t\t\telse\n\t\t\t\t\tthrow std::domain_error(\"Invalid real type.\");\n\t\t\t}\n\n\t\t\tif constexpr(std::is_same_v)\n\t\t\t\terr = LAPACKE_ssyevr(LAPACK_COL_MAJOR, (only_evals?'N':'V'), (only_selected_evals?'V':'A'), 'L',\n\t\t\t\t\tN, inmat.data(), N, mineval, maxeval, minidx, maxidx,\n\t\t\t\t\teps, &iNumFound, evals_re.data(), outevecs.data(), N, uptrIdxArr.get());\n\t\t\telse if constexpr(std::is_same_v)\n\t\t\t\terr = LAPACKE_dsyevr(LAPACK_COL_MAJOR, (only_evals?'N':'V'), (only_selected_evals?'V':'A'), 'L',\n\t\t\t\t\tN, inmat.data(), N, mineval, maxeval, minidx, maxidx,\n\t\t\t\t\teps, &iNumFound, evals_re.data(), outevecs.data(), N, uptrIdxArr.get());\n\t\t\telse\n\t\t\t\tthrow std::domain_error(\"Invalid real type.\");\n\n\t\t\t// resize to actual number of eigenvalues and -vectors\n\t\t\tif(std::size_t(iNumFound) != N)\n\t\t\t{\n\t\t\t\tevals_re.resize(iNumFound, t_real{0});\n\t\t\t\tevals_im.resize(iNumFound, t_real{0});\n\t\t\t\tevecs_re.resize(iNumFound, tl2::zero(N));\n\t\t\t\tevecs_im.resize(iNumFound, tl2::zero(N));\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tif constexpr(std::is_same_v)\n\t\t{\n\t\t\terr = LAPACKE_sgeev(LAPACK_COL_MAJOR, 'N', (only_evals ? 'N' : 'V'), N,\n\t\t\t\tinmat.data(), N, evals_re.data(), evals_im.data(), nullptr, N,\n\t\t\t\tonly_evals ? nullptr : outevecs.data(), N);\n\t\t}\n\t\telse if constexpr(std::is_same_v)\n\t\t{\n\t\t\terr = LAPACKE_dgeev(LAPACK_COL_MAJOR, 'N', (only_evals ? 'N' : 'V'), N,\n\t\t\t\tinmat.data(), N, evals_re.data(), evals_im.data(), nullptr, N,\n\t\t\t\tonly_evals ? nullptr : outevecs.data(), N);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::domain_error(\"Invalid real type.\");\n\t\t}\n\t}\n\n\n\t// evecs\n\tif(!only_evals)\n\t{\n\t\tif((is_symmetric && !use_selective_func))\n\t\t{\n\t\t\tfor(std::size_t i=0; i(evals_im[i], 0))\n\t\t\t\t{\n\t\t\t\t\tfor(std::size_t j=0; j(sum, 0))\n\t\t\t\t{\n\t\t\t\t\tevecs_re[i] /= sum;\n\t\t\t\t\tevecs_im[i] /= sum;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn std::make_tuple(err == 0, evals_re, evals_im, evecs_re, evecs_im);\n}\n\n\n/**\n * singular values of a real or complex matrix mat = U * diag{vals} * V^h\n * @returns [ ok, U, Vh, vals ]\n */\ntemplate>\nstd::tuple>\nsingval(const t_mat& mat)\nrequires tl2::is_mat\n{\n\tconst std::size_t rows = mat.size1();\n\tconst std::size_t cols = mat.size2();\n\n\tconst auto [Nmin, Nmax] = std::minmax(rows, cols);\n\tstd::vector inmat(rows*cols), outU(rows*rows), outVh(cols*cols);\n\tstd::vector vals(Nmin);\n\tstd::vector _tmp(Nmax * Nmax * 2);\n\n\tfor(std::size_t i=0; i)\n\t{\n\t\tif constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_cgesvd(LAPACK_ROW_MAJOR, 'A', 'A', rows, cols, inmat.data(), cols,\n\t\t\t\tvals.data(), outU.data(), rows, outVh.data(), cols, _tmp.data());\n\t\telse\n\t\t\terr = LAPACKE_zgesvd(LAPACK_ROW_MAJOR, 'A', 'A', rows, cols, inmat.data(), cols,\n\t\t\t\tvals.data(), outU.data(), rows, outVh.data(), cols, _tmp.data());\n\t}\n\telse\n\t{\n\t\tif constexpr(std::is_same_v)\n\t\t\terr = LAPACKE_sgesvd(LAPACK_ROW_MAJOR, 'A', 'A', rows, cols, inmat.data(), cols,\n\t\t\t\tvals.data(), outU.data(), rows, outVh.data(), cols, _tmp.data());\n\t\telse\n\t\t\terr = LAPACKE_dgesvd(LAPACK_ROW_MAJOR, 'A', 'A', rows, cols, inmat.data(), cols,\n\t\t\t\tvals.data(), outU.data(), rows, outVh.data(), cols, _tmp.data());\n\t}\n\n\n\tt_mat U = tl2::unit(rows);\n\tt_mat Vh = tl2::unit(cols);\n\n\tfor(std::size_t i=0; i\nstd::tuple pseudoinv(const t_mat& mat)\nrequires tl2::is_mat\n{\n\tusing t_scalar = typename t_mat::value_type;\n\tusing t_real = tl2::underlying_value_type;\n\n\tauto [ ok, U, Vh, vals ] = singval(mat);\n\n\tauto V = tl2::herm(Vh);\n\tauto Uh = tl2::herm(U);\n\n\tfor(t_real& d : vals)\n\t{\n\t\tif(!tl2::equals(d, t_real(0)))\n\t\t\td = t_real(1)/d;\n\t}\n\n\tauto diag = tl2::diag(vals);\n\treturn std::make_tuple(tl2::prod(V, tl2::prod(diag, Uh)), ok);\n}\n\n\n\n// ----------------------------------------------------------------------------\n// equation solvers\n// ----------------------------------------------------------------------------\n\n/**\n * system of ODEs with constant coefficients C\n * @see (Arens 2015), pp. 1049-1051\n *\n * f'(x) = C f(x) and f(x0) = f0\n * => f(x) = f0 * exp(C(x-x0)) = sum_i norm_i * evec_i * exp(eval_i * (x-x0))\n * norm = (evec_i)^(-1) * f0\n */\ntemplate\nstd::tuple\nodesys_const(const t_mat& C, const t_val& x, const t_val& x0, const t_vec& f0)\nrequires (tl2::is_mat && tl2::is_vec)\n{\n\tconst std::size_t rows = C.size1();\n\tconst std::size_t cols = C.size2();\n\tif(rows != cols)\n\t\treturn std::make_tuple(false, t_vec{});\n\n\tconst auto [ok, evals, evecs] = eigenvec(C);\n\tif(!ok)\n\t\treturn std::make_tuple(false, t_vec{});\n\n\t//for(std::size_t i=0; i(evecs, false);\n\tconst auto [basis_inv, invok] = tl2::inv(basis);\n\tif(!invok)\n\t\treturn std::make_tuple(false, t_vec{});\n\tconst t_vec norm = basis_inv * f0;\n\n\tt_vec f = tl2::zero(cols);\n\tfor(std::size_t i=0; i\nstd::tuple\ndiffsys_const(const t_mat& C, const t_val& n, const t_val& n0, const t_vec& f0)\nrequires (tl2::is_mat && tl2::is_vec)\n{\n\tconst std::size_t rows = C.size1();\n\tconst std::size_t cols = C.size2();\n\tif(rows != cols)\n\t\treturn std::make_tuple(false, t_vec{});\n\n\tconst auto [ok, evals, evecs] = eigenvec(C);\n\tif(!ok)\n\t\treturn std::make_tuple(false, t_vec{});\n\n\t//for(std::size_t i=0; i(evecs, false);\n\tconst auto [basis_inv, invok] = tl2::inv(basis);\n\tif(!invok)\n\t\treturn std::make_tuple(false, t_vec{});\n\tconst t_vec norm = basis_inv * f0;\n\n\tt_vec f = tl2::zero(cols);\n\tfor(std::size_t i=0; i\nstd::tuple qr(const t_mat& mat)\nrequires is_mat && is_vec\n{\n#ifdef __TLIBS2_USE_LAPACK__\n\treturn tl2_la::qr(mat);\n\n#else\n\tconst std::size_t rows = mat.size1();\n\tconst std::size_t cols = mat.size2();\n\tconst std::size_t N = std::min(cols, rows);\n\n#if __TLIBS2_QR_METHOD == 0\n\tt_mat R = mat;\n\tt_mat Q = unit(N, N);\n\n\tfor(std::size_t icol=0; icol(R, icol);\n\t\tt_mat matMirror = ortho_mirror_zero_op(vecCol, icol);\n\n\t\tQ = prod(Q, matMirror, false);\n\t\tR = prod(matMirror, R);\n\t}\n\n#elif __TLIBS2_QR_METHOD == 1\n\tstd::vector sysM;\n\tsysM.reserve(mat.size2());\n\tfor(std::size_t i=0; i(mat, i));\n\n\tstd::vector Qsys = orthonorm_sys(sysM);\n\tt_mat Q = create(Qsys, false);\n\tt_mat R = prod(trans(Q), mat);\n#endif\n\n\treturn std::make_tuple(true, Q, R);\n#endif\n}\n\n\n/**\n * inverted matrix\n * @see https://en.wikipedia.org/wiki/Invertible_matrix#In_relation_to_its_adjugate\n * @see https://en.wikipedia.org/wiki/Adjugate_matrix\n */\ntemplate\nstd::tuple inv(const t_mat& mat)\nrequires is_mat\n{\n\t// fails if matrix is not square, TODO: fix\n\tif constexpr(tl2::is_dyn_mat)\n\t\tassert((mat.size1() == mat.size2()));\n\telse\n\t\tstatic_assert(t_mat::size1() == t_mat::size2());\n\n#ifdef __TLIBS2_USE_LAPACK__\n\treturn tl2_la::inv(mat);\n#else\n\tusing T = typename t_mat::value_type;\n\tusing t_vec = std::vector;\n\tconst std::size_t N = mat.size1();\n\n\tconst t_vec matFlat = convert(mat);\n\tconst T fullDet = flat_det(matFlat, N);\n\n\t// fail if determinant is zero\n\tif(equals(fullDet, 0))\n\t{\n\t\t//std::cerr << \"det == 0\" << std::endl;\n\t\treturn std::make_tuple(t_mat(), false);\n\t}\n\n\tt_mat matInv;\n\tif constexpr(is_dyn_mat)\n\t\tmatInv = t_mat(N, N);\n\n\tfor(std::size_t i=0; i(matFlat, N, N, i, j);\n\t\t\tmatInv(j,i) = sgn * flat_det(subMat, N-1);\n\t\t}\n\t}\n\n\tmatInv = matInv / fullDet;\n\treturn std::make_tuple(matInv, true);\n#endif\n}\n\n\n/**\n * determinant\n * \n * M v = l v\n * M = V^-1 L V\n * det(M) = det(V^-1 L V) = det(V V^-1 L) = det(L) = l_1*...*l_n\n */\ntemplate\ntypename t_mat::value_type det(const t_mat& mat)\nrequires is_mat\n{\n\tusing T = typename t_mat::value_type;\n\tif(mat.size1() != mat.size2())\n\t\treturn 0;\n\n#ifdef __TLIBS2_USE_LAPACK__\n\n\tusing t_vec = vec;\n\n\tif constexpr(tl2::is_complex)\n\t{\n\t\tconst auto [ok, evals, evecs] =\n\t\t\ttl2_la::eigenvec(mat, true, false, false);\n\n\t\tT detval{1, 0};\n\t\tfor(const auto& eval : evals)\n\t\t\tdetval *= eval;\n\n\t\treturn detval;\n\t}\n\telse\n\t{\n\t\tconst auto [ok, evalsRe, evalsIm, evecsRe, evecsIm] =\n\t\t\ttl2_la::eigenvec(mat, true, false, false);\n\n\t\tstd::complex detval{1, 0};\n\t\tfor(std::size_t i=0; i{evalsRe[i], evalsIm[i]};\n\n\t\treturn detval.real();\n\t}\n\n#else\n\n\tstd::vector matFlat = convert, t_mat>(mat);\n\treturn flat_det>(matFlat, mat.size1());\n\n#endif\n}\n\n\n/**\n * matrix power\n */\ntemplate\nstd::tuple pow(const t_mat& mat, int ipow)\nrequires is_mat\n{\n\tt_mat themat;\n\tif(mat.size1() != mat.size2())\n\t\treturn std::make_tuple(themat, false);\n\n\tbool ok = true;\n\tint ipow_pos = ipow<0 ? -ipow : ipow;\n\n\tthemat = unit(mat.size1());\n\tfor(int i=0; i(themat);\n\n\treturn std::make_tuple(themat, ok);\n}\n\n\n/**\n * least-squares regression, solves for parameters v\n * @see https://en.wikipedia.org/wiki/Least_squares\n * @see (Arens 2015), p. 793\n *\n * exact equation:\n * \tX v = y\n *\n * approx. equation (normal equation):\n * \tX^t X v = X^t y\n * \tv = inv(X^t X) X^t y\n *\n * \t(QR)^t QR v = X^t y\n * \tR^tQ^t QR v = X^t y\n * \tR^tR v = X^t y\n * \tv = inv(R^tR) X^t y\n */\ntemplate>\nstd::tuple leastsq(const t_vec& x, const t_vec& y, std::size_t order,\n\tbool use_qr=true, bool use_pseudoinv=false)\nrequires is_vec && is_dyn_mat\n{\n\t// check array sizes, TODO: fix\n\tif constexpr(tl2::is_dyn_vec)\n\t\tassert((x.size() == y.size()));\n\n\n\tusing namespace tl2_ops;\n\tusing T = typename t_vec::value_type;\n\n\tconst std::size_t N = x.size();\n\tt_mat X{N, order+1};\n\n\tfor(std::size_t j=0; j<=order; ++j)\n\t\tfor(std::size_t i=0; i(j));\n\n\n\tt_mat XtX;\n\n\tif(use_qr)\n\t{\n\t\tauto [ok_qr, Q, R] = qr(X);\n\t\tif(!ok_qr)\n\t\t\t\treturn std::make_tuple(t_vec{}, false);\n\n\t\tXtX = trans(R) * R;\n\t}\n\telse\n\t{\n\t\tXtX = trans(X) * X;\n\t}\n\n\tt_vec Xty = trans(X) * y;\n\tt_mat Y;\n\tbool ok = false;\n\n\tif(use_pseudoinv)\n\t{\n#ifdef __TLIBS2_USE_LAPACK__\n\t\tstd::tie(Y, ok) = tl2_la::pseudoinv(XtX);\n#else\n\t\t#pragma message(\"leastsq: Pseudo-inverse is not available, using standard inverse instead.\")\n\t\tstd::tie(Y, ok) = inv(XtX);\n#endif\n\t}\n\telse\n\t{\n\t\tstd::tie(Y, ok) = inv(XtX);\n\t}\n\n\tt_vec v = Y * Xty;\n\n\treturn std::make_tuple(v, ok);\n}\n\n\n\n/**\n * signed angle between two vectors\n */\ntemplate\ntypename t_vec::value_type angle(const t_vec& vec0,\n\tconst t_vec& vec1, const t_vec* pvec_norm=nullptr)\nrequires is_vec\n{\n\tusing namespace tl2_ops;\n\tusing t_real = typename t_vec::value_type;\n\n\tif(vec0.size() != vec1.size())\n\t\tthrow std::runtime_error(\"angle: vector sizes do not match.\");\n\n\tif(vec0.size() == 2)\n\t{\n\t\t// signed angles wrt basis\n\t\tt_real angle0 = std::atan2(vec0[1], vec0[0]);\n\t\tt_real angle1 = std::atan2(vec1[1], vec1[0]);\n\n\t\treturn angle1 - angle0;\n\t}\n\tif(vec0.size() == 3)\n\t{\n\t\t// cross product gives sine\n\t\tt_vec veccross = cross({vec0, vec1});\n\t\tt_real dS = norm(veccross);\n\n\t\t// dot product gives cosine\n\t\tt_real dC = inner(vec0, vec1);\n\t\tt_real dAngle = std::atan2(dS, dC);\n\n\t\t// get signed angle\n\t\tif(pvec_norm)\n\t\t{\n\t\t\t// see if the cross product points along the direction\n\t\t\t// of the given normal\n\t\t\tif(inner(veccross, *pvec_norm) < t_real{0})\n\t\t\t\tdAngle = -dAngle;\n\t\t}\n\n\t\treturn dAngle;\n\t}\n\n\tthrow std::runtime_error(\"angle: only implemented for size == 2 and size == 3.\");\n}\n\n\n\n/**\n * get the normal vector to a polygon\n */\ntemplate class t_cont = std::vector>\nt_vec get_poly_normal(t_cont& vecPoly)\nrequires is_vec\n{\n\tusing namespace tl2_ops;\n\tusing t_real = typename t_vec::value_type;\n\n\t// line from centre to vertex\n\tconst t_vec vecCentre = mean(vecPoly);\n\t// face normal\n\tt_vec vecNormBest = zero(vecCentre.size());\n\tt_real tBestCross = t_real(0);\n\n\t// find non-collinear vectors\n\tfor(std::size_t iVecPoly=1; iVecPoly({vecPoly[0]-vecCentre, vecPoly[1]-vecCentre});\n\t\tt_real tCross = norm(vecNorm);\n\t\tif(tCross > tBestCross)\n\t\t{\n\t\t\ttBestCross = tCross;\n\t\t\tvecNormBest = vecNorm;\n\t\t}\n\t}\n\n\t// nothing found\n\tif(vecNormBest.size() < vecCentre.size())\n\t\treturn t_vec{};\n\n\treturn vecNormBest;\n}\n\n\n\n/**\n * sort vertices in a convex polygon\n */\ntemplate class t_cont = std::vector>\nvoid sort_poly_verts_norm(t_cont& vecPoly, const t_vec& _vecNorm)\nrequires is_vec\n{\n\tusing namespace tl2_ops;\n\n\tif(vecPoly.size() <= 1)\n\t\treturn;\n\n\t// line from centre to vertex\n\tconst t_vec vecCentre = mean(vecPoly);\n\tconst t_vec vecNorm = _vecNorm / norm(_vecNorm);\n\n\tt_vec vec0 = vecPoly[0] - vecCentre;\n\n\tstd::stable_sort(vecPoly.begin(), vecPoly.end(),\n\t[&vecCentre, &vec0, &vecNorm](const t_vec& vertex1, const t_vec& vertex2) -> bool\n\t{\n\t\tt_vec vec1 = vertex1 - vecCentre;\n\t\tt_vec vec2 = vertex2 - vecCentre;\n\n\t\treturn angle(vec0, vec1, &vecNorm) < angle(vec0, vec2, &vecNorm);\n\t});\n}\n\n\n/**\n * sort vertices in a convex polygon using an absolute centre for determining the normal\n * @returns normal\n */\ntemplate class t_cont = std::vector>\nt_vec sort_poly_verts(t_cont& vecPoly, const t_vec& vecAbsCentre, bool make_norm_perp_to_poly=false)\nrequires is_vec\n{\n\tusing namespace tl2_ops;\n\n\tif(vecPoly.size() <= 1)\n\t\treturn t_vec{};\n\n\t// line from centre to vertex\n\tconst t_vec vecCentre = mean(vecPoly);\n\t// face normal\n\tt_vec vecNorm = vecCentre - vecAbsCentre;\n\n\tsort_poly_verts_norm(vecPoly, vecNorm);\n\n\tif(make_norm_perp_to_poly)\n\t{\n\t\tt_vec normal = get_poly_normal(vecPoly);\n\n\t\t// do they point in the same direction?\n\t\tif(inner(normal, vecNorm) < 0.)\n\t\t\tnormal = -normal;\n\t\tvecNorm = normal;\n\t}\n\n\tvecNorm /= norm(vecNorm);\n\treturn vecNorm;\n}\n\n\n/**\n * sort vertices in a convex polygon determining normal\n * @returns normal\n */\ntemplate class t_cont = std::vector>\nt_vec sort_poly_verts(t_cont& vecPoly)\nrequires is_vec\n{\n\tusing namespace tl2_ops;\n\n\tif(vecPoly.size() <= 1)\n\t\treturn;\n\n\tt_vec vecNorm = get_poly_normal(vecPoly);\n\tsort_poly_verts_norm(vecPoly, vecNorm, true);\n\n\tvecNorm /= norm(vecNorm);\n\treturn vecNorm;\n}\n\n}\n\n\n\n#ifdef __TLIBS2_USE_QHULL__\n\nnamespace tl2_qh {\n\n/**\n * calculates the convex hull\n * @see https://github.com/t-weber/misc/blob/master/geo/qhulltst.cpp\n */\ntemplate class t_cont = std::vector>\nstd::tuple>, t_cont, t_cont>\nget_convexhull(const t_cont& vecVerts)\nrequires tl2::is_vec\n{\n\tusing namespace tl2_ops;\n\n\tusing t_real = typename t_vec::value_type;\n\tusing t_real_qh = double;\n\tusing t_facetlist_iter = typename orgQhull::QhullLinkedList::iterator;\n\tusing t_vertexset_iter = typename orgQhull::QhullSet::iterator;\n\n\n\t// copy vertices\n\tint dim = vecVerts[0].size();\n\tstd::size_t len = vecVerts.size()*dim;\n\tstd::unique_ptr mem{new t_real_qh[len]};\n\n\tstd::size_t i=0;\n\tfor(const t_vec& vert : vecVerts)\n\t{\n\t\tfor(int d=0; d> vecPolys;\n\tt_cont vecNormals;\n\tt_cont vecDists;\n\tvecPolys.reserve(facets.size());\n\tvecNormals.reserve(facets.size());\n\tvecDists.reserve(facets.size());\n\t//const t_vec vecCentre = tl2::mean(vecVerts);\n\n\tfor(t_facetlist_iter iter=facets.begin(); iter!=facets.end(); ++iter)\n\t{\n\t\t// triangulable?\n\t\tif(iter->isUpperDelaunay())\n\t\t\tcontinue;\n\n\t\torgQhull::QhullVertexSet vertices = iter->vertices();\n\n\t\tt_cont vecPoly;\n\t\tvecPoly.reserve(vertices.size());\n\n\t\tfor(t_vertexset_iter iterVertex=vertices.begin(); iterVertex!=vertices.end(); ++iterVertex)\n\t\t{\n\t\t\torgQhull::QhullPoint point = (*iterVertex).point();\n\t\t\tt_vec vecPoint(dim);\n\t\t\tfor(int i=0; i(vecPoly, vecCentre, true);\n\t\tvecNormal.resize(dim);\n\n\t\torgQhull::QhullHyperplane plane = iter->hyperplane();\n\t\tconst t_real_qh* planenorm = plane.coordinates();\n\t\tconst t_real_qh planedist = plane.offset();\n\t\tfor(int i=0; i remove polyhedron\n\tif(vecPolys.size() < 3)\n\t\tvecPolys = decltype(vecPolys){};\n\n\treturn std::make_tuple(vecPolys, vecNormals, vecDists);\n}\n}\n#endif\n\n\n\nnamespace tl2 {\n// ----------------------------------------------------------------------------\n// Quaternions\n// @see (Kuipers 2002) for infos\n// ----------------------------------------------------------------------------\n\ntemplate t_quat unit_quat() requires is_quat\n{\n\treturn t_quat(1, 0,0,0);\n}\n\n\n/**\n * calculates the quaternion inverse\n * @see (Bronstein 2008), Ch. 4\n * @see (Kuipers 2002), p. 112\n * @see https://en.wikipedia.org/wiki/Quaternion#Conjugation,_the_norm,_and_reciprocal\n */\ntemplate t_quat inv(const t_quat& q) requires is_quat\n{\n\tt_quat qc{q.R_component_1(), -q.R_component_2(), -q.R_component_3(), -q.R_component_4()};\n\treturn qc / (q*qc);\n}\n\n\n/**\n * quaternion product\n * @see (Kuipers 2002), pp. 106-110\n * @see https://en.wikipedia.org/wiki/Quaternion#Scalar_and_vector_parts\n */\ntemplate\nt_quat prod(const t_quat& q1, const t_quat& q2)\nrequires is_quat && is_vec\n{\n\tusing T = typename t_quat::value_type;\n\n\tT r1 = q1.R_component_1();\n\tT r2 = q2.R_component_1();\n\n\tt_vec vec1 = create({q1.R_component_2(), q1.R_component_3(), q1.R_component_4()});\n\tt_vec vec2 = create({q2.R_component_2(), q2.R_component_3(), q2.R_component_4()});\n\n\tT r = r1*r2 - inner(vec1, vec2);\n\tt_vec vec = r1*vec2 + r2*vec1 + cross({vec1, vec2});;\n\n\treturn t_quat(r, vec[0], vec[1], vec[2]);\n}\n\n\n/**\n * 3x3 matrix -> quat\n * @desc algo from: http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q55\n */\ntemplate\nt_quat rot3_to_quat(const t_mat& rot)\nrequires is_quat && is_mat\n{\n\tusing T = typename t_quat::value_type;\n\tconst T tr = trace(rot);\n\tT v[3], w;\n\n\tif(tr > T(0))\t// scalar component is largest\n\t{\n\t\tw = T(0.5) * std::sqrt(tr+T(1));\n\t\tv[0] = (rot(2,1) - rot(1,2)) / (T(4)*w);\n\t\tv[1] = (rot(0,2) - rot(2,0)) / (T(4)*w);\n\t\tv[2] = (rot(1,0) - rot(0,1)) / (T(4)*w);\n\t}\n\telse\n\t{\n\t\tfor(std::size_t iComp=0; iComp<3; ++iComp)\t// find largest vector component\n\t\t{\n\t\t\tconst std::size_t iM = iComp;\t\t// major comp.\n\t\t\tconst std::size_t im1 = (iComp+1)%3;\t// minor comp. 1\n\t\t\tconst std::size_t im2 = (iComp+2)%3;\t// minor comp. 2\n\n\t\t\tif(rot(iM,iM)>=rot(im1,im1) && rot(iM,iM)>=rot(im2,im2))\n\t\t\t{\n\t\t\t\tv[iM] = T(0.5) * std::sqrt(T(1) + rot(iM,iM) - rot(im1,im1) - rot(im2,im2));\n\t\t\t\tv[im1] = (rot(im1, iM) + rot(iM, im1)) / (v[iM]*T(4));\n\t\t\t\tv[im2] = (rot(iM, im2) + rot(im2, iM)) / (v[iM]*T(4));\n\t\t\t\tw = (rot(im2,im1) - rot(im1,im2)) / (v[iM]*T(4));\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif(iComp>=2)\n\t\t\t\tthrow std::runtime_error(\"rot3_to_quat: invalid condition.\");\n\t\t}\n\t}\n\n\tt_quat quatRet{w, v[0],v[1],v[2]};\n\tT norm_eucl = std::sqrt(w*w + v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n\treturn quatRet / norm_eucl;\n}\n\n\n/**\n * quat -> 3x3 matrix\n * @see (Desktop Bronstein 2008), formulas (4.162a/b)\n * @see (Bronstein 2008), p. 296, formulas (4.109a/b)\n */\ntemplate\nt_mat quat_to_rot3(const t_quat& quat)\nrequires is_quat && is_mat\n{\n\tt_quat qc{quat.R_component_1(), -quat.R_component_2(), -quat.R_component_3(), -quat.R_component_4()};\n\tconst t_quat i{0,1,0,0}, j{0,0,1,0}, k{0,0,0,1};\n\tconst t_quat cols[] = { quat*i*qc, quat*j*qc, quat*k*qc };\n\n\tt_mat mat = unit(3);\n\tfor(std::size_t icol=0; icol<3; ++icol)\n\t{\n\t\tmat(0, icol) = cols[icol].R_component_2();\n\t\tmat(1, icol) = cols[icol].R_component_3();\n\t\tmat(2, icol) = cols[icol].R_component_4();\n\t}\n\n\treturn mat;\n}\n\n\n/**\n * vector -> quat\n * @see (Kuipers 2002), p. 114\n */\ntemplate\nt_quat vec3_to_quat(const t_vec& vec)\nrequires is_quat && is_vec\n{\n\tusing T = typename t_vec::value_type;\n\treturn t_quat{T(0), vec[0], vec[1], vec[2]};\n}\n\n\n/**\n * quat, vector product\n * @see (Kuipers 2002), p. 127\n */\ntemplate\nt_vec quat_vec_prod(const t_quat& q, const t_vec& v)\nrequires is_quat && is_vec\n{\n\tt_quat qv = vec3_to_quat(v);\n\tt_quat qc{q.R_component_1(), -q.R_component_2(), -q.R_component_3(), -q.R_component_4()};\n\tt_quat qvq = q * qv * qc;\n\n\treturn create({ qvq.R_component_2(), qvq.R_component_3(), qvq.R_component_4() });\n}\n\n\n/**\n * quat -> complex 2x2 matrix\n * @see (Scherer 2010), p.173\n * @see (DesktopBronstein08), ch. 4, equations (4.163a) and (4.163b)\n * @see (Bronstein08), ch. 4, p. 296, equation (4.110a) and (4.110b)\n */\ntemplate\nt_mat_cplx quat_to_cmat(const t_quat& quat)\nrequires is_quat && is_mat && is_mat\n{\n\tusing t_cplx = typename t_mat_cplx::value_type;\n\n\tconst auto matI = unit(2);\n\tt_mat_cplx mat =\n\t\tt_cplx(quat.R_component_1()) * matI +\n\t\tt_cplx(quat.R_component_2()) * su2_matrix(0) +\n\t\tt_cplx(quat.R_component_3()) * su2_matrix(1) +\n\t\tt_cplx(quat.R_component_4()) * su2_matrix(2);\n\n\treturn mat;\n}\n\n\n/**\n * rotation angle\n * @see https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix\n */\ntemplate\ntypename t_quat::value_type rotation_angle(const t_quat& quat)\nrequires is_quat\n{\n\tusing t_real = typename t_quat::value_type;\n\treturn t_real{2}*std::acos(quat.R_component_1());\n}\n\n\n/**\n * quat -> rotation axis\n * @see (Bronstein 2008), Ch. 4, pp. 301-302\n * @see https://en.wikipedia.org/wiki/Quaternion#Exponential,_logarithm,_and_power_functions\n * @see https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation\n */\ntemplate\nstd::pair rotation_axis(const t_quat& quat)\nrequires is_quat && is_vec\n{\n\tusing T = typename t_vec::value_type;\n\n\tt_vec vec = create({\n\t\tquat.R_component_2(),\n\t\tquat.R_component_3(),\n\t\tquat.R_component_4()\n\t});\n\n\tT angle = rotation_angle(quat);\n\tvec /= std::sin(T{0.5}*angle);\n\n\treturn std::make_pair(vec, angle);\n}\n\n\n/**\n * rotation axis -> quat\n * @see (Desktop Bronstein 2008), formula (4.193)\n * @see (Bronstein 2008), ch. 4, pp. 301-302\n * @see https://en.wikipedia.org/wiki/Quaternion#Exponential,_logarithm,_and_power_functions\n * @see https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation\n */\ntemplate\nt_quat rotation_quat(const t_vec& vec, typename t_vec::value_type angle)\nrequires is_quat && is_vec\n{\n\tusing T = typename t_vec::value_type;\n\n\tconst T s = std::sin(T(0.5)*angle);\n\tconst T c = std::cos(T(0.5)*angle);\n\tconst T n = norm(vec);\n\n\tconst T x = s * vec[0] / n;\n\tconst T y = s * vec[1] / n;\n\tconst T z = s * vec[2] / n;\n\tconst T r = c;\n\n\treturn t_quat{r, x,y,z};\n}\n\n\n/**\n * quaternion to rotate vec0 into vec1\n */\ntemplate\nt_quat rotation_quat(const t_vec& _vec0, const t_vec& _vec1)\nrequires is_quat && is_vec\n{\n\tusing T = typename t_vec::value_type;\n\n\tt_vec vec0 = _vec0 / norm(_vec0);\n\tt_vec vec1 = _vec1 / norm(_vec1);\n\n\t// parallel vectors -> do nothing\n\tif(equals(vec0, vec1))\n\t{\n\t\treturn unit_quat();\n\t}\n\n\t// antiparallel vectors -> rotate about any perpendicular axis\n\telse if(equals(vec0, -vec1))\n\t{\n\t\tt_vec vecPerp = create({ vec0[2], T{0}, -vec0[0] });\n\t\treturn rotation_quat(vecPerp, pi);\n\t}\n\n\t// rotation axis from cross product\n\tt_vec vecaxis = cross({vec0, vec1});\n\n\tT dC = inner(vec0, vec1);\n\tT dS = norm(vecaxis);\n\n\t// rotation angle\n\tT dAngle = std::atan2(dS, dC);\n\n\treturn rotation_quat(vecaxis, dAngle);\n}\n\n\ntemplate\nt_quat rotation_quat_x(typename t_quat::value_type angle)\nrequires is_quat\n{\n\tusing T = typename t_quat::value_type;\n\treturn t_quat{std::cos(T(0.5)*angle), std::sin(T(0.5)*angle), T(0), T(0)};\n}\n\n\ntemplate\nt_quat rotation_quat_y(typename t_quat::value_type angle)\nrequires is_quat\n{\n\tusing T = typename t_quat::value_type;\n\treturn t_quat{std::cos(T(0.5)*angle), T(0), std::sin(T(0.5)*angle), T(0)};\n}\n\n\ntemplate\nt_quat rotation_quat_z(typename t_quat::value_type angle)\nrequires is_quat\n{\n\tusing T = typename t_quat::value_type;\n\treturn t_quat{std::cos(T(0.5)*angle), T(0), T(0), std::sin(T(0.5)*angle)};\n}\n\n\n\n/**\n * XYZ euler angles -> quat\n * @see (Kuipers 2002), pp. 166-167\n */\ntemplate\nt_quat euler_to_quat_xyz(\n\ttypename t_quat::value_type phi, typename t_quat::value_type theta, typename t_quat::value_type psi)\nrequires is_quat\n{\n\tt_quat q1 = rotation_quat_x(phi);\n\tt_quat q2 = rotation_quat_y(theta);\n\tt_quat q3 = rotation_quat_z(psi);\n\n\treturn q3 * q2 * q1;\n}\n\n\n/**\n * ZXZ euler angles -> quat\n * @see (Kuipers 2002), pp. 166-167\n */\ntemplate\nt_quat euler_to_quat_zxz(\n\ttypename t_quat::value_type phi, typename t_quat::value_type theta, typename t_quat::value_type psi)\nrequires is_quat\n{\n\tt_quat q1 = rotation_quat_z(phi);\n\tt_quat q2 = rotation_quat_x(theta);\n\tt_quat q3 = rotation_quat_z(psi);\n\n\treturn q3 * q2 * q1;\n}\n\n\n/**\n * quat -> XYZ euler angles\n * @see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles\n */\ntemplate\nstd::vector\nquat_to_euler_xyz(const t_quat& quat)\nrequires is_quat\n{\n\tusing T = typename t_quat::value_type;\n\tT q[] = { quat.R_component_1(), quat.R_component_2(),\n\t\tquat.R_component_3(), quat.R_component_4() };\n\n\t// formulas from:\n\t// http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles\n\tT phi = std::atan2(T(2)*(q[0]*q[1] + q[2]*q[3]), T(1)-T(2)*(q[1]*q[1] + q[2]*q[2]));\n\tT theta = std::asin(T(2)*(q[0]*q[2] - q[3]*q[1]));\n\tT psi = std::atan2(T(2)*(q[0]*q[3] + q[1]*q[2]), T(1)-T(2)*(q[2]*q[2] + q[3]*q[3]));\n\n\treturn std::vector({ phi, theta, psi });\n}\n\n\n/**\n * @see (Desktop Bronstein 2008), formula (4.217)\n * @see (Bronstein 2008), p. 308, formula (4.165)\n */\ntemplate\nt_quat stereo_proj(const t_quat& quat)\nrequires is_quat\n{\n\tusing T = typename t_quat::value_type;\n\treturn (T{1}+quat) / (T{1}-quat);\n}\n\n\n/**\n * @see (Desktop Bronstein 2008), formula (4.217)\n * @see (Bronstein 2008), p. 308, formula (4.165)\n */\ntemplate\nt_quat stereo_proj_inv(const t_quat& quat)\nrequires is_quat\n{\n\tusing T = typename t_quat::value_type;\n\treturn (T{1}-quat) / (T{1}+quat);\n}\n\n// ----------------------------------------------------------------------------\n\n\n\n// ----------------------------------------------------------------------------\n// Fourier transform\n// @see (Scarpino 2011), ch. 14 for infos.\n// ----------------------------------------------------------------------------\n\n/**\n * dft\n * @see http://www.fftw.org/fftw3_doc/The-1d-Discrete-Fourier-Transform-_0028DFT_0029.html#The-1d-Discrete-Fourier-Transform-_0028DFT_0029\n */\ntemplate,\n\ttemplate class t_cont = std::vector>\nrequires is_complex\nt_cplx dft_coeff(int k, const t_cont& invec, bool bInv = false)\n{\n\tconst std::size_t N = invec.size();\n\n\tt_cplx imag(0., 1.);\n\tt_cplx f(0., 0.);\n\n\tfor(std::size_t j=0; j*T(j)*T(k)/T(N);\n\t\tif(bInv) dv = -dv;\n\t\tf += invec[j] * (std::cos(dv) + imag*std::sin(dv));\n\t}\n\n\treturn f;\n}\n\n\n/**\n * dft\n * @see http://www.fftw.org/fftw3_doc/The-1d-Discrete-Fourier-Transform-_0028DFT_0029.html#The-1d-Discrete-Fourier-Transform-_0028DFT_0029\n */\ntemplate,\n\ttemplate class t_cont = std::vector>\nrequires is_complex\nt_cont dft(const t_cont& invec, \n\tbool bInv = false, bool bNorm = false)\n{\n\tconst std::size_t N = invec.size();\n\tt_cont outvec;\n\toutvec.resize(N);\n\n\tfor(std::size_t k=0; k(k, invec, bInv);\n\n\t\tif(bNorm && bInv)\n\t\t\toutvec[k] /= N;\n\t}\n\n\treturn outvec;\n}\n\n\n/**\n * fft\n * @see (Scarpino 2011), ch. 14.\n */\ntemplate>\nrequires is_complex\nt_cplx fft_factor(T N, T k, bool bInv = false)\n{\n\tT ph = bInv ? -1 : 1.;\n\n\tT c = std::cos(T(2)*pi*k/N * ph);\n\tT s = std::sin(T(2)*pi*k/N * ph);\n\n\treturn t_cplx{c, -s};\n}\n\n\n/**\n * fft\n * @see (Scarpino 2011), ch. 14.\n */\ntemplate,\n\ttemplate class t_cont = std::vector>\nrequires is_complex\nt_cont fft_reorder(const t_cont& vecIn)\n{\n\tt_cont vecIdx =\n\t\tbit_reverse_indices(vecIn.size());\n\n\tt_cont vecInRev;\n\tvecInRev.reserve(vecIn.size());\n\n\tfor(std::size_t i=0; i,\n\ttemplate class t_cont = std::vector>\nrequires is_complex\nt_cont fft_merge(const t_cont& vecIn, bool bInv = false)\n{\n\tconst std::size_t N = vecIn.size();\n\tconst std::size_t N2 = N/2;\n\n\tif(N==0 || N==1)\n\t\treturn vecIn;\n\n\tauto split_vec = [](const t_cont& vec)\n\t\t-> std::pair, t_cont>\n\t{\n\t\tstd::size_t N = vec.size();\n\n\t\tt_cont vec1, vec2;\n\t\tvec1.reserve(N/2);\n\t\tvec2.reserve(N/2);\n\n\t\tfor(std::size_t i=0; i vec1 = fft_merge(pair.first, bInv);\n\tt_cont vec2 = fft_merge(pair.second, bInv);\n\n\tt_cont vecOut;\n\tvecOut.resize(N);\n\n\tfor(std::size_t i=0; i(N, i, bInv);\n\t\tvecOut[N2+i] = vec1[i] + vec2[i]*fft_factor(N, N2+i, bInv);\n\t}\n\n\treturn vecOut;\n}\n\n\n/**\n * fft\n * @see (Scarpino 2011), ch. 14.\n */\ntemplate,\n\ttemplate class t_cont = std::vector>\nrequires is_complex\nt_cont fft(const t_cont& vecIn,\n\tbool bInv = false, bool bNorm = false)\n{\n\tconst std::size_t n = vecIn.size();\n\tt_cont vecOut;\n\tvecOut.resize(n);\n\n\tvecOut = fft_reorder(vecIn);\n\tvecOut = fft_merge(vecOut, bInv);\n\n\tif(bInv && bNorm)\n\t\tfor(t_cplx& c : vecOut)\n\t\t\tc /= n;\n\n\treturn vecOut;\n}\n// ----------------------------------------------------------------------------\n}\n\n// ----------------------------------------------------------------------------\n\n#endif\n", "meta": {"hexsha": "77f0a002d863f7efdd4e59361607ae9f97fa4c3d", "size": 216610, "ext": "h", "lang": "C", "max_stars_repo_path": "libs/maths.h", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/maths.h", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/maths.h", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 25.9537502995, "max_line_length": 199, "alphanum_fraction": 0.6362540972, "num_tokens": 68871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.41224208673435225}} {"text": "//Causal FIR filtering of each row or col of X according to dim.\n\n//FIR impulse responses are given in matrix B.\n//For dim=0, X is NxT and B is NxL\n//For dim=1, X is TxN and B is LxN\n//where N is the number of neurons, T the number of time points, and L the FIR filter order.\n\n#include \n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint fir_s (float *Y, const float *X, const float *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim);\nint fir_d (double *Y, const double *X, const double *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim);\nint fir_c (float *Y, const float *X, const float *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim);\nint fir_z (double *Y, const double *X, const double *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim);\n\n\nint fir_s (float *Y, const float *X, const float *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim)\n{\n const float z = 0.0f;\n \n //Initialize Y to 0\n cblas_scopy((int)(N*T),&z,0,Y,1);\n\n if (N==1u)\n {\n for (size_t l=0u; l\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"libgad.h\"\n#include \"KdTree.h\"\n#include \"./lmmin.h\"\n#include \"./lm_eval.h\"\n#define\tPI 3.14159265358979323846\n#define GAP2BORDER 16000 //min distance to boarders to ignore periodic boundaries\n#define INCLUDE 0 //(friends + INCLUDE*kpc/h) are used to determine CM\n#define TRACE_FACTOR 2.0 //TRACE_FACTOR times virial radius will be traced back to IC\n#define h0 0.72\n#define VIROD 200 \n#define DIM 512\n#define ENVDENSRAD (4000 * h0)\n#define\tMIN(a, b) ((a)<(b)?(a):(b))\n#define\tMAX(a, b) ((a)>(b)?(a):(b))\n#define ABS(a) ((a) >= 0 ? (a) : -(a))\n#define CMP(a,b) ((a)>(b)?(1):(-1))\n#define PB(a,b) ((a)>(b)?(a-b):(a))\n#define MOVE(a,b) PB(a+b/2,b)\n#define MOVEB(a) MOVE((a),boxsz)\n#define MV(a,b) ((a)+(b)/2)%(b)\n//#define SQR(x) (x)*(x)\n#define SOFTENING 0\n#define G 6.6742e-11\n#define Msun 1.989e30\n#define kpc 3.08567758128e19\n#define DEBUG 1\n\n#define VA_USE_PART_TYPE 2\n#define CM_USE_PART_TYPE 2\n#define INERTIA_USE_PART_TYPE 2\n#define kNN 50\n\ndouble cdens;\n\nstruct particle {int ind;float dist;};\nclock_t t[2];\n\n\nvoid usage()\n{\n \t fprintf(stderr,\"TrHalo v0.05\\n\");\n\t fprintf(stderr,\" -f -i \\n\");\n\t fprintf(stderr,\" -m -n or -cm \\n\");\n\t fprintf(stderr,\" if you want to search for CM in an area around the given coordinates\\n\");\n\t fprintf(stderr,\" add -sr to include particles for the search with distance to cm < radius\\n\");\n\t fprintf(stderr,\" -gr -tf \\n\");\n\t fprintf(stderr,\" -jr -cut \\n\");\n\t fprintf(stderr,\" -pb \\n\");\n \t fprintf(stderr,\" -n \\n\");\n \t fprintf(stderr,\" -cid
\\n\");\n \t fprintf(stderr,\" -trid \\n\");\n \t fprintf(stderr,\" -r \\n\");\n \t fprintf(stderr,\" -ui \\n\");\n \t fprintf(stderr,\" -gap \\n\");\n \t fprintf(stderr,\" -mcnt \\n\");\n \t fprintf(stderr,\" -sd \\n\");\n\n\t exit(1);\n}\n\n\ndouble fit_fct(double t, double *p)\n{\n return log10((p[0]) / ((t/p[1]) * SQR(1+t/p[1])));\n}\n\n// void printout ( int n_par, double* par, int m_dat, double* fvec, \n// void *data, int iflag, int iter, int nfev )\n// {\n// // dummy function to catch fitting output\n// }\n\n\nfloat step()\n{\n float tm;\n t[1]=clock();\n tm=(float)(t[1]-t[0])/CLOCKS_PER_SEC;\n t[0]=clock();\n return tm;\n}\n\n/*\nint cmp (struct particle *a, struct particle *b)\n{\n if (a[0].dist > b[0].dist) return 1; else return -1;\n}\n*/\nint cmp (const void *first, const void *second)\n{\n struct particle *a = (struct particle*) first;\n struct particle *b = (struct particle*) second;\n if (a->dist > b->dist) return 1;\n else if (a->dist < b->dist) return -1;\n else return 0;\n}\n\nint cmpind (const void *first, const void *second)\n{\n struct particle *a = (struct particle*) first;\n struct particle *b = (struct particle*) second;\n if (a->ind > b->ind) return 1;\n else if (a->ind < b->ind) return -1;\n else return 0;\n}\n\nint compare (float *a, float *b)\n{\n if (*a > *b) return 1; else return -1;\n}\n\nint coord512 (int *result, long index)\n{\n int c[3];\n int i;\n result[0]=floor(index%262144/512.0);\n result[1]=(index%512);\n result[2]=floor(index/262144.0);\n for (i=0; i<3; i++)\n if ((result[i]<0) || (result[i]>512)) return 1;\n return 0;\n}\n\n\nint main (int argc, char *argv[])\n{\n typedef float fltarr[3];\n struct particle *part, *vpart;\n gadpart *P;\n struct header ic,evolved, out;\n FILE *fp;\n char vmfile[256],icfile[256],evolvedfile[256],snfile[256],friendsfile[256],idlfile[256],gridfile[256],jrfile[256], gadfile[256], hname[256], parfile[256], idfile[256], datfile[256];\n unsigned int numpart=0, nummass=0;\n int blocksize,i,j,k,l,m,dum,dum2,tr_halo=0,tr_halo_cnt = 0,id,halo,checknpart,mindum,nhalo,count,notrace=1;\n int *tr_halo_id,*tr_halo_i,*tr_halo_i_dum, ca[3], size[3];\n // fltarr *pos_ev,*pos_ic,*vel, *outpos, *outvel;\n fltarr *pos_ic;\n fltarr shift, diff;\n float *mass_ev, *mass_dum,*mass_ic, *outmass,dist,maxdist,*distance,halomass,halorad, halolmd;\n double posdum,max[3],min[3],srad=0, icmin[3], icmax[3], scm[3];\n double lmd,vcm[3]={0,0,0},jcm[3]={0,0,0},J[3]={0,0,0}, torq[3],rdum[3], vdum[3], massdum;\n int *id_ev, *outid,*iclus, halonpart;\n float tm,linkle,od, tr_factor;\n double mdens,boxsz,cm[3]={0,0,0}, expcm[3], masstot, gridsize, rlog[50], p[50], err[50], d, rad_ratio=0.3;\n short pb[3]={0,0,0};\n int minbox[3], maxbox[3], szbox[3], ***grid, boxind[3], alignf, mincnt=100;\n int nfun, npar, indmax[3], indmin[3], dojr=0, docut=0, vcnt, starsonly=0, dmonly=1, doidl=1, start, end, use_inertia=0, use_va, use_cm, cmset=0, nopb=0, cid=0, traceid=0, gal_all=0, addbh=0, printcm=0;\n double par[2],ddum, dx512, ddum1, totj, envdens, sqrenvdensrad, bgdens, sfl=SOFTENING, meff, halfmrad, effrad;\n double GAP=GAP2BORDER, searchdist=0;\n \n t[0]=clock();\n dx512=72000.0/512.0;\n \n if (DEBUG) printf(\"DEBUG-Output enabled\\n\");fflush(stdout);\n\n //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n //filenames are ignored if given as command line parameters in the same order\n\n strcpy(vmfile,\"\");\n strcpy(gridfile,\"\");\n strcpy(parfile,\"halodata.txt\");\n strcpy(evolvedfile,\"\");\n strcpy(icfile,\"\");\n strcpy(idlfile,\"\");\n tr_factor=TRACE_FACTOR;\n use_inertia=INERTIA_USE_PART_TYPE;\n use_va=VA_USE_PART_TYPE;\n use_cm=CM_USE_PART_TYPE;\n // tr_halo=123;\n //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n i=1;\n if (1==argc) usage();\n while (i0)\n {\n fread(&blocksize,sizeof(int),1,fp); //read particle masses of evolved snapshot file\n fread(&mass_dum[0],sizeof(float),nummass,fp);\n fread(&blocksize,sizeof(int),1,fp);\n }\n\n fclose(fp);\n*/\n numpart= readgadget_part(evolvedfile, &evolved, &P);\n if (numpart==0) \n\t{\n\t extern int libgaderr;\n\t fprintf(stderr,\"LibGad Error Code: %d\\n\", libgaderr);\n\t exit(libgaderr);\n\t}\n masstot=0;\n j=0;\n for (i=0; i< numpart; i++) \n {\n masstot+=P[i].mass;\n if ((cid) && P[i].id==cid )\n {\n\t for (j=0; j<3; j++) cm[j]=P[i].pos[j];\n }\n } \n mdens=masstot/pow(evolved.boxsize*evolved.time,3);\n\n cdens=(2.78e-8);\n cdens=cdens*(evolved.omegal+evolved.omega0*pow(evolved.time,-3));\n bgdens=cdens*evolved.omega0;\n dum=0;\n for (i=0; i<5; i++)\n {\n dum+=evolved.npart[i];\n if (DEBUG)\n if (evolved.npart[i]>0) printf(\"%d %f %f\\n\", i, P[dum-1].mass, P[dum].mass);\n }\n\n if (DEBUG) printf(\"readin evolved %.2f\\n\",step());fflush(stdout);\n printf(\"snapshot %s\\n\", evolvedfile);\n printf(\"ucm %d ui %d uva %d\\n\", use_cm, use_inertia, use_va);\n if (strcmp(vmfile,\"\")!=0)\n {\n fp=fopen(vmfile,\"r\"); //read virialmassfile\n fscanf(fp,\"%d %d %s %s\", &checknpart, &nhalo, &snfile, &friendsfile);\n if (strcmp(snfile,evolvedfile)!=0) \n\t{\n\t printf(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\");\n\t printf(\"Warning: Evolved Snapshotfile and the one specified in %s are not identical!\\n\",vmfile);\n\t printf(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\");\n\t}\n if (tr_halo > nhalo)\n\t{\n\t fprintf(stderr,\"Illegal Halo index\\n\");\n\t exit(2);\n\t}\n j=1;\n while (j < tr_halo)\n\t{\n\t fscanf(fp,\"%d %f %d %f %f %f %f %f\", &j, &halomass, &halonpart, &halolmd, &halorad, &cm[0], &cm[1], &cm[2]);\n\t}\n fclose(fp);\n }\n\n if ( (!cm[0]) && (!cm[1]) && (!cm[2]) && !(cmset) )\n {\n fprintf(stderr,\"Neither -m nor -cm option used\\n\");\n exit(3);\n }\n if ( (!cm[0]) && (!cm[1]) && (!cm[2])) \n {\n nopb=1;\n // tr_factor=1.0;\n }\n /*\n printf(\"n %d\\n\",j);\n printf(\"cm %f %f %f\\n\",cm[0], cm[1], cm[2]);\n printf(\"friendsfile %s\\n\",friendsfile);\n printf(\"snfile %s\\n\",snfile);\n printf(\"n %d\\n\",tr_halo);\n */\n\n tr_halo_cnt=0;\n masstot=0;\n\n if (GAP==GAP2BORDER) \n {\n GAP = evolved.boxsize/4.;\n }\n\n for (k=0; k<3; k++) //check whether periodic boundaries are needed\n {\n if ( ((cm[k](evolved.boxsize-GAP) || pb[k])) && (!nopb))\n\t{\n\t pb[k]=1;\n\t cm[k]=MOVE(cm[k],boxsz);\n\t}\n }\n if (DEBUG) printf(\"search center \\n\");fflush(stdout);\n for (i=0; i<3; i++) scm[i]=cm[i];\nif (srad>0)\n {\n tr_halo_id=(int *)malloc(numpart*sizeof(int));\n tr_halo_i =(int *)malloc(numpart*sizeof(int));\n maxdist=srad*srad;\n if (dmonly) {start=evolved.npart[0]; end=evolved.npart[0]+evolved.npart[1];}\n else if (starsonly) {start=evolved.npart[0]+evolved.npart[1]+evolved.npart[2]+evolved.npart[3]; end=start+evolved.npart[4];}\n else {start=0; end=numpart;}\n\n {start=0; end=numpart;}\n if ((end-start) (MOVE(cm[k],boxsz)+GAP )) ) dum=0;\n\t } else {\n\t posdum=P[i].pos[k];\n\t if ( (posdum < (cm[k]-GAP)) || (posdum > (cm[k]+GAP)) ) dum=0;\n\t }\n\t}\n\n if (dum) \n\t{\n\t tr_halo_id[tr_halo_cnt]=P[i].id;\n\t tr_halo_i[tr_halo_cnt++]=i;\n\t}\n }\n\n tr_halo_id=realloc(tr_halo_id,sizeof(int)*tr_halo_cnt);\n tr_halo_i =realloc(tr_halo_i ,sizeof(int)*tr_halo_cnt);\n \n // for (j=0; j<3; j++) printf(\"min %f max %f cm %f\\n\", min[j],max[j],cm[j]);\n // pos_dum=(fltarr *)malloc(sizeof(fltarr)*numpart);\n tr_halo_i_dum =(int *)malloc(sizeof(int)*numpart);\n count=0; \n\n\n for (i=0; i < numpart; i++) //\n {\n dum=1;\n for (j=0; j<3; j++) \n\t{\n\t if (pb[j]) \n\t {\n\t if (((MOVE(P[i].pos[j],boxsz)+INCLUDE) < min[j]) || ((MOVE(P[i].pos[j],boxsz)-INCLUDE) > max[j])) dum=0;\n\t }\n\t else {if (((P[i].pos[j]+INCLUDE) < min[j]) || ((P[i].pos[j]-INCLUDE) > max[j])) dum=0;}\n\t}\n if (dum) \n\t{\n\t //\t for (j=0; j<3; j++) pos_dum[count][j]=P[i].pos[j];\n\t tr_halo_i_dum[count]=i;\n \t count++;\n\t}\n }\n maxdist=0;\n for (j=0; j<3; j++) \n {\n //if (pb[j]) maxdist+=pow((MOVE(max[j],boxsz)-MOVE(min[j],boxsz))/2,2);else\n maxdist+=pow((max[j]-min[j])/2,2);\n }\n maxdist=sqrt(maxdist)*2;\n */\n\nif (srad>0)\n{\n double cvel[3]={0.,0.,0.};\n maxdist=srad;\n count=tr_halo_cnt;\ndo\n {\n // printf(\"Center of Mass for halo %d : %f %f %f particles: %d rad %f\\n \", tr_halo, cm[0], cm[1], cm[2],count,maxdist);\n\n //pos_dum=realloc(pos_dum,sizeof(fltarr)*count);\n //tr_halo_i_dum=realloc(tr_halo_i_dum,sizeof(int)*count);\n\n //printf(\"ja\\n\");fflush(stdout);\n\n masstot=0;\n maxdist*=0.92;\n for (j=0; j<3; j++){rdum[j]=cm[j];}\n cm[0]=0;\n cm[1]=0;\n cm[2]=0;\n // printf(\"%d\\n\",count);\n for (i=0; i < count; i++)\n {\n for (j=0; j<3; j++) \n\t{\n\t if (pb[j]) cm[j]+=MOVE(P[tr_halo_i[i]].pos[j],boxsz)*P[tr_halo_i[i]].mass;\n\t else cm[j]+=P[tr_halo_i[i]].pos[j]*P[tr_halo_i[i]].mass;\n\t}\n masstot+=P[tr_halo_i[i]].mass;\n // if (i<10)\n // printf(\"%f %f %f !\\n\", P[tr_halo_i[i]].pos[0]*P[tr_halo_i[i]].mass, cm[1], cm[2]);fflush(stdout);\n //printf(\"%d\\n\",i);fflush(stdout);\n }\n\n // printf(\"%f %f %f !\\n\", cm[0], cm[1], cm[2]);fflush(stdout);\n\n for (j=0; j<3; j++) cm[j]=cm[j]/(masstot);\n \n dum=0;\n for (i=0; i < count; i++) //\n {\n dist=0;\n for (j=0; j<3; j++) \n\t{\n\t if (pb[j]) dist += pow((MOVE(P[tr_halo_i[i]].pos[j],boxsz)-cm[j]),2);\n\t else dist += pow((P[tr_halo_i[i]].pos[j]-cm[j]),2);\n\t}\n \n dist=sqrt(dist);\n if (dist < maxdist) \n\t{\n\t //\t for (j=0; j<3; j++) pos_dum[dum][j]=pos_dum[i][j];\n\t tr_halo_i[dum]=tr_halo_i[i];\n\t dum++;\n\t}\n }\n count=dum;\n if ((count<50) && (cvel[0]==0))\n {\n masstot=0;\n for (i=0; i< count; i++)\n\t{\n\t for (j=0; j<3; j++) \n\t {\n\t cvel[j]+=P[tr_halo_i[i]].vel[j]*P[tr_halo_i[i]].mass;\n\t }\n\t masstot+= P[tr_halo_i[i]].mass;\n\t}\n for (j=0; j<3; j++) cvel[j]=cvel[j]/(masstot);\n printf(\"%d particles for cvel-calculation\\n\",count);\n printf(\"Central Velocity %10.4f %10.4f %10.4f\\n\", cvel[0], cvel[1], cvel[2] );\n }\n // printf(\"count: %d cm: %f %f %f change: %f% f% f rad: %f \\n\",count, cm[0],cm[1], cm[2], cm[0]-rdum[0], cm[1]-rdum[1], cm[2]-rdum[2], maxdist);\n } while (count>5);\n \n\n\n if (addbh)\n {\n if (use_cm!=16) printf(\"Black holed not centered on stars, are you sure? (think about using -ucm 16)\\n\");\n for (j=0; j<3; j++)\n {\n\t P[numpart].pos[j]=cm[j];\n\t P[numpart].vel[j]=cvel[j];\n }\n P[numpart].mass=P[0].mass;\n P[numpart].id=numpart+1;\n out=evolved;\n out.npart[5]++;\n out.nall[5]++;\n char outfilename[256];\n sprintf(outfilename,\"%s-bh\", evolvedfile);\n // writegadget(outfilename, out, pos_ev, vel, id_ev, mass_ev);\n writegadget_part(outfilename, out, P);\n }\n\n }\n/*\n//printf(\"CM found %.2f now sort by distance and calculate virial radius+mass\\n\",step());\n// free(pos_dum);\n free(tr_halo_i_dum);\n \n \npart=(struct particle *)malloc(sizeof(struct particle)*tr_halo_cnt);\nfor (i=0; i< tr_halo_cnt; i++) \n {\n\t dist=0;\n\t for (j=0; j<3; j++) \n\t {\n\t if (pb[j]) dist += pow((MOVE(P[tr_halo_i[i]].pos[j],boxsz)-cm[j]),2);\n\t else dist += pow((P[tr_halo_i[i]].pos[j]-cm[j]),2);\n\t }\n\t part[i].dist=sqrt(dist);\n\t //part[i].mass=P[tr_halo_i[i]].mass;\n\t //part[i].id=P[tr_halo_i[i]].id;\n\t part[i].ind=tr_halo_i[i];\n } \n qsort(&part[0],tr_halo_cnt,sizeof(struct particle),(void *)cmp);\n masstot=0;\n i=0;\n od=201;\n while (((od > 200) && (imaxdist) break;\n\t }\n\n\t if (dist < sqrenvdensrad)\n\t {\n\t envdens+=P[i].mass;\n\t }\n\n\t if (dist < maxdist) \n\t {\n\t dist=sqrt(dist);\n\t part[count].dist=dist;\n\t part[count++].ind=i;\n\t if (dist < effrad)\n\t {\n\t\t dum2=0;\n\t\t for (m=0; m<6; m++)\n\t\t {\n\t\t dum2+=evolved.npart[m];\n\t\t if (dum2>i) break;\n\t\t }\n\t\t if ((1< VIROD) || (i<5)) //Add mass until overdensity drops below 200\n {\n\t int ind = part[i].ind;\n\t masstot+=P[part[i].ind].mass;\n\t if ((P[ind].type == 0) ||(P[ind].type == 4)) \n\t {\n\t b_mass += P[ind].mass;\n\t if (P[ind].type == 0) gas_mass += P[ind].mass;\n\t else star_mass += P[ind].mass;\n\t } else \n\t {\n\t dm_mass+= P[ind].mass;\n\t }\n\t od=masstot/(pow(part[i].dist*evolved.time,3)*(4.0/3.0)*PI*cdens);\n\t //printf(\"i %d od %f\\n\",i,od);\n\t vpart[i].dist=part[i].dist;\n vpart[i].ind=part[i].ind;\n\t i++;\n\t if (i > count)\n\t {\n\t fp=fopen(\"error_trhalo.dat\",\"a\");\n\t fprintf(fp,\"Halo %d is making trouble\\n\",tr_halo);\n\t fclose(fp);\n\t printf(\"halo %d is making trouble\\n\",tr_halo);\n\t break;\n\t }\n\t if (i>numpart) {i--;break;}\n\t if ((part[i].dist > searchdist) && (searchdist)) break;\n }\n if (DEBUG) printf(\"Virial Radius found count %d\\n\", count);fflush(stdout); \n masstot-=P[part[i-1].ind].mass;\n if ((P[part[i-1].ind].type == 0) ||(P[part[i-1].ind].type == 4)) \n\t {\n\t b_mass -= P[part[i-1].ind].mass;\n\t } else \n\t {\n\t dm_mass-= P[part[i-1].ind].mass;\n\t }\n dum=i-1; \n vcnt=i;\n halorad=part[vcnt-1].dist;\n envdens=envdens/((4.0/3.0)*PI*pow(ENVDENSRAD*evolved.time,3));\n vpart=realloc(vpart,sizeof(struct particle)*vcnt);\n qsort(&vpart[0],vcnt,sizeof(struct particle),(void *)cmpind);\n\n {\n gadpart_dist *tmppart= malloc (sizeof(gadpart_dist) * vcnt);\n for (i=0; i< vcnt; i++)\n\t {\n\t tmppart[i].dist=part[i].dist;\n\t tmppart[i].part=P[part[i].ind];\n\t }\n double par[2]={0.005,20};\n double rcs;\n double conc = nfwfit(par, tmppart, vcnt, halorad, sfl, &rcs); \n printf(\"NFW: %f %f\\nc %f\\nRs %f\\n\", par[0], par[1], conc, rcs);\n free(tmppart);\n }\n\n for (j=0; j<3; j++) \n {\n if (pb[j])\n {\n\t cm[j]=MOVE(cm[j],boxsz);\n\t printf(\"!!!periodic boundaries used in Dimension %d !!!\\n\",j);\n }\n }\n\n printf(\"\\n halo %5d consists of %5d particles, virial Mass/h %5.2f\\n rad %5.2f od %4.2f\\n\",tr_halo,vcnt,masstot,part[i-1].dist,od);\n printf(\" Baryonic Mass/h %5.2f\\n DM Mass/h %5.2f \\n\\n\",b_mass, dm_mass);\n printf(\"Center of Mass: %10.4f %10.4f %10.4f\\n\",cm[0] ,cm[1] ,cm[2]);\n printf(\"Shift: %10.4f %10.4f %10.4f\\n\",cm[0]-scm[0],cm[1]-scm[1],cm[2]-scm[2]);\n if (printcm)\n {\n FILE *filep= fopen(\"cm.dat\", \"w\");\n fprintf(filep, \"%f %f %f\\n\",cm[0],cm[1],cm[2]);\n fclose(filep);\n }\n printf(\"particles in box: %d\\n\",count);\n printf(\"Environmental Density (R = %f ): %g\\n\", ENVDENSRAD,(envdens/bgdens)-1);\n if (DEBUG) printf(\"... \\n\");fflush(stdout); \n tr_halo_id=(int *)malloc(count*sizeof(int));\n tr_halo_i =(int *)malloc(count*sizeof(int));\n tr_halo_cnt=0;\n\n if (docut)\n {\n gadpart *OUT= (gadpart * ) malloc (sizeof(gadpart)*vcnt);\n /* outpos =(fltarr *)malloc(sizeof(fltarr)*vcnt);\n outvel =(fltarr *)malloc(sizeof(fltarr)*vcnt);\n outid =(int *)malloc(sizeof(int)*vcnt);\n outmass =(float *)malloc(sizeof(float)*vcnt);\n */\n out=evolved;\n for (i=0; i<6; i++)\n {\n\t out.npart[i]=0;\n\t out.nall[i]=0;\n }\n i=0;\n while (ipart[i].ind) break;\n }\n if ((distsfl)) \n {\n\t d=log10(dist);\n\t j=floor(d/(log10(halorad)/50));\n\t err[j]++;\n\t p[j]+=P[part[i].ind].mass;\n }\n if ( ((1<sfr;\n\t }\n\t else if (m==1) DMmass+= P[part[i].ind].mass;\n }\n i++;\n }\n meanage /= nstars_gal;\n double innerdens=innertotm/(pow((halorad * 0.1)*evolved.time,3)*(4.0/3.0)*PI);\n printf(\"hmeff: %f effrad: %f\\n\", hmeff, effrad);\n printf(\"Galaxy mass (M_star < 10 %% Rvir): %f \\n\", galmass);\n printf(\"mean age: %g \\n\", meanage);\n printf(\"SFR (< 10 %% Rvir): %g \\n\", gsfr);\n printf(\"specific SFR (< 10 %% Rvir): %g \\n\", gsfr / galmass);\n printf(\"Gas mass (M_gas < 10 %% Rvir): %f \\n\", gasmass);\n printf(\"darkmatter mass (M_gas < 10 %% Rvir): %f \\n\", DMmass);\n printf(\"Total mass < 10 %% Rvir: %f \\n\", innertotm);\n printf(\"overdensity < 10 %% Rvir: %g\\n\", innerdens/bgdens - 1);\n printf(\"density < 10 %% Rvir: %g\\n\", innerdens);\n if (DEBUG) printf(\"lambda calculation: \\n\");fflush(stdout); \n nfun=0;\n k=0;\n\n /*fitting\n\n d=log10(halorad)/50;\n for (j=0; j<50; j++)\n {\n if (err[j]!=0)\n {\n\t err[nfun]=(1/(sqrt(err[j])));\n\t //\t err[nfun]=(1/((err[j])));\n\t if (k==0) {\n rlog[nfun]=(pow(10, ((j+1)*d )))/2;\n p[nfun]=p[j]/((4.0/3.0)* PI * (pow(10, ((j+1)*d*3))));\n // printf(\"j %d\\n\", j);\n\n }\n else {\n\t ddum=p[j];\n\t rlog[nfun]=(pow(10, ((j+1)*d )) + pow(10, (k*d)))/2;\n\t p[nfun]=p[j]/((4.0/3.0)* PI * (pow(10, ((j+1)*d*3)) - pow(10, (k*d*3))));\n\t if (p[nfun]<0) printf(\"%g %e %e \\n\", ddum, pow(10, ((j+1)*d*3)), pow(10, (k*d*3)) );\n }\n \n// if (rlog[nfun] < SOFTENING) \n// {\n//\t err[nfun]*=10;\n//\t printf(\"S %d\\n\", nfun);\n// }\n \n k=j+1;\n nfun++;\n } else {\n\t //\t p[j]=0;\n\t //\t err[j]=1e10;\n }\n }\n \n for (j=0; j numpart) tr_halo_cnt=numpart;\n printf(\"number of particles within %g times virial radius %d\\n trhalo_cnt %d\\n\", tr_factor ,i, tr_halo_cnt);\n if (doidl) fclose(fp);\n if (count!=tr_halo_cnt)\n {\n tr_halo_id=realloc(tr_halo_id,sizeof(int)*tr_halo_cnt);\n tr_halo_i =realloc(tr_halo_i ,sizeof(int)*tr_halo_cnt);\n }\n\n if (DEBUG) printf(\"... \\n\");fflush(stdout); \n /**********************************************************************************************************************************************/\n\n // for (l=-5; l<=5; l++)\n \n count=vcnt; //+l*300;\n for (k=0; k<3; k++)\n {\n jcm[k]=0;\n vcm[k]=0;\n J[k]=0;\n }\n totj=0;\n massdum=0;\n\n for (j=0; j < count; j++)\n {\n for (k=0; k<3; k++)\n {\n\t vcm[k]+=(P[part[j].ind].vel[k]*P[part[j].ind].mass);\n\t if (pb[k]) jcm[k]+=(MOVE(P[part[j].ind].pos[k],boxsz)*P[part[j].ind].mass);\n \t else jcm[k]+=(P[part[j].ind].pos[k]*P[part[j].ind].mass);\n }\n massdum+=P[part[j].ind].mass;\n }\n for (k=0; k<3; k++)\n {\n vcm[k]=vcm[k]/massdum;\n jcm[k]=jcm[k]/massdum;\n jcm[k]=jcm[k];\n //test\n //jcm[k]=cm[k];\n }\n if (dojr) fp=fopen(jrfile,\"w\");\n for (j=0; j < count; j++)\n {\n for (k=0; k<3; k++) \n {\n\t if (pb[k]) rdum[k]=MOVE(P[part[j].ind].pos[k],boxsz)-jcm[k];\n\t else rdum[k]=P[part[j].ind].pos[k]-jcm[k];\n\t vdum[k]=P[part[j].ind].vel[k]-vcm[k];\n }\n torq[0]=(rdum[1]*vdum[2]-rdum[2]*vdum[1]);\n torq[1]=(rdum[2]*vdum[0]-rdum[0]*vdum[2]);\n torq[2]=(rdum[0]*vdum[1]-rdum[1]*vdum[0]);\n\n ddum=0;\n for (k=0; k<3; k++) \n {\n\t J[k]+=torq[k]*P[part[j].ind].mass;\n\t ddum+=torq[k]*torq[k];\n }\n totj+=sqrt(ddum)*P[part[j].ind].mass;\n \n ddum=0;\n ddum1=0;\n for (k=0; k<3; k++) {ddum+=SQR(rdum[k]); ddum1+=SQR(torq[k]);}\n if (dojr) fprintf(fp,\"%g %g\\n\", sqrt(ddum), sqrt(ddum1)*P[part[j].ind].mass);\n }\n if (dojr) fclose(fp);\n\n\n lmd=0;\n for (k=0; k<3; k++) {lmd+=J[k]*J[k];}\n 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));\n // lmd=(totj*1e10*(Msun/evolved.hubparam)*1e3*(kpc/evolved.hubparam))/(sqrt(2)*part[count-1].dist*(kpc/evolved.hubparam)*massdum*1e10*(Msun/evolved.hubparam));\n lmd=lmd/sqrt(G*massdum*1e10*(Msun/evolved.hubparam)/(part[count-1].dist*(kpc/evolved.hubparam)));\n\n printf(\"Spin: lambda %e r %g\\n\",lmd, part[count-1].dist);\n \n\n // fp=fopen(parfile,\"w\");\n // fprintf(fp,\"%g %g %g %g \\n\", lmd, par[0], par[1], halorad/par[1] );\n // fclose(fp);\n /**********************************************************************************************************************************************/\n //Determine Halo-Shape\n\n if (use_inertia)\n {\n maxdist=rad_ratio*halorad;\n if (!(use_inertia&2)) \n {\n\t if (gal_all) maxdist=30*evolved.hubparam;\n\t else maxdist=effrad;\n }\n double q=1, s=1, s_old;\n gsl_matrix *I = gsl_matrix_alloc (3, 3);\n gsl_vector *eval = gsl_vector_alloc (3);\n gsl_matrix *evec = gsl_matrix_alloc (3, 3);\n gsl_matrix *LU = gsl_matrix_alloc (3, 3);\n gsl_matrix *inv = gsl_matrix_alloc (3, 3); \n gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (3);\n gsl_matrix *rotation = gsl_matrix_alloc (3, 3);\n gsl_matrix_set_identity(rotation);\n gsl_matrix *resultmatrix = gsl_matrix_alloc (3, 3);\n gsl_matrix_set_zero(I);\n struct gadpart *wpart;\n \n wpart= (struct gadpart *)malloc(sizeof(struct gadpart)*vcnt);\n m=0;\n for (k=0; k < vcnt; k++)\n {\n\t l=part[k].ind;\n\t for (j=0; j < 3; j++)\n\t {\n\t if (pb[j]) wpart[k].pos[j]=MOVEB(P[l].pos[j])-MOVEB(cm[j]);\n\t else wpart[k].pos[j]=P[l].pos[j]-cm[j];\n\t wpart[k].vel[j]=P[l].vel[j];\n\t }\n\t wpart[k].mass=P[l].mass;\n\t wpart[k].id=P[l].id;\n\t dum=0;\n\t for (m=0; m<6; m++)\n\t {\n \t dum+=evolved.npart[m];\n\t if (l 1e-2);\n\n if (docut)\n {\n sprintf( gadfile, \"%s_rot\", hname);\n FILE *matrixf=fopen(gadfile,\"w\");\n gsl_matrix_fwrite (matrixf, rotation);\n fclose(matrixf);\n }\n\n gsl_matrix_set_zero(I);\n for (k=0; k < vcnt; k++)\n { \n\t l=part[k].ind;\n\t for (i=0; i < 3; i++)\n\t for (j=i; j < 3; j++)\n\t {\n\t ddum =wpart[k].pos[i] * wpart[k].pos[j];\n\t dist =SQR(wpart[k].pos[0])+SQR(wpart[k].pos[1]/q)+SQR(wpart[k].pos[2]/s);\n\t ddum/= dist;\n\t if ((sqrt(dist) 50)\n {\n\n\t qsort(&dpart[0], num_va, sizeof(gadpart_dist), (void *) cmp_dist);\n\t if (DEBUG) {printf(\"particles sorted \\n\");fflush(stdout);}\n\t int distnum= gadsearch(dpart, maxdist, 0, num_va);\n\t if (DEBUG) {printf(\"maxdist determined \\n\");fflush(stdout);}\n\t //\t dpart= realloc(dpart, distnum*sizeof(gadpart_dist));\n\n\t KdNode * root;\n\t initKdNode(&root, NULL);\n\t buildKdTree(root, vapart, num_va, 0);\n\t if (DEBUG) {printf(\"KD-Tree completed \\n\");fflush(stdout);}\n\n\t for (i=0; i<3; i++) Pi[j]=0;\n\t int incstep;\n\t if (distnum<120) incstep=1;\n\t else if (distnum<300) incstep=5;\n\t else if (distnum<500) incstep=10;\n\t else if (distnum<5000) incstep=30;\n\t else incstep=50;\n\n\t for (i=0; i(ic.boxsize-GAP) || pb[k])) && (!nopb))\n\t{\n\t pb[k]=1;\n\t //\t cm[k]=MOVE(cm[k],boxsz);\n\t}\n }\n\n // j=P[part[0].ind].id-1;\n j=tr_halo_id[0]-1;\n coord512(ca,j);\n for (k=0; k<3; k++)\n {\n if (pb[k]) {icmin[k]=MV(ca[k], DIM)*dx512; icmax[k]=MV(ca[k], DIM)*dx512;}\n else {icmin[k]=ca[k]*dx512;icmax[k]=ca[k]*dx512;}\n }\n if (!traceid) fp=fopen(\"ind.dat\",\"w\");\n for (k=0; k<3; k++) {indmax[k]=j; indmin[k]=j;}\n for (i=1; i icmax[k]) {icmax[k]= round(ddum); indmax[k]=j;}\n\t } else\n\t {\n\t ddum=ca[k]*dx512;\n\t if (ddum < icmin[k]) {icmin[k]= round(ddum); indmin[k]=j;}\n\t if (ddum > icmax[k]) {icmax[k]= round(ddum); indmax[k]=j;}\n\t } \n\t}\n\n if (!traceid)\n fprintf(fp,\"%g %g %g\\n\",P[tr_halo_i[i]].pos[0]-cm[0],P[tr_halo_i[i]].pos[1]-cm[1],P[tr_halo_i[i]].pos[2]-cm[2]);\n \n }\n if (!traceid) fclose(fp);\n\n \n alignf=2;\n gridsize=72000.0/(64.0*alignf);\n\n for (k=0; k<3; k++)\n\t{\n\t min[k]=icmin[k];\n\t max[k]=icmax[k];\n\t}\n\n if (DEBUG) \n {\n printf(\"indmin: %d %d %d...\\n\",indmin[0], indmin[1], indmin[2]);fflush(stdout);\n printf(\"indmax: %d %d %d...\\n\",indmax[0], indmax[1], indmax[2]);fflush(stdout);\n printf(\"icmin: %f %f %f...\\n\",icmin[0], icmin[1], icmin[2]);fflush(stdout);\n printf(\"icmax: %f %f %f...\\n\",icmax[0], icmax[1], icmax[2]);fflush(stdout);\n\n}\n\n if (strcmp(gridfile,\"\")) //build a grid and determine which cells contain particles of the halo\n {\n for (k=0; k<3; k++)\n {\n printf(\"%d\\n\", pb[k]);\n coord512(ca, indmin[k]);\n minbox[k]= (ca[k]>0) ? (ca[k]-1) : (ca[k]+DIM-1);\n coord512(ca, indmax[k]);\n maxbox[k]= (ca[k] minbox[k]) ? (maxbox[k]-minbox[k]) : (maxbox[k]-minbox[k]+DIM);\n \n //if ((szbox[k]&1)==1) szbox[k]++;\n // szbox[k]*=alignf;\n printf(\"%d %d %d \\n\",minbox[k],maxbox[k],szbox[k]);fflush(stdout);\n }\n\n grid= (int ***) malloc (szbox[0]*sizeof(int **)); //allocate 3-dimensional array\n\n for (i=0; i < szbox[0]; i++) \n {\n grid[i]= (int **) malloc (szbox[1] * sizeof(int *));\n }\n for (i=0; i < szbox[0]; i++) \n for (j=0; j < szbox[1]; j++)\n {\n\tgrid[i][j]= (int *) calloc (szbox[2],sizeof(int ));\n }\n fp = fopen(datfile, \"w\");\n for (i=0; i0)? diff[k] : (diff[k]+boxsz);\n shift[k]=( (boxsz/2.0) - (icmin[k]+(diff[k]/2.0)));\n expcm[k]=(cm[k]+shift[k]) > 0 ? (cm[k]+shift[k]) : (cm[k]+shift[k])+boxsz;\n printf(\" %g \", expcm[k]);\n }\n printf(\"\\n\");\n\n\n\n\n\n free(part);\n printf(\"Time needed: %.2f sec\\n\",((float)clock())/CLOCKS_PER_SEC);\n return 0;\n}\n", "meta": {"hexsha": "d5dcfd1ca28f89ab0c97fdb143bf8ef75ec35c93", "size": 50937, "ext": "c", "lang": "C", "max_stars_repo_path": "trhalo.c", "max_stars_repo_name": "Fette3lke/GadTools", "max_stars_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trhalo.c", "max_issues_repo_name": "Fette3lke/GadTools", "max_issues_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-01-12T14:40:32.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-12T14:40:32.000Z", "max_forks_repo_path": "trhalo.c", "max_forks_repo_name": "lgo33/GadTools", "max_forks_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.173119469, "max_line_length": 209, "alphanum_fraction": 0.5323635079, "num_tokens": 18360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4115336263443285}} {"text": "#include \n#include \n#include \n//#include \n#include \n#include \n#include \n#include \n\nvoid randperm(int*, int);\nvoid load_double_mat(double*, int, int, int, char*);\nvoid load_int_mat(int*, int, int, int, char*);\nvoid load_double_array(double*, int, char*);\nvoid load_int_array(int*, int, char*);\nvoid load_double_value(int,char);\nvoid load_int_value(int,char);\nint mat_size_row(int*);\nint find_value_in_array(int*,int,int,int);\nvoid mat2d_prod(double*, int, int, double*, int, int, double*, int, int);\ndouble obtainerr2_par(int,int,double*, int, int, int*, int, double*);\nvoid least_square_solver(double*, int, int, double*, double*);\n\n#define MASTER 0\n#define FROM_MASTER 1\n#define FROM_WORKER 2\n\nint main(int argc, char **argv)\n{\n int n1, n2, n3;\n int np, nfu;\n double kv[3][3], pk[3][3], pp[8][3];\n double *rp, *rpL, *rpN, *rpO;\n int *map_to_cluster1, *map_to_cluster2, *map_to_cluster3;\n int *nlist;\n int neighbor_num;\n int ncluster, ncluster2, ncluster3, ncorr_col;\n int c2start, c3start;\n int data;\n double *E, *Ef;\n int ndata;\n int i, j, k, nj, nk, ctn;\n int iter, max_iter;\n double kT=0.0517;\n int howmanycluster;\n int dispfreq;\n \n int construct_corr_mat = 0;\n\n // mpi parameters and initialization\n int numprocs, rank, mtype;\n int row_dist_size;\n int row_ini, row_end, row_offset;\n MPI_Status status;\n MPI_Init(&argc, &argv);\n MPI_Comm_size(MPI_COMM_WORLD, &numprocs); // Get # processors\n MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get my rank (id)\n\n if (numprocs>1)\n printf(\"Parallel computing: the input files are read by all nodes. Multiple messages are not due to error!\\n\",numprocs);\n\n // Construct conrrelation matrix. It can also be loaded.\n \n if (construct_corr_mat) {\n printf(\"Not activated yet.\\n\");\n/* // Task: make a function to load values from clusterlist run, later\n np = 48; // for 3x2x2 cell\n nfu = np/2; // for 3x2x2 cell\n neighbor_num = 47; // for 3x2x2 cell\n ncluster2 = 10;\n ncluster3 = 62;\n \n // load lattice and cluster data\n load_double_mat(kv,3,3,1,\"kv.dat\");\n load_double_mat(rp,np,3,1,\"rp.dat\");\n load_double_mat(rpL,npL,3,1,\"rpL.dat\");\n load_double_mat(rpN,npN,3,1,\"rpN.dat\");\n load_double_mat(rpO,npO,3,1,\"rpO.dat\");\n load_double_array(cluster2,\"cluster2.dat\");\n load_double_array(cluster3,\"cluster3.dat\");\n load_int_array(map_to_cluster1,\"map_to_cluster1.dat\");\n load_int_array(map_to_cluster2,\"map_to_cluster2.dat\");\n load_int_array(map_to_cluster3,\"map_to_cluster3.dat\");\n load_int_array(nlist,\"nlist.dat\");\n \n ncluster = ncluster2+ncluster3+1+1;\n ncorr_col = 1 + 2*np + 3*ncluster2 + 4*ncluster3;\n c2start = 3; //2*length(cluster1)+1. Don't need -1: cluster2 idx starts from 0\n c3start = 3*ncluster2 + c2start;\n\n // load LNO occupation variable data\n load_int_array(data,\"LNC_occu_data.dat\");\n load_double_array(E,\"E.dat\");\n load_double_array(Ef,\"Ef.dat\");\n ndata = mat_size_row(data);\n int nL[ndata];\n int nC[ndata];\n int nN[ndata];\n \n for (i=0;i drand48())\n cluster_set2[select2] = target;\n else {\n cluster_set1[select1] = target;\n cvs = cvs_old;\n }\n if (cvs < cvs_min) {\n for (i=0;i\n#include \n\nnamespace GSL{\n\tstatic std::string errMsg;\n\tstatic int gsl_errno;\n\tvoid error_handler(const char* reason, const char* file, int line, int gsl_errno){\n\t\tGSL::gsl_errno=gsl_errno;\n\t\terrMsg=file+std::string(\":\")+std::to_string(line)+\": \"+reason;\n\t}\n\t\n\tvoid reset_gsl_error(){ gsl_errno=0; }\n\t\n\t///\\class\n\t///\\brief Container for GSL workspace to be use with the integrators.\n\tclass IntegrateWorkspace {\n\tprivate:\n\t\t\n\tpublic:\n\t\tgsl_integration_workspace* ws;\n\t\tIntegrateWorkspace(size_t limit) {\n\t\t\tws=gsl_integration_workspace_alloc(limit);\n\t\t}\n\t\t~IntegrateWorkspace() {\n\t\t\tgsl_integration_workspace_free(ws);\n\t\t}\n\t};\n\t\n\t///\\brief One dimensional integral using GSL.\n\t/// @param ws GSL integration workspace.\n\t/// @param f Function to integrate.\n\t/// @param a Lower integration limit.\n\t/// @param b Upper integration limit.\n\t/// @param acc Accuracy parameter.\n\t/// @param max_iter Maximum number of iterations to perform the integral.\n\ttemplate\n\tdouble integrate(IntegrateWorkspace& ws, FunctionType&& f, double a, double b, double acc=1e-7, unsigned int max_iter=10000){\n\t\t//precondition copied from gsl-1.16/integration/qag.c:122\n\t\t//assuming epsabs=0 and epsrel=acc\n\t\tif ((acc < 50 * GSL_DBL_EPSILON || acc < 0.5e-28))\n\t\t\tthrow std::runtime_error(\"Specified tolerance too small\");\n\t\t\n\t\tusing FPtr=decltype(&f);\n\t\tdouble (*wrapper)(double,void*)=[](double x, void* params)->double{\n\t\t\tauto& f=*static_cast(params);\n\t\t\treturn(f(x));\n\t\t};\n\t\t\n\t\tdouble result, error;\n\t\tgsl_function F;\n\t\tF.function = wrapper;\n\t\tF.params = &f;\n\t\t\n\t\tgsl_integration_qag(&F, a, b, 0, acc, max_iter, GSL_INTEG_GAUSS15, ws.ws, &result, &error);\n\t\t\n\t\treturn(result);\n\t}\n\t\n\t///\\brief One dimensional integral using GSL.\n\t/// @param f Function to integrate.\n\t/// @param a Lower integration limit.\n\t/// @param b Upper integration limit.\n\t/// @param acc Accuracy parameter.\n\t/// @param max_iter Maximum number of iterations to perform the integral.\n\ttemplate\n\tdouble integrate(FunctionType&& f, double a, double b, double acc=1e-7, unsigned int max_iter=10000, size_t memory_alloc=10000){\n\t\tIntegrateWorkspace ws(memory_alloc);\n\t\treturn integrate(ws, f, a, b, acc, max_iter);\n\t}\n} //namespace GSL\n#endif //HAVE_GSL\n\n#endif //GSL_INTERFACE_H", "meta": {"hexsha": "047af7da8362d82b58c03b571468afc4da6d3e46", "size": 2363, "ext": "h", "lang": "C", "max_stars_repo_path": "test/gsl_interface.h", "max_stars_repo_name": "cnweaver/AdaptiveQuad", "max_stars_repo_head_hexsha": "6f99bdbf8f9ffdd25b1babfd9f4b46364ffb033a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/gsl_interface.h", "max_issues_repo_name": "cnweaver/AdaptiveQuad", "max_issues_repo_head_hexsha": "6f99bdbf8f9ffdd25b1babfd9f4b46364ffb033a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/gsl_interface.h", "max_forks_repo_name": "cnweaver/AdaptiveQuad", "max_forks_repo_head_hexsha": "6f99bdbf8f9ffdd25b1babfd9f4b46364ffb033a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0921052632, "max_line_length": 129, "alphanum_fraction": 0.7160389336, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4110514729243789}} {"text": "#ifndef METHODS_CWA_SMD_OPT_H\n#define METHODS_CWA_SMD_OPT_H\n\n#include \n#include \"quartz_internal/util/gsl_converter.h\"\n\nnamespace method {\nnamespace cwa_smd_opt {\nnamespace details {\n\ninline\ngsl_multimin_fdfminimizer_type * minimizer_map(const std::string type) {\n if(type == \"steepest_descent\") {\n return const_cast(gsl_multimin_fdfminimizer_steepest_descent);\n } else if(type == \"conjugate_pr\") {\n return const_cast(gsl_multimin_fdfminimizer_conjugate_pr);\n } else if(type == \"conjugate_fr\") {\n return const_cast(gsl_multimin_fdfminimizer_conjugate_fr);\n } else if(type == \"bfgs\") {\n return const_cast(gsl_multimin_fdfminimizer_vector_bfgs);\n } else if(type == \"bfgs2\") {\n return const_cast(gsl_multimin_fdfminimizer_vector_bfgs2);\n } else {\n throw Error(\"minimizer \" + type + \" is not implemented\");\n }\n\n}\n\nstruct cwa_smd_opt_param {\n arma::mat original_points;\n arma::vec expectations_ref;\n std::vector> original_operators;\n arma::vec weights;\n arma::vec scaling;\n long long grade;\n};\n\n\ninline\ndouble penalty_function(\n const arma::mat & points,\n const arma::vec & expectations_ref,\n const std::vector> & original_operators,\n const arma::vec & weights,\n const arma::vec & scaling,\n const long long grade) {\n\n double result = 0;\n\n for (arma::uword i = 0; i < original_operators.size(); i++) {\n const long long the_grade = original_operators[i].grade();\n if (the_grade < grade && the_grade > 0) {\n const double result_from_cwa =\n cwa_smd::details::expectation(original_operators[i], points, weights,\n scaling);\n\n result += std::pow(result_from_cwa - expectations_ref(i), 2);\n }\n }\n\n return result;\n\n}\n\ninline\narma::mat penalty_function_derivative(\n const arma::mat & points,\n const arma::vec & expectations_ref,\n const std::vector> & original_operators,\n const arma::vec & weights,\n const arma::vec & scaling,\n const long long grade\n) {\n\n arma::mat result(arma::size(points), arma::fill::zeros);\n\n for (arma::uword i = 0; i < original_operators.size(); i++) {\n const long long the_grade = original_operators[i].grade();\n if (the_grade < grade && the_grade > 0) {\n const double result_from_cwa =\n cwa_smd::details::expectation(original_operators[i], points, weights,\n scaling);\n\n for (arma::uword j = 0; j < points.n_cols; j++) {\n const arma::vec point = arma::diagmat(1.0 / scaling) * points.col(j);\n for (arma::uword k = 0; k < points.n_rows / 2; k++) {\n const math::Polynomial x_derivative =\n original_operators[i].derivative(\n k) / scaling(k);\n const math::Polynomial p_derivative =\n original_operators[i].derivative(\n k + points.n_rows / 2) / scaling(k + points.n_rows / 2);\n\n result(k, j) -=\n 2.0 * (result_from_cwa - expectations_ref(i)) * weights(j) *\n x_derivative.at(point) / arma::sum(weights);\n result(k + points.n_rows / 2, j) -=\n 2.0 * (result_from_cwa - expectations_ref(i)) * weights(j) *\n p_derivative.at(point) / arma::sum(weights);\n }\n }\n }\n }\n\n return -result;\n\n}\n\ninline\ndouble penalty_function_gsl_wrapper(const gsl_vector * flattened_points,\n void * param) {\n\n const arma::vec arma_flattened_points = gsl::convert_vec(flattened_points);\n const auto converted_param = *(cwa_smd_opt_param *) param;\n const arma::mat points = arma::reshape(arma_flattened_points, arma::size(\n converted_param.original_points));\n\n return penalty_function(points,\n converted_param.expectations_ref,\n converted_param.original_operators,\n converted_param.weights,\n converted_param.scaling,\n converted_param.grade);\n}\n\ninline\nvoid penalty_function_derivative_gsl_wrapper(\n const gsl_vector * flattened_points,\n void * param,\n gsl_vector * g) {\n const arma::vec arma_flattened_points = gsl::convert_vec(flattened_points);\n const auto converted_param = *(cwa_smd_opt_param *) param;\n const arma::mat points = arma::reshape(arma_flattened_points, arma::size(\n converted_param.original_points));\n\n const arma::vec result =\n arma::vectorise(\n penalty_function_derivative(points,\n converted_param.expectations_ref,\n converted_param.original_operators,\n converted_param.weights,\n converted_param.scaling,\n converted_param.grade));\n\n const auto result_pointer = gsl::convert_vec(result);\n\n gsl_vector_memcpy(g, result_pointer);\n\n gsl_vector_free(result_pointer);\n}\n\ninline\nvoid penalty_function_fdf_gsl_wrapper(\n const gsl_vector * a_derivatives,\n void * param,\n double * f,\n gsl_vector * g) {\n penalty_function_derivative_gsl_wrapper(a_derivatives, param, g);\n\n *f = penalty_function_gsl_wrapper(a_derivatives, param);\n}\n\ninline\nstd::tuple cwa_optimize(const cwa_smd_opt_param input,\n const double initial_step_size,\n const double tolerance,\n const double gradient_tolerance,\n const size_t total_steps,\n const std::string type) {\n\n /* allocate memory for minimization process */\n const auto minimizer_type = minimizer_map(type);\n\n const arma::uword n = input.original_points.n_elem;\n\n const auto penalty_function_value = penalty_function(input.original_points,\n input.expectations_ref,\n input.original_operators,\n input.weights,\n input.scaling,\n input.grade);\n\n const double gradient_module = arma::norm(\n arma::vectorise(penalty_function_derivative(input.original_points,\n input.expectations_ref,\n input.original_operators,\n input.weights,\n input.scaling,\n input.grade)));\n\n if (penalty_function_value < tolerance &&\n gradient_module < gradient_tolerance) {\n return {input.original_points, penalty_function_value, gradient_module, 0};\n }\n\n auto minimizer_environment = gsl_multimin_fdfminimizer_alloc(minimizer_type,\n n);\n\n /* assigning function to minimizer object */\n gsl_multimin_function_fdf minimizer_object;\n minimizer_object.f = &penalty_function_gsl_wrapper;\n minimizer_object.df = &penalty_function_derivative_gsl_wrapper;\n minimizer_object.fdf = &penalty_function_fdf_gsl_wrapper;\n minimizer_object.n = n;\n minimizer_object.params = (void *) &input;\n\n /* starting point */\n const arma::vec flattened = arma::vectorise(input.original_points);\n gsl_vector * points = gsl::convert_vec(flattened);\n\n /* set environment */\n gsl_multimin_fdfminimizer_set(minimizer_environment,\n &minimizer_object, points,\n initial_step_size, tolerance);\n\n size_t iter = 0;\n int status = GSL_CONTINUE;\n do {\n iter++;\n\n status = gsl_multimin_fdfminimizer_iterate(minimizer_environment);\n\n if (status) {\n throw Error(gsl_strerror(status));\n }\n\n status = gsl_multimin_test_gradient(minimizer_environment->gradient,\n gradient_tolerance);\n\n if (status == GSL_SUCCESS) {\n const arma::vec result = gsl::convert_vec(minimizer_environment->x);\n\n const double f = minimizer_environment->f;\n const double df = arma::norm(gsl::convert_vec(minimizer_environment->gradient));\n gsl_multimin_fdfminimizer_free(minimizer_environment);\n gsl_vector_free(points);\n\n return {arma::reshape(result, arma::size(input.original_points)), f, df, iter};\n }\n } while (status == GSL_CONTINUE && iter < total_steps);\n\n throw Error(\"fail to converge towards the solution\");\n}\n\n} // namespace details\n\nstruct State {\npublic:\n arma::mat points;\n arma::vec weights;\n arma::vec masses;\n arma::uword grade;\n arma::uvec expectation_table;\n arma::vec expectations;\n arma::uvec positional_indices;\n arma::uvec momentum_indices;\n arma::vec scaling;\n\n // Establish an easy way to construct your State\n template\n State(const PhaseSpaceDistribution & initial,\n const arma::uvec & grid,\n const arma::mat & range,\n const arma::vec & scaling,\n const arma::vec & masses,\n const arma::uword grade) :\n points(math::space::points_generate(grid, range)),\n weights(arma::real(at(initial, points))),\n masses(masses),\n grade(grade),\n expectation_table(math::space::grids_to_table(\n grade * arma::ones(points.n_rows))),\n scaling(scaling) {\n if (grid.n_rows != range.n_rows) {\n throw Error(\"Different dimension between the grid and the range\");\n }\n if (grid.n_rows != 2 * masses.n_rows) {\n throw Error(\"Different dimension between the grid and the masses\");\n }\n\n const arma::uword dimension = grid.n_elem;\n const arma::uword length = std::pow(grade, dimension);\n\n this->expectations = arma::vec(length);\n this->positional_indices = arma::uvec(dimension / 2);\n this->momentum_indices = arma::uvec(dimension / 2);\n\n const arma::vec ranges = range.col(1) - range.col(0);\n\n // exponents check in\n#pragma omp parallel for\n for (arma::uword i = 0; i < dimension / 2; i++) {\n arma::uvec X = arma::zeros(dimension);\n arma::uvec P = arma::zeros(dimension);\n X(i) = 1;\n P(i + dimension / 2) = 1;\n this->positional_indices(i) =\n math::space::indices_to_index(X, this->expectation_table);\n this->momentum_indices(i) =\n math::space::indices_to_index(P, this->expectation_table);\n }\n\n // expectations check in\n#pragma omp parallel for\n for (arma::uword i = 0; i < length; i++) {\n const lvec indices =\n arma::conv_to::from(\n math::space::index_to_indices(i, this->expectation_table));\n\n this->expectations(i) =\n cwa_smd::details::expectation(math::polynomial::Term(1.0, indices),\n this->points, this->weights,\n this->scaling);\n }\n }\n\n template\n State(const PhaseSpaceDistribution & initial,\n const arma::uvec & grid,\n const arma::mat & range,\n const arma::uword grade) :\n points(math::space::points_generate(grid, range)),\n weights(arma::real(at(initial, points))),\n masses(arma::ones(grid.n_rows / 2)),\n grade(grade),\n expectation_table(math::space::grids_to_table(\n grade * arma::ones(points.n_rows))) {\n if (grid.n_rows != range.n_rows) {\n throw Error(\"Different dimension between the grid and the range\");\n }\n if (grid.n_rows != 2 * masses.n_rows) {\n throw Error(\"Different dimension between the grid and the masses\");\n }\n\n const auto dimension = grid.n_elem;\n const auto length = std::pow(grade, dimension);\n\n this->expectations = arma::vec(length);\n this->positional_indices = arma::uvec(dimension / 2);\n this->momentum_indices = arma::uvec(dimension / 2);\n\n const arma::vec ranges = range.col(1) - range.col(0);\n this->scaling = ranges;\n// this->scaling = arma::ones(arma::size(ranges));\n\n // exponents check in\n for (arma::uword i = 0; i < dimension / 2; i++) {\n arma::uvec X = arma::zeros(dimension);\n arma::uvec P = arma::zeros(dimension);\n X(i) = 1;\n P(i + dimension / 2) = 1;\n this->positional_indices(i) =\n math::space::indices_to_index(X, this->expectation_table);\n this->momentum_indices(i) =\n math::space::indices_to_index(P, this->expectation_table);\n }\n\n // expectations check in\n for (arma::uword i = 0; i < length; i++) {\n const lvec indices =\n arma::conv_to::from(\n math::space::index_to_indices(i, this->expectation_table));\n\n this->expectations(i) =\n cwa_smd::details::expectation(\n math::polynomial::Term(1.0, indices),\n this->points, this->weights, this->scaling);\n }\n }\n\n inline\n State(const arma::mat & points,\n const arma::vec & weights,\n const arma::vec & masses,\n const arma::uvec & expectation_table,\n const arma::vec & expectations,\n const arma::uvec & positional_indices,\n const arma::uvec & momentum_indices,\n const arma::vec & scaling,\n const arma::uword grade) :\n points(points),\n weights(weights),\n masses(masses),\n grade(grade),\n expectation_table(expectation_table),\n expectations(expectations),\n positional_indices(positional_indices),\n momentum_indices(momentum_indices),\n scaling(scaling) {}\n\n inline\n State(const State & state) :\n points(state.points),\n weights(state.weights),\n masses(state.masses),\n grade(state.grade),\n expectation_table(state.expectation_table),\n expectations(state.expectations),\n positional_indices(state.positional_indices),\n momentum_indices(state.momentum_indices),\n scaling(state.scaling) {}\n\n inline\n arma::uword dim() const {\n return points.n_rows / 2;\n }\n\n inline\n State normalise() const {\n State state = *this;\n state.weights = state.weights / arma::sum(state.weights);\n\n return state;\n }\n\n inline\n arma::vec positional_expectation() const {\n\n return method::cwa::State(this->points, this->weights, this->masses)\n .positional_expectation();\n }\n\n inline\n arma::vec momentum_expectation() const {\n return method::cwa::State(this->points, this->weights, this->masses)\n .momentum_expectation();\n }\n\n State operator+(const State & B) const {\n if (!arma::approx_equal(this->weights, B.weights, \"abs_diff\", 1e-16) ||\n !arma::approx_equal(this->masses, B.masses, \"abs_diff\", 1e-16)) {\n throw Error(\"Different cwa states are being added\");\n }\n\n State state = B;\n state.points += this->points;\n state.expectations += this->expectations;\n\n return state;\n }\n\n State operator*(const double B) const {\n\n State state = *this;\n state.expectations *= B;\n state.points *= B;\n\n return state;\n }\n\n template\n auto expectation(const math::Polynomial & polynomial) const {\n return cwa_smd::details::at_search(polynomial,\n this->points,\n this->weights,\n this->expectations,\n this->expectation_table,\n this->scaling,\n this->grade) *\n polynomial.at(this->scaling);\n }\n\n template\n arma::vec expectation(const std::vector>\n\n & polynomials) const {\n arma::vec result(polynomials.size());\n\n#pragma omp parallel for\n for (arma::uword i = 0; i < result.n_elem; i++) {\n result(i) = this->expectation(polynomials[i]);\n }\n\n return result;\n }\n\n State & operator=(const State &) = default;\n};\n\nstruct Operator {\n\npublic:\n math::Polynomial potential;\n math::Polynomial H;\n std::vector> original_operators;\n std::vector> operators;\n\n Operator(const State & state,\n const math::Polynomial & potential) :\n potential(potential),\n H(hamiltonian(potential, state.masses).scale(state.scaling)),\n operators() {\n\n std::vector>\n op(std::pow(state.grade, state.dim() * 2));\n std::vector>\n original_op(std::pow(state.grade, state.dim() * 2));\n\n op[0] = math::Polynomial(state.dim() * 2, 0.0);\n original_op[0] = math::Polynomial(state.dim() * 2, 1.0);\n\n\n for (arma::uword i = 1; i < op.size(); i++) {\n const auto observable =\n math::Polynomial(math::polynomial::Term(1.0,\n math::space::index_to_indices(\n i,\n state.expectation_table)));\n\n original_op[i] = observable;\n\n const arma::uword cut_off = std::min(observable.grade(), H.grade()) / 2;\n const auto moyal =\n moyal_bracket(math::Polynomial(observable), H, state.scaling,\n cut_off);\n\n op[i] = moyal;\n }\n\n this->operators = op;\n this->original_operators = original_op;\n }\n\n\n inline\n PropagationType propagation_type() const {\n return Classic;\n }\n\n State operator()(const State & state) const {\n\n arma::mat p_submatrix = state.points.rows(state.dim(), 2 * state.dim() - 1);\n p_submatrix.each_col() /= state.masses;\n\n const arma::mat points_change_list =\n arma::join_cols(p_submatrix,\n cwa::details::force(this->potential,\n state.points.rows(0, state.dim() -\n 1)));\n\n arma::vec expectation_change_list =\n arma::vec(arma::size(state.expectations));\n\n#pragma omp parallel for\n for (arma::uword i = 0; i < expectation_change_list.n_elem; i++) {\n expectation_change_list(i) =\n cwa_smd::details::at_search(this->operators[i],\n state.points,\n state.weights,\n state.expectations,\n state.expectation_table,\n state.scaling,\n state.grade);\n }\n\n return State(points_change_list,\n state.weights,\n state.masses,\n state.expectation_table,\n expectation_change_list,\n state.positional_indices,\n state.momentum_indices,\n state.scaling,\n state.grade);\n }\n\n};\n\ntemplate\nOperatorWrapper\ncwa_opt(const double initial_step_size,\n const double tolerance,\n const double gradient_tolerance,\n const size_t total_steps,\n const std::string type = \"bfgs2\",\n const int print_level = 0) {\n return [initial_step_size,\n tolerance,\n gradient_tolerance,\n total_steps,\n type,\n print_level\n ](const Operator & cwa_smd_opt_operator,\n const Potential & potential) -> Propagator {\n return [initial_step_size,\n tolerance,\n gradient_tolerance,\n total_steps,\n &cwa_smd_opt_operator,\n type,\n print_level\n ]\n (const State & state,\n const double dt) -> State {\n const arma::vec & ref_expectations = state.expectations;\n const arma::mat & points = state.points;\n const auto & original_operators = cwa_smd_opt_operator.original_operators;\n\n details::cwa_smd_opt_param input{points, ref_expectations,\n original_operators,\n state.weights, state.scaling,\n (long long) state.grade};\n\n const auto opt_result = details::cwa_optimize(input, initial_step_size,\n tolerance, gradient_tolerance, total_steps, type);\n\n const arma::mat new_points = std::get<0>(opt_result);\n const double f = std::get<1>(opt_result);\n const double df = std::get<2>(opt_result);\n const int iter = std::get<3>(opt_result);\n\n if(print_level > 2) {\n fmt::print(\"f: {0:20.10f}, df: {1:20.10f}, iter: {2}\", f, df, iter);\n fmt::print(\"\\n\");\n }\n\n State new_state = state;\n new_state.points = new_points;\n return new_state;\n };\n };\n}\n\n} // namespace cwa\n}\n\n#endif //METHODS_CWA_SMD_OPT_H", "meta": {"hexsha": "a9ce0d4d8eb0238a858a663f1c48f25c4947cf8c", "size": 21195, "ext": "h", "lang": "C", "max_stars_repo_path": "include/quartz_internal/details/methods/cwa_smd_opt.h", "max_stars_repo_name": "Walter-Feng/Quartz", "max_stars_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T09:34:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T01:27:32.000Z", "max_issues_repo_path": "include/quartz_internal/details/methods/cwa_smd_opt.h", "max_issues_repo_name": "Walter-Feng/Quartz", "max_issues_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-02-27T04:46:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T05:26:46.000Z", "max_forks_repo_path": "include/quartz_internal/details/methods/cwa_smd_opt.h", "max_forks_repo_name": "Walter-Feng/Quartz", "max_forks_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8038277512, "max_line_length": 100, "alphanum_fraction": 0.5934418495, "num_tokens": 4720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4110514729243789}} {"text": "/*=========================================================================\n\n Library : Image Registration Toolkit (IRTK)\n Module : $Id$\n Copyright : Imperial College, Department of Computing\n Visual Information Processing (VIP), 2008 onwards\n Date : $Date$\n Version : $Revision$\n Changes : $Author$\n\nCopyright (c) 1999-2014 and onwards, Imperial College London\nAll rights reserved.\nSee LICENSE for details\n\n=========================================================================*/\n\n#ifndef _IRTKMATRIX_H\n\n#define _IRTKMATRIX_H\n\n#include \n\n#ifdef USE_VXL\n#include \n#else\n#include \n#endif\n\n#include \n\n#include \n#include \n\n/**\n\n Matrix class.\n\n*/\n\nclass irtkMatrix : public irtkObject\n{\n\nprotected:\n\n /// Number of rows\n int _rows;\n\n /// Number of colums\n int _cols;\n\n /// Data\n double **_matrix;\n\npublic:\n\n /// Default constructor\n irtkMatrix();\n\n /// Constructor for given number of rows and columns\n irtkMatrix(int, int);\n\n /// Copy constructor\n irtkMatrix(const irtkMatrix &);\n\n /// Destructor\n ~irtkMatrix();\n\n /// Initialize matrix with number of rows and columns\n void Initialize(int, int);\n\n //\n // Matrix access functions\n //\n\n /// Returns number of rows\n int Rows() const;\n\n /// Returns number of columns\n int Cols() const;\n\n /// Puts matrix value\n void Put(int, int, double);\n\n /// Gets matrix value\n double Get(int, int) const;\n\n //\n // Operators for matrix access\n //\n\n /// Puts matrix value\n double& operator()(int, int);\n\n /// Gets matrix value\n double operator()(int, int) const;\n\n /// Access matrix get operator\n irtkMatrix operator()(int, int, int, int);\n\n /// Access matrix put operator\n void operator()(irtkMatrix &, int, int);\n\n //\n // Matrix operators for doubles\n //\n\n /// Subtraction of a double\n irtkMatrix& operator-=(const double&);\n\n /// Addition of a double\n irtkMatrix& operator+=(const double&);\n\n /// Multiplication with a double\n irtkMatrix& operator*=(const double&);\n\n /// Division by a double\n irtkMatrix& operator/=(const double&);\n\n /// Return result of subtraction of a double\n irtkMatrix operator- (const double&);\n\n /// Return result of addition of a double\n irtkMatrix operator+ (const double&);\n\n /// Return result of multiplication with a double\n irtkMatrix operator* (const double&);\n\n /// Return result of division by a double\n irtkMatrix operator/ (const double&);\n\n //\n // Matrix operators for matrices\n //\n\n /// Matrix copy operator\n irtkMatrix& operator =(const irtkMatrix&);\n\n /// Matrix subtraction operator\n irtkMatrix& operator-=(const irtkMatrix&);\n\n /// Matrix addition operator\n irtkMatrix& operator+=(const irtkMatrix&);\n\n /// Matrix multiplication operator\n irtkMatrix& operator*=(const irtkMatrix&);\n\n /// Return result of matrix subtraction\n irtkMatrix operator- (const irtkMatrix&);\n\n /// Return result of matrix addition\n irtkMatrix operator+ (const irtkMatrix&);\n\n /// Return result of matrix multiplication\n irtkMatrix operator* (const irtkMatrix&);\n\n /// Matrix inversion operator\n irtkMatrix operator! (void);\n\n /// Matrix transpose operator\n irtkMatrix operator~ (void);\n\n /// Matrix comparison operator =\n int operator==(const irtkMatrix &);\n\n // Matrix exponential via Pade approximation.\n // See Golub and Van Loan, Matrix Computations, Algorithm 11.3-1.\n friend irtkMatrix expm(irtkMatrix);\n\n // Matrix logarithm.\n friend irtkMatrix logm(irtkMatrix);\n\n // Matrix square root.\n friend irtkMatrix sqrtm(irtkMatrix);\n\n friend irtkMatrix FrechetMean(irtkMatrix *, int, int = 10);\n\n friend irtkMatrix FrechetMean(irtkMatrix *, double *, int, int = 10);\n\n#ifndef USE_STL\n /// Comparison operator != (if USE_STL is defined, negate == operator)\n int operator!=(const irtkMatrix &);\n#endif\n\n //\n // Matrix functions\n //\n\n /// Calculate norm of matrix\n double Norm(void) const;\n\n /// Calculate trace of matrix\n double Trace(void) const;\n\n // The infinity norm is the maximum of the absolute value row sums.\n double InfinityNorm(void) const;\n\n /// Calculate determinant of matrix\n double Det() const;\n\n /* Calculate SVD of matrix\n * now does the same as Eigenvalues (but eigenvalues are in square root)\n * algorithm chosen according to matrix properties (symmetry, diagonizability)\n */\n void SVD(irtkMatrix &, irtkVector &, irtkMatrix &);\n\n /// Identity matrix\n void Ident();\n\n /// Returns true if the matrix is an identity matrix.\n bool IsIdentity() const;\n\n /// Invert of matrix\n void Invert();\n\n /// Adjugate of matrix and return determine;\n void Adjugate(double &);\n\n /// Transpose matrix\n void Transpose();\n\n /* Calculate eigenvalues and eigenvectors of matrix\n * now does the same as SVD (but eigenvalues are NOT in square root)\n * algorithm chosen according to matrix properties (symmetry, diagonizability)\n */\n void Eigenvalues(irtkMatrix &, irtkVector &, irtkMatrix &);\n\n /// Calculate least square fit via SVD\n void LeastSquaresFit(const irtkVector &, irtkVector &);\n\n //\n // Matrix in- and output\n //\n\n /// Interface to output stream\n friend std::ostream& operator<< (std::ostream&, const irtkMatrix&);\n\n /// Interface to input stream\n friend std::istream& operator>> (std::istream&, irtkMatrix&);\n\n /// Print matrix\n void Print();\n\n /// Read matrix from file\n void Read (char *);\n\n /// Write matrix to file\n void Write(char *);\n\n /// Import matrix from text file (requires no. of expected rows and cols)\n void Import (char *, int, int);\n\n#ifdef USE_VXL\n\n /// Conversion to VNL matrix\n template void Matrix2Vnl(vnl_matrix *m) const;\n\n /// Conversion from VNL matrix\n template void Vnl2Matrix(vnl_matrix *m);\n\n#else\n\n /// Conversion to GSL matrix (memory must be allocated)\n void Matrix2GSL(gsl_matrix *) const;\n\n /// Conversion from GSL matrix\n void GSL2Matrix(gsl_matrix *);\n\n //\n // Matrix operators for vectors\n //\n\n /// Return result of multiplication of matrix and vector\n irtkVector operator* (const irtkVector&);\n\n#endif\n};\n\n//\n// Access operators\n//\n\ninline int irtkMatrix::Rows() const\n{\n return _rows;\n}\n\ninline int irtkMatrix::Cols() const\n{\n return _cols;\n}\n\ninline void irtkMatrix::Put(int rows, int cols, double matrix)\n{\n#ifdef NO_BOUNDS\n _matrix[cols][rows] = matrix;\n#else\n if ((rows >= 0) && (rows < _rows) && (cols >= 0) && (cols < _cols)) {\n _matrix[cols][rows] = matrix;\n } else {\n cout << \"irtkMatrix::Put: parameter out of range\\n\";\n }\n#endif\n}\n\ninline double irtkMatrix::Get(int rows, int cols) const\n{\n#ifdef NO_BOUNDS\n return _matrix[cols][rows];\n#else\n if ((rows >= 0) && (rows < _rows) && (cols >= 0) && (cols < _cols)) {\n return _matrix[cols][rows];\n } else {\n cout << \"irtkMatrix::Get: parameter out of range\\n\";\n return 0;\n }\n#endif\n}\n\ninline double &irtkMatrix::operator()(int rows, int cols)\n{\n#ifdef NO_BOUNDS\n return _matrix[cols][rows];\n#else\n if ((rows >= 0) && (rows < _rows) && (cols >= 0) && (cols < _cols)) {\n return _matrix[cols][rows];\n } else {\n cout << \"irtkMatrix::operator(): parameter out of range\\n\";\n return _matrix[0][0];\n }\n#endif\n}\n\ninline double irtkMatrix::operator()(int rows, int cols) const\n{\n#ifdef NO_BOUNDS\n return _matrix[cols][rows];\n#else\n if ((rows >= 0) && (rows < _rows) && (cols >= 0) && (cols < _cols)) {\n return _matrix[cols][rows];\n } else {\n cout << \"irtkMatrix::operator(): parameter out of range\\n\";\n return 0;\n }\n#endif\n}\n\n//\n// Matrix operators for doubles\n//\n\ninline irtkMatrix& irtkMatrix::operator-=(const double &x)\n{\n int i, j;\n\n for (j = 0; j < _cols; j++) {\n for (i = 0; i < _rows; i++) {\n _matrix[j][i] -= x;\n }\n }\n return *this;\n}\n\ninline irtkMatrix& irtkMatrix::operator+=(const double &x)\n{\n int i, j;\n\n for (j = 0; j < _cols; j++) {\n for (i = 0; i < _rows; i++) {\n _matrix[j][i] += x;\n }\n }\n return *this;\n}\n\ninline irtkMatrix& irtkMatrix::operator*=(const double &x)\n{\n int i, j;\n\n for (j = 0; j < _cols; j++) {\n for (i = 0; i < _rows; i++) {\n _matrix[j][i] *= x;\n }\n }\n return *this;\n}\n\ninline irtkMatrix& irtkMatrix::operator/=(const double &x)\n{\n int i, j;\n\n for (j = 0; j < _cols; j++) {\n for (i = 0; i < _rows; i++) {\n _matrix[j][i] /= x;\n }\n }\n return *this;\n}\n\ninline irtkMatrix irtkMatrix::operator-(const double &x)\n{\n int i, j;\n irtkMatrix m;\n\n m = *this;\n for (j = 0; j < _cols; j++) {\n for (i = 0; i < m._rows; i++) {\n m._matrix[j][i] = _matrix[j][i] - x;\n }\n }\n return m;\n}\n\ninline irtkMatrix irtkMatrix::operator+(const double &x)\n{\n int i, j;\n irtkMatrix m;\n\n m = *this;\n for (j = 0; j < _cols; j++) {\n for (i = 0; i < m._rows; i++) {\n m._matrix[j][i] = _matrix[j][i] + x;\n }\n }\n return m;\n}\n\ninline irtkMatrix irtkMatrix::operator*(const double &x)\n{\n int i, j;\n irtkMatrix m;\n\n m = *this;\n for (j = 0; j < _cols; j++) {\n for (i = 0; i < m._rows; i++) {\n m._matrix[j][i] = _matrix[j][i] * x;\n }\n }\n return m;\n}\n\ninline irtkMatrix irtkMatrix::operator/(const double &x)\n{\n int i, j;\n irtkMatrix m;\n\n m = *this;\n for (j = 0; j < _cols; j++) {\n for (i = 0; i < m._rows; i++) {\n m._matrix[j][i] = _matrix[j][i] / x;\n }\n }\n return m;\n}\n\n//\n// Matrix operators for matrices\n//\n\ninline int irtkMatrix::operator==(const irtkMatrix& m)\n{\n int i, j;\n\n if ((m._rows != _rows) || (m._cols != _cols)) return 0;\n for (j = 0; j < _cols; j++) {\n for (i = 0; i < m._rows; i++) {\n if (m._matrix[j][i] != _matrix[j][i]) return 0;\n }\n }\n return 1;\n}\n\n#ifndef USE_STL\ninline int irtkMatrix::operator!=(const irtkMatrix& m)\n{\n return !(*this == m);\n}\n#endif\n\ninline double irtkMatrix::Trace(void) const\n{\n int i, j;\n double trace = 0;\n\n if(_rows == _cols){\n\n // The trace of a matrix\n for (j = 0; j < _cols; j++) {\n for (i = 0; i < _rows; i++) {\n trace += _matrix[j][i];\n }\n }\n return trace;\n }else{\n std::cerr << \"irtkMatrix::Trace() matrix number of col != row\" << std::endl;\n return 0;\n }\n}\n\ninline double irtkMatrix::Norm(void) const\n{\n int i, j;\n double norm = 0;\n\n // The norm of a matrix M is defined as trace(M * M~)\n for (j = 0; j < _cols; j++) {\n for (i = 0; i < _rows; i++) {\n norm += _matrix[j][i]*_matrix[j][i];\n }\n }\n return std::sqrt(norm);\n}\n\ninline double irtkMatrix::InfinityNorm(void) const\n{\n int i, j;\n double normInf = -1.0 * DBL_MAX;\n double sum;\n\n for (i = 0; i < _rows; ++i) {\n sum = 0;\n for (j = 0; j < _cols; ++j) {\n sum += abs(_matrix[j][i]);\n }\n if (sum > normInf)\n normInf = sum;\n }\n return normInf;\n}\n\n\n#endif\n\n\n", "meta": {"hexsha": "145cd0b828623eed4a266161e01f5bf294613c66", "size": 10758, "ext": "h", "lang": "C", "max_stars_repo_path": "source/IRTKSimple2/geometry++/include/irtkMatrix.h", "max_stars_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_stars_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_stars_repo_licenses": ["Zlib", "Unlicense", "Intel", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/IRTKSimple2/geometry++/include/irtkMatrix.h", "max_issues_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_issues_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_issues_repo_licenses": ["Zlib", "Unlicense", "Intel", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/IRTKSimple2/geometry++/include/irtkMatrix.h", "max_forks_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_forks_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_forks_repo_licenses": ["Zlib", "Unlicense", "Intel", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1460674157, "max_line_length": 84, "alphanum_fraction": 0.6102435397, "num_tokens": 3221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190477, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4106372595160938}} {"text": "/*\n * Copyright 2016 Maikel Nadolski\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n#ifndef HMM_IO_H_\n#define HMM_IO_H_\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"maikel/hmm/hidden_markov_model.h\"\n#include \"maikel/function_profiler.h\"\n\nnamespace maikel { namespace hmm {\n\n struct getline_error: public std::runtime_error {\n getline_error(std::string s): std::runtime_error(s) {}\n };\n\n struct read_ascii_matrix_error: public std::runtime_error {\n read_ascii_matrix_error(std::string s): std::runtime_error(s) {}\n };\n\n struct read_sequence_error: public std::runtime_error {\n read_sequence_error(std::string s): std::runtime_error(s) {}\n };\n\n inline std::istream& getline(std::istream& in, std::istringstream& linestream)\n {\n Expects(in);\n std::string line;\n if (!std::getline(in, line))\n throw getline_error(\"Could not read the line from given stream.\");\n linestream.str(line);\n linestream.clear();\n return in;\n }\n\n template \n std::pair getdims(std::istream& in)\n {\n Expects(in);\n std::pair dim;\n std::istringstream line(ranges::front(ranges::getlines(in)));\n if (!(line >> dim.first >> dim.second))\n throw read_ascii_matrix_error(\"Could not read dimensions.\");\n return dim;\n }\n\n template \n typename std::enable_if<\n std::is_floating_point::value,\n Eigen::Matrix>::type\n read_ascii_matrix(std::istream& in, std::size_t rows, std::size_t cols)\n {\n Expects(in);\n typename Eigen::Matrix matrix(rows, cols);\n std::istringstream line;\n for (std::size_t i = 0; i < rows; ++i) {\n getline(in, line);\n for (std::size_t j = 0; j < cols; ++j)\n if (!(line >> matrix(i,j)))\n throw read_ascii_matrix_error(\"Could not read entries in line: \" + line.str() + \".\");\n }\n Ensures(gsl::narrow(matrix.rows()) == rows &&\n gsl::narrow(matrix.cols()) == cols);\n return matrix;\n }\n\n template \n Eigen::DenseBase& normalize_rows(Eigen::DenseBase& matrix)\n {\n using Index = typename Eigen::DenseBase::Index;\n for (Index i = 0; i < matrix.rows(); ++i)\n matrix.row(i) /= matrix.row(i).sum();\n return matrix;\n }\n\n template \n typename std::enable_if<\n std::is_floating_point::value,\n hidden_markov_model>::type\n read_hidden_markov_model(std::istream& in)\n {\n Expects(in);\n using matrix = typename hidden_markov_model::matrix;\n using row_vector = typename hidden_markov_model::row_vector;\n using index = typename hidden_markov_model::size_type;\n index states;\n index symbols;\n\n std::tie(states, symbols) = getdims(in);\n matrix A = read_ascii_matrix(in, states, states);\n matrix B = read_ascii_matrix(in, states, symbols);\n row_vector pi = read_ascii_matrix(in, 1, states);\n normalize_rows(A);\n normalize_rows(B);\n normalize_rows(pi);\n\n Ensures(A.rows() == states && A.cols() == states);\n Ensures(B.rows() == states && B.cols() == symbols);\n Ensures(pi.rows() == 1 && pi.cols() == states);\n return hidden_markov_model(A, B, pi);\n }\n\n template \n typename std::enable_if<\n std::is_floating_point::value,\n void>::type\n print_model_parameters(std::ostream& out, hidden_markov_model const& model)\n {\n out << \"N= \" << model.states() << \"\\n\";\n out << \"M= \" << model.symbols() << \"\\n\";\n out << \"A:\\n\" << model.A << \"\\n\";\n out << \"B:\\n\" << model.B << \"\\n\";\n out << \"pi:\\n\" << model.pi << \"\\n\";\n out << std::flush;\n }\n\n template \n size_type read_sequence_length(std::istream& in)\n {\n std::string line;\n std::getline(in, line);\n std::istringstream linestream(line);\n size_type length;\n linestream >> length;\n return length;\n }\n\n template \n std::map\n read_symbol_map(std::istream& in)\n {\n std::map symbol_to_index;\n Integral count{};\n std::string buffer;\n std::getline(in, buffer);\n std::istringstream lstream(buffer);\n while (lstream >> buffer)\n if (symbol_to_index.insert(make_pair(buffer, count)).second)\n ++count;\n return symbol_to_index;\n }\n\n template \n std::vector\n read_sequence(std::istream& in)\n {\n std::vector sequence;\n std::map symbol_to_index = read_symbol_map(in);\n sequence.reserve(read_sequence_length(in));\n auto symbol_map = [&symbol_to_index] (std::string const& symbol) {\n auto found = symbol_to_index.find(symbol);\n if (found == symbol_to_index.end())\n throw read_sequence_error(\"Unkown Symbols in Input.\");\n return found->second;\n };\n auto sequence_input = ranges::istream_range(in);\n ranges::copy(sequence_input | ranges::view::transform(symbol_map), ranges::back_inserter(sequence));\n return sequence;\n }\n\n template \n std::vector\n read_sequence(std::istream& in, std::map& symbol_to_index)\n {\n MAIKEL_PROFILER;\n std::vector sequence;\n sequence.reserve(read_sequence_length(in));\n auto symbol_map = [&symbol_to_index] (Symbol const& symbol) {\n auto found = symbol_to_index.find(symbol);\n if (found == symbol_to_index.end())\n throw read_sequence_error(\"Unkown Symbols in Input.\");\n return found->second;\n };\n auto sequence_input = ranges::istream_range(in);\n ranges::copy(sequence_input | ranges::view::transform(symbol_map), ranges::back_inserter(sequence));\n return sequence;\n }\n} // namespace hmm\n} // namespace maikel\n\n#endif /* HMM_IO_H_ */\n", "meta": {"hexsha": "640e11d981b723b573644deb5514e70520e72882", "size": 6901, "ext": "h", "lang": "C", "max_stars_repo_path": "include/maikel/hmm/io.h", "max_stars_repo_name": "maikel/hidden-markov-model", "max_stars_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T07:16:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:16:01.000Z", "max_issues_repo_path": "include/maikel/hmm/io.h", "max_issues_repo_name": "maikel/Hidden-Markov-Model", "max_issues_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/maikel/hmm/io.h", "max_forks_repo_name": "maikel/Hidden-Markov-Model", "max_forks_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1633663366, "max_line_length": 106, "alphanum_fraction": 0.6468627735, "num_tokens": 1677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176237, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4104142985064465}} {"text": "/*! \\file profile_coord_map.h\n \\brief Grid initialization, finding flux coordinates, and getting profile data\n\n Called by all the top-level functions.\n */\n\n\n#include \n#include \n#include \n#include \n#include \t// needed for 2-d root-finding\n#include \n#include \n#include \"eq_quantity.h\"\n\n\n#ifndef REAL_TYPEDEF\n#define REAL_TYPEDEF\n#ifndef single\t\t\t// compiler option determines variable size\ntypedef double REAL;\n#else\ntypedef float REAL;\n#endif\n#endif\n\n#ifndef DEBUG\t\t\t// default debug level: no output to stderr\n#define DEBUG 0\n#endif\n\n#ifndef DEVELOPMENT\t\t// default development level: use the best of what has been tested to work\n#define DEVELOPMENT 0\n#endif\n\n#ifndef VERBOSE\n#define VERBOSE 0\n#endif\n\n#define MAX_N_TRIES 4\t\t// number of times to try to get the root-finder unstuck\n\n// used by desiredrz: constants to choose the desired grid in R,Z space\n// used by desiredxyz: constants for desired 3d grid in x,y,z\nextern double Xmin,Xmax,Ymin,Ymax,Zmin,Zmax;\n\n// used by getAllProfiles\n#define NORM_TO_KEV 4.7894e4 // conversion constant from normalized units to keV (called Tem_00 in fortran files) Normalization in GTS: Length 100cm, Time Deuterium Cyclotron frequency in 1T B field -- OMEGA_D^-1,\n// T normalized st. vth = sqrt(T). Temperature has the energy dimention.\n\n#define INVCM3_TO_INVM3 1e6\t// convert cm^{-3} to m^{-3}\n\n\n// used by decayNToutsideLCFS and getBoundaryPoints\n#define ABOUNDARY 0.9\n#define AINSIDE 0.88\n#define AZERO 1.2\n//#define DECAY_SCALING 0.1*(ABOUNDARY-AINSIDE) // the 0.1 makes it drop off faster\n\n#define MINIMUM(x,y) ((x) < (y) ? (x) : (y))\n\nextern char* NTFileName;\n\n// ---------- local function declarations\nint cylToLargeAR(REAL R[],REAL Z[], REAL r[], REAL theta[],int n,REAL R0,REAL Z0);\nint largeARtoCyl(REAL r[],REAL theta[], REAL R[], REAL Z[],int n,REAL R0,REAL Z0);\nint desiredrz(REAL R[],REAL Z[],REAL R1d[],REAL Z1d[],int nr,int nz,REAL R0,REAL Z0);\nint desiredxyz(int nx,int ny,int nz,REAL x1d[],REAL y1d[],REAL z1d[],REAL x[],REAL y[],REAL z[],REAL R0,REAL Z0);\nint mesh2dGrid(REAL x2d[],REAL y2d[],REAL x1d[],REAL y1d[],int nx,int ny);\nint mesh3dGrid(REAL x3d[],REAL y3d[],REAL z3d[],REAL x1d[],REAL y1d[],REAL z1d[],int nx,int ny,int nz);\n\nint guessatheta(REAL a[],REAL theta[], REAL R[], REAL Z[],int n,REAL R0,REAL Z0);\nREAL error_amt(REAL R,REAL Z,REAL a,REAL theta);\nvoid print_state(size_t iter, gsl_multiroot_fsolver * s);\nint findcorrectatheta(REAL a[],REAL theta[],REAL Ract[],REAL Zact[],REAL Bm[],REAL Rwant[], REAL Zwant[],int n,int flag[],int location[],int mismatch[]);\nint coord_f(const gsl_vector *x,void *params,gsl_vector *f);\nint getBoundaryPoints(double** R_bdy,double** Z_bdy,int n_bdy);\nvoid free_BoundaryPoints(double* R_bdy,double* Z_bdy);\n\nint get_mag_axis(REAL coords[]);\nint decayNToutsideLCFS(int npts,REAL a[],REAL ne[],REAL Te[],REAL Ti[],int* flag);\n\nint getFluxCoords(int npts,REAL a[],REAL theta[],REAL Bm[],REAL Ract[],REAL Zact[],REAL Rinitial[],REAL Zinitial[],REAL Rwant[],REAL Zwant[],REAL mag_axis_coords[],int flag[],int location[], int mismatch[]);\n\nint getAllProfiles(int npts,REAL Bpol[],REAL BR[],REAL BZ[],REAL Ti[],REAL Te[],REAL P[],REAL ne[],REAL qprofile[],REAL a[],REAL theta[],REAL Rwant[],REAL Zwant[],REAL R_bdy[],REAL Z_bdy[],int InOutFlag[],int location[]);\n\nint getProfile(REAL a,REAL* ne,REAL* Ti,REAL* Te,REAL* a_p,REAL* n_p,REAL* Ti_p,REAL* Te_p,int n_prof );\n\nint adiabaticElectronResponse(int npts,int ntimesteps,REAL ne_tilde[],REAL ne0[],REAL phi[],REAL Te[],int flag[]);\n\n//modified by Lei Shi adding function to find the outside points\n\n//declaration\nvoid inner_check(double R[],double Z[],double R_bdy[],double Z_bdy[],int flag[],int n,int n_bdy,double tol);\n//R,Z contains grid point coordinates, R_bdy Z_bdy contains boundary points, flag show inside(with value 1) and outside(with value 0), n the number of grid points, n_bdy the number of boundary points.\n\n//if (R[i],Z[i]) is inside or on the boundary of the contour specified by R_bdy and Z_bdy, flag[i] is set to 1, otherwise 0;\n\n//definition\n\nint horipos_check(double Rc,double Zc, double R1,double Z1,double R2,double Z2,double tol){\n double R=R1+ (Zc-Z1)/(Z2-Z1)*(R2-R1);\n\n if(fabs(R-Rc)<=tol)\n return 2;\n else if(R 1\n fprintf(stderr,\"desiredrz: dx:%g,dy:%g,dz:%g\\n\",dx,dy,dz);\n#endif\n for(i=0;i= 0\n\n REAL rwant[n],polwant[n];\n k = cylToLargeAR(R,Z,rwant,polwant,n,R0,Z0);// the minor radius and polodial angles of the R,Z we want\n\n // --- current method: 2D interpolation for 2 variables:\n // (rgrid,polgrid) -> a\n // (rgrid,polgrid) -> theta\n REAL agrid[ngrid],thetagrid[ngrid],Rgrid[ngrid],Zgrid[ngrid];\n REAL rgrid[ngrid],polgrid[ngrid],Bgrid[ngrid];\n\n // set up a grid to interpolate on\n // use to get an even grid in a,theta\n double da = 1.5/(n1dgrid-1);\n double dtheta = 2.0*M_PI/n1dgrid;\n for(i=0;i (agrid,thetagrid)\n // to get (rwant,thetawant) -> (a,theta)\n k = interp2d(n,ngrid,rwant,polwant,a,theta,rgrid,polgrid,agrid,thetagrid);\n\n#if DEBUG > 0\n fprintf(stderr,\"point agrid thetagrid Rgrid Zgrid rgrid polgrid\\n\");\n for(i=0;i2.5) a[i]=2.5;\t// limit the maximum radial flux coord\n\n#endif\n\n\n // // --- previous method: 1D interpolation of both variables independently\n // // polgrid -> (agrid=1,thetagrid)\n // // rgrid -> (agrid,thetagrid=pi/6)\n\n // REAL agrid[n1dgrid],thetagrid[n1dgrid],Rgrid[n1dgrid],Zgrid[n1dgrid];\n // REAL rgrid[n1dgrid],polgrid[n1dgrid],Bgrid[n1dgrid];\n\n // // first do the poloidal interpolation\n // double dtheta = 2*M_PI/n1dgrid;\n // for(i=0;iRwant; // desired R,Z\n REAL Zwant = ((struct coordparams *) params)->Zwant;\n\n REAL a[1] = {gsl_vector_get (x, 0)}; // current a,theta\n REAL theta[1] = {gsl_vector_get (x, 1)};\n int n=1;\n int k;\n REAL Ract[1],Zact[1],Bm[1]; // actual R,Z at this value of a,theta\n\n if(!finite(a[0])) a[0] = ABOUNDARY; // in portalr4 this was necessary to eliminate faults\n if(!finite(theta[0])) theta[0] = 0.0;\n\n k = esigetrzb_(Ract,Zact,Bm,a,theta,&n); // solve for the actual R,Z values\n\n gsl_vector_set (f, 0, Rwant-Ract[0]); // the error\n gsl_vector_set (f, 1, Zwant-Zact[0]);\n return GSL_SUCCESS;\n}\n\n//! returns the distance between desired (R,Z) position and the position mapped to by flux coords (a,theta)\nREAL error_amt(REAL R,REAL Z,REAL a,REAL theta){\n REAL Ract,Zact,Bact;\n int single=1;\n esigetrzb_(&Ract,&Zact,&Bact,&a,&theta,&single);\n\n // return sqrt((R-Ract)*(R-Ract)+(Z-Zact)*(Z-Zact));\n return hypot(R-Ract,Z-Zact);\n}\n\n//! Print current status of the root-finder\nvoid print_state(size_t iter, gsl_multiroot_fsolver * s){\n fprintf (stderr,\"iter = %3u x = % .3f % .3f \"\n\t \"f(x) = % .3e % .3e\\n\",\n\t iter,\n\t gsl_vector_get (s->x, 0),\n\t gsl_vector_get (s->x, 1),\n\t gsl_vector_get (s->f, 0),\n\t gsl_vector_get (s->f, 1));\n}\n\n//! performs 2D root finding to get the (a,theta) for an array of given (R,Z) values\n/*! Uses the gsl mulidimensional hybrids root solver ``gsl_multiroot_fsolver_hybrids''. */\n// Modified by Lei Shi\n// use function esirz2agq to find (a,theta) for a given (R,Z) inside LCFS, and treat outside points seperately\n\n//write CDF function show the flags\n\ninline void ERR_CI(int e,const char* s)\n{\n fprintf(stderr,\"error:%s in %s\\n\",nc_strerror(e),s);\n exit(e);\n}\n\nvoid writeCDF(char* fname,int ntotal, double R[],double Z[],int n_bdy,double R_bdy[],double Z_bdy[],int flag[]){\n int R_dim_id,Z_dim_id,R_bdy_dim_id,Z_bdy_dim_id,flag_dim_id;\n int nr_id,nz_id,ntotal_id,n_bdy_id;\n int R_id,Z_id,R_bdy_id,Z_bdy_id,flag_id;\n int f_id;\n int ecode;\n if(ecode=nc_create(fname,NC_CLOBBER,&f_id))\n ERR_CI(ecode,\"create file\");\n if(ecode=nc_def_dim(f_id,\"r_dim\",ntotal,&R_dim_id))\n ERR_CI(ecode,\"def r dim\");\n if(ecode=nc_def_dim(f_id,\"z_dim\",ntotal,&Z_dim_id))\n ERR_CI(ecode,\"def z dim\");\n if(ecode=nc_def_dim(f_id,\"r_bdy_dim\",n_bdy,&R_bdy_dim_id))\n ERR_CI(ecode,\"def r_bdy dim\");\n if(ecode=nc_def_dim(f_id,\"z__bdy_dim\",n_bdy,&Z_bdy_dim_id))\n ERR_CI(ecode,\"def z_bdy dim\");\n if(ecode=nc_def_dim(f_id,\"flag_dim\",ntotal,&flag_dim_id))\n ERR_CI(ecode,\"def flag dim\");\n if(ecode=nc_def_var(f_id,\"nr\",NC_INT,0,NULL,&nr_id))\n ERR_CI(ecode,\"def nr var\");\n if(ecode=nc_def_var(f_id,\"nz\",NC_INT,0,NULL,&nz_id))\n ERR_CI(ecode,\"def nz var\");\n if(ecode=nc_def_var(f_id,\"ntotal\",NC_INT,0,NULL,&ntotal_id))\n ERR_CI(ecode,\"def ntotal var\");\n if(ecode=nc_def_var(f_id,\"n_bdy\",NC_INT,0,NULL,&n_bdy_id))\n ERR_CI(ecode,\"def n_bdy var\");\n if(ecode=nc_def_var(f_id,\"r\",NC_DOUBLE,1,&R_dim_id,&R_id))\n ERR_CI(ecode,\"def r var\");\n if(ecode=nc_def_var(f_id,\"z\",NC_DOUBLE,1,&Z_dim_id,&Z_id))\n ERR_CI(ecode,\"def z var\");\n if(ecode=nc_def_var(f_id,\"r_bdy\",NC_DOUBLE,1,&R_bdy_dim_id,&R_bdy_id))\n ERR_CI(ecode,\"def r_bdy var\");\n if(ecode=nc_def_var(f_id,\"z_bdy\",NC_DOUBLE,1,&Z_bdy_dim_id,&Z_bdy_id))\n ERR_CI(ecode,\"def z_bdy var\");\n if(ecode=nc_def_var(f_id,\"flag\",NC_INT,1,&flag_dim_id,&flag_id))\n ERR_CI(ecode,\"def flag var\");\n if(ecode=nc_enddef(f_id))\n ERR_CI(ecode,\"enddef\");\n\n\n if(ecode=nc_put_var_int(f_id,nr_id,&ntotal))\n ERR_CI(ecode,\"put nr var\");\n if(ecode=nc_put_var_int(f_id,nz_id,&ntotal))\n ERR_CI(ecode,\"put nz var\");\n if(ecode=nc_put_var_int(f_id,ntotal_id,&ntotal))\n ERR_CI(ecode,\"put ntotal var\");\n if(ecode=nc_put_var_int(f_id,n_bdy_id,&n_bdy))\n ERR_CI(ecode,\"put n_bdy var\");\n if(ecode=nc_put_var_double(f_id,R_id,R))\n ERR_CI(ecode,\"put R var\");\n if(ecode=nc_put_var_double(f_id,Z_id,Z))\n ERR_CI(ecode,\"put Z var\");\n if(ecode=nc_put_var_double(f_id,R_bdy_id,R_bdy))\n ERR_CI(ecode,\"put R_bdy var\");\n if(ecode=nc_put_var_double(f_id,Z_bdy_id,Z_bdy))\n ERR_CI(ecode,\"put Z_bdy var\");\n if(ecode=nc_put_var_int(f_id,flag_id,flag))\n ERR_CI(ecode,\"put flag var\");\n\n if(ecode=nc_close(f_id))\n ERR_CI(ecode,\"close file\");\n\n FILE* txtfile;\n txtfile=fopen(\"./bdy_out.txt\",\"w\");\n fprintf(txtfile,\"%d\\n\",n_bdy);\n int i;\n for(i=0;i match_tol){\n\tfprintf(errlog,\"Point %d (%lf,%lf) %lf away from axis has been mapped %lf away\\n\",i,Rwant[i],Zwant[i],dis,err);\n\tmismatch[i] = 1;\n\t//fprintf(stderr,\"Point %d (%lf,%lf) %lf away from axis has been mapped %lf away\\n\",i,Rwant[i],Zwant[i],dis,err);\n\tif(fabs(Zwant[i])<0.1)\n\t{\n\t a[i]=0;\n\t theta[i]=0;\n\t}\n }\n location[i]=-1; // inside points do not need location information\n }\n else if(flag[i]==0){\n // fprintf(stderr,\"outter point.\\n\");\n Bm[i]=b_axis*mag_axis_coords[0]/Rwant[i]; // let B inversely proportional to R, based on B on axis\n Ract[i]=Rwant[i];\n Zact[i]=Zwant[i];\n Z_rel=Zwant[i]-mag_axis_coords[1];\n R_rel=Rwant[i]-mag_axis_coords[0];\n int quarter=0;\n if(R_rel>=0){\n\tif(Z_rel>=0) quarter=1;\n\telse quarter =4;\n }\n else{\n\tif(Z_rel>=0) quarter=2;\n\telse quarter=3;\n }\n\n theta_guess=atan((Z_rel/R_rel));\n if(quarter == 2 || quarter == 3)\n\ttheta_guess += M_PI;\n if(quarter == 4)\n\ttheta_guess += 2*M_PI;\n\n Z_rel=Z_bdy[0]-mag_axis_coords[1];\n R_rel=R_bdy[0]-mag_axis_coords[0];\n theta_bdy=atan((Z_rel/R_rel));\n\n if(R_rel>=0){\n\tif(Z_rel>0) quarter=1;\n\telse quarter =4;\n }\n else{\n\tif(Z_rel>0) quarter=2;\n\telse quarter=3;\n }\n if(quarter == 2 || quarter == 3)\n\ttheta_bdy+=M_PI;\n if(quarter == 4)\n\ttheta_bdy += 2*M_PI;\n\n\n sign_ini=(theta_guess>=theta_bdy)?1:-1;\n\n int j;\n for(j=0;j=0){\n\t if(Z_rel>0) quarter=1;\n\t else quarter =4;\n\t }\n\t else{\n\t if(Z_rel>0) quarter=2;\n\t else quarter=3;\n\t }\n\t if(quarter == 2 || quarter == 3)\n\t theta_bdy+=M_PI;\n\t if(quarter == 4)\n\t theta_bdy += 2*M_PI;//set the theta into (0,2Pi]\n\n\t sign_cur=theta_guess>=theta_bdy?1:-1;\n\t if(sign_ini*sign_cur<0){ //if passes the theta we want and is not on the opposite side, then we find the right boundary point\n\t location[i]=j;\n\t break;\n\t }\n\t\n\t}\n if(j==NBOUNDARY)\n\tlocation[i]=0;\n\n Z_rel=Zwant[i]-mag_axis_coords[1];\n R_rel=Rwant[i]-mag_axis_coords[0];\n // fprintf(stderr,\"start guess a\\n\");\n a_guess=sqrt((Z_rel*Z_rel+R_rel*R_rel)/((R_bdy[loc]-mag_axis_coords[0])*(R_bdy[loc]-mag_axis_coords[0])+(Z_bdy[loc]-mag_axis_coords[1])*(Z_bdy[loc]-mag_axis_coords[1])))*a_bdy;\n a[i]=a_guess;\n theta[i]=2*M_PI/NBOUNDARY*loc;\n\n }\n else{\n fprintf(stderr,\"flag error: point %d at (%lf,%lf) has flag %d.\\n\",i,Rwant[i],Zwant[i],flag[i]);\n exit(5);\n }\n }\n fprintf(stderr,\"finish getting locations.\\n\");\n fclose(errlog);\n return 0;\n\n /*old version by Erik\n // declarations for root solver\n const gsl_multiroot_fsolver_type *T;\n gsl_multiroot_fsolver *s;\n int status;\t\t\t// status of root-finder (notifies if stuck, etc)\n\n size_t iter = 0;\n int i;\n int ntries;\t\t\t// num of times for this point that we get stuck\n const size_t ndims = 2;\t// 2D coordinate\n struct coordparams p;\t\t// parameters used by ea. instance of solver: Rwant,Zwant\n gsl_multiroot_function f = {&coord_f, ndims, &p}; // root solver setup\n gsl_vector *x = gsl_vector_alloc (ndims); // R,Z values used by root solver\n\n T = gsl_multiroot_fsolver_hybrids; // solver type\n s = gsl_multiroot_fsolver_alloc (T, 2);\n\n\n // loop over all points\n for(i=0;i0){\n if(error_amt(Rwant[i],Zwant[i],a[i],theta[i]) > error_amt(Rwant[i],Zwant[i],a[i-1],theta[i-1])){ // if the nearest point is a better guess than the default initial guess, use the previous point\n\ta[i] = a[i-1];\n\ttheta[i] = theta[i-1];\n }\n }\n\n // set up this instance of the root finder\n p.Rwant = Rwant[i];\t\t// pass the desired coordinates as parameters\n p.Zwant = Zwant[i];\n gsl_vector_set (x, 0, a[i]);\n gsl_vector_set (x, 1, theta[i]);\n\n // try a few times with different initial conditions if the solver gets stuck\n for(ntries=0;ntries0){\n\t#if DEVELOPMENT <= 0\n\tgsl_vector_set(x,0,0.2);\n\tgsl_vector_set(x,1,0.25*M_PI+ 0.8*gsl_vector_get(x,1));\n\t#else\n\t//\tgsl_vector_set(x,0,0.2 + fmod(0.3+gsl_vector_get(x,0),1.2));\n\tgsl_vector_set(x,0,0.2 + fmod(0.4+gsl_vector_get(x,0),2.0));\n\t//\tgsl_vector_set(x,1,-M_PI + fmod(1.5*M_PI+gsl_vector_get(x,1),2.0*M_PI));\n\tgsl_vector_set(x,1,-M_PI + fmod(1.25*M_PI+gsl_vector_get(x,1),2.0*M_PI));\n\t#endif\n }\n gsl_multiroot_fsolver_set (s, &f, x); // initialize the root finder\n iter = 0;\t\t\t// reset iteration counter\n do{\n\titer++;\n\tstatus = gsl_multiroot_fsolver_iterate (s);\n#if DEBUG > 0\n\tfprintf(stderr,\"point:%d, ntries:%d, status:%d, \",i,ntries,status);\n\tprint_state (iter, s);\t// uncomment to give info at each iteration\n#endif\n\tif (status){ // check if solver is stuck\n\t break;\n\t}\n\tstatus = gsl_multiroot_test_residual (s->f, 1e-7);\n }while (status == GSL_CONTINUE && iter < 200);\n\n }\n\n a[i] = gsl_vector_get(s->x,0);\n theta[i] = gsl_vector_get(s->x,1);\n }\n\n gsl_multiroot_fsolver_free (s);\n gsl_vector_free (x);\n\n // make sure all radial flux coords are positive (a>0)\n for(i=0;i 0\n REAL err_dist;\n\n //modified by Lei start\n const int NBOUNDARY=4000;\n double R_bdy[NBOUNDARY],Z_bdy[NBOUNDARY];\n getBoundaryPoints(R_bdy,Z_bdy,NBOUNDARY);\n\n // for(i=0;i 1e-7)//if the error is unnormally large, try to find a reasonable a and theta for that point, and adjust the B value\n {\n\t//\tfprintf(stderr,\"Warning, point %d is mapped %.4g [m] away from requested position.\\n\",i,err_dist);\n\n\tint single_point=1;\n\tdouble zero=0;\n\tdouble b; // B field on the axis\n\tdouble theta_guess;\n\tdouble theta_bdy;\n\tdouble a_guess;\n\tdouble a_bdy=1;\n\n\tdouble Z_rel;//the relative Z respect to mag_axis\n\tdouble R_rel;//the relative R respect to mag_axis\n\t\n\tdouble mag_axis_coords[2];\n\tint loc;\n\tint sign_ini;\n\tint sign_cur;\n\n\tesigetrzb_(&mag_axis_coords[0],&mag_axis_coords[1],&b,&zero,&zero,&single_point);\n\n\tBm[i]=b*mag_axis_coords[0]/Rwant[i]; // let B inversely proportional to R, based on B on axis\n\n\tZ_rel=Zwant[i]-mag_axis_coords[1];\n\tR_rel=Rwant[i]-mag_axis_coords[0];\n\n\ttheta_guess=atan((Z_rel/R_rel));\n\tif(theta_guess<=0)\n\t theta_guess += 2*M_PI;\n\ttheta_bdy=atan((Z_bdy[0]-mag_axis_coords[1])/(R_bdy[0]-mag_axis_coords[0]));\n\tif(theta_bdy<=0)\n\t theta_bdy+=2*M_PI;\n\tsign_ini=(theta_guess>=theta_bdy)?1:-1;\n\t//\tfprintf(stderr,\"pt[%d]:\\n sign_ini = %d\\n\",i,sign_ini);\n\tint j;\n\tfor(j=0;j=theta_bdy?1:-1;\n\t if(sign_ini*sign_cur<0 && Zwant[i]*Z_bdy[j]>=0){ //if passes the theta we want and is not on the opposite side, then we find the right boundary point\n\t\n\t loc=j;\n\t break;\n\t }\n\t\n\t }\n\n\ta_guess=sqrt((Z_rel*Z_rel+R_rel*R_rel)/((R_bdy[loc]-mag_axis_coords[0])*(R_bdy[loc]-mag_axis_coords[0])+(Z_bdy[loc]-mag_axis_coords[1])*(Z_bdy[loc]-mag_axis_coords[1])))*a_bdy;\n\ta[i]=a_guess;\n\ttheta[i]=2*M_PI/NBOUNDARY*loc;\n\t//\tif(theta_bdy>M_PI)\n\t// fprintf(stderr,\"sign_cur=%d\\n loc= %d,Rwant=%lf, Zwant=%lf, theta=%lf, Rbd=%lf, Zbd=%lf, thetabd=%lf, a=%lf\",sign_cur,loc,Rwant[i],Zwant[i],theta_guess,R_bdy[loc],Z_bdy[loc],theta_bdy,a[i]);\n }\n }\n\n //Modified by Lei End\n#endif\n\n\nold version ends*/\n}\n\n//! Calculates the (R,Z) coordinates of the boundary of the last-closed-flux-surface\n/*! Assumes the LCFS is given by the macro ABOUNDARY (set to 1.0 by default) */\nint getBoundaryPoints(double** R_bdy,double** Z_bdy,int n_bdy){\n double dtheta = 2*M_PI/(n_bdy-1);\n double a[n_bdy],theta[n_bdy],B_bdy[n_bdy];\n *R_bdy = (double*)xmalloc(sizeof(double)*n_bdy);\n *Z_bdy = (double*)xmalloc(sizeof(double)*n_bdy);\n int i,k;\n for(i=0;i1.0){\n// ne[i] = nebound*exp((a[i]-abound)/lambda_ne);\n// Te[i] = tebound*exp((a[i]-abound)/lambda_te);\n// Ti[i] = tibound*exp((a[i]-abound)/lambda_ti);\n// }\n int i;\n for(i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"disjoint_set_data_structure.h\"\n#include \"permutation.h\"\n\ntemplate\nclass path_merger {\npublic:\n\texplicit path_merger(UniformRandomBitGenerator& g) noexcept;\n\tpermutation operator()(const permutation& lhs, const permutation& rhs);\nprivate:\n\tusing edge_type = std::pair;\n\tusing edge_vector = std::vector;\n\tedge_vector to_edges(const permutation& perm) const;\n\tpermutation to_permutation(const edge_vector& edges) const;\n\tUniformRandomBitGenerator& rand;\n};\n\ntemplate\npath_merger::path_merger(UniformRandomBitGenerator& g) noexcept\n\t: rand(g) {}\n\ntemplate\npermutation path_merger::operator()(const permutation& lhs, const permutation& rhs) {\n\tExpects(lhs.size() == rhs.size());\n\tExpects(lhs.size() > 0);\n\tconst std::size_t size = lhs.size();\n\tedge_vector lhs_edges = to_edges(lhs);\n\tedge_vector rhs_edges = to_edges(rhs);\n\tedge_vector result_edges;\n\tresult_edges.reserve(size);\n\tstd::set_intersection(lhs_edges.begin(), lhs_edges.end(), rhs_edges.begin(), rhs_edges.end(), std::back_inserter(result_edges));\n\tdisjoint_set_data_structure components(size);\n\tstd::vector missing_edges(size, 2);\n\tfor (const auto& [left, right] : result_edges) {\n\t\tcomponents.merge(left, right);\n\t\tgsl::at(missing_edges, left)--;\n\t\tgsl::at(missing_edges, right)--;\n\t}\n\tstd::shuffle(lhs_edges.begin(), lhs_edges.end(), rand);\n\tstd::shuffle(rhs_edges.begin(), rhs_edges.end(), rand);\n\tgsl::span spans[2] {lhs_edges, rhs_edges};\n\twhile (!std::all_of(std::begin(spans), std::end(spans), std::mem_fn(&gsl::span::empty))) {\n\t\tfor (auto&& span : spans) {\n\t\t\tauto it = std::find_if(span.begin(), span.end(), [&](const edge_type& edge) {\n\t\t\t\tconst auto& [lhs, rhs] = edge;\n\t\t\t\treturn gsl::at(missing_edges, lhs) && gsl::at(missing_edges, rhs) && components.find(lhs) != components.find(rhs);\n\t\t\t});\n\t\t\tif (it != span.end()) {\n\t\t\t\tconst auto& [left, right] = *it;\n\t\t\t\tresult_edges.emplace_back(left, right);\n\t\t\t\tcomponents.merge(left, right);\n\t\t\t\tgsl::at(missing_edges, left)--;\n\t\t\t\tgsl::at(missing_edges, right)--;\n\t\t\t}\n\t\t\tspan = span.subspan(it - span.begin());\n\t\t}\n\t}\n\tstd::stack> s;\n\tfor (unsigned i = 0; i < size; i++) {\n\t\trepeat(gsl::at(missing_edges, i), [&] {\n\t\t\tif (!s.empty() && components.find(s.top()) != components.find(i)) {\n\t\t\t\tconst unsigned& left = s.top();\n\t\t\t\tconst unsigned& right = i;\n\t\t\t\tresult_edges.emplace_back(left, right);\n\t\t\t\tcomponents.merge(left, right);\n\t\t\t\tgsl::at(missing_edges, left)--;\n\t\t\t\tgsl::at(missing_edges, right)--;\n\t\t\t\ts.pop();\n\t\t\t} else {\n\t\t\t\ts.push(i);\n\t\t\t}\n\t\t});\n\t}\n\tif (!s.empty()) {\n\t\tconst unsigned left = s.top();\n\t\ts.pop();\n\t\tconst unsigned& right = s.top();\n\t\tresult_edges.emplace_back(left, right);\n\t}\n\tEnsures(result_edges.size() == lhs.size());\n\treturn to_permutation(result_edges);\n}\n\ntemplate\nauto path_merger::to_edges(const permutation& perm) const -> edge_vector {\n\tExpects(perm.size() > 0);\n\tedge_vector result {std::minmax({perm.front(), perm.back()})};\n\tresult.reserve(perm.size());\n\tstd::transform(std::next(perm.begin()), perm.end(), perm.begin(), std::inserter(result, result.end()), [](unsigned lhs, unsigned rhs) {\n\t\treturn std::minmax({lhs, rhs});\n\t});\n\tstd::sort(result.begin(), result.end());\n\tEnsures(result.size() == perm.size());\n\treturn result;\n}\n\ntemplate\npermutation path_merger::to_permutation(const edge_vector& edges) const {\n\tExpects(edges.size() > 0);\n\tconst std::size_t size = edges.size();\n\tstd::vector> graph(size);\n\tfor (auto&& node : graph) {\n\t\tnode.reserve(2);\n\t}\n\tfor (const auto& [lhs, rhs] : edges) {\n\t\tgsl::at(graph, lhs).push_back(rhs);\n\t\tgsl::at(graph, rhs).push_back(lhs);\n\t}\n\tpermutation result(size);\n\tunsigned prev = 0;\n\tunsigned cur = graph.front().front();\n\tstd::for_each(std::next(result.begin()), result.end(), [&](unsigned& element) {\n\t\telement = cur;\n\t\tconst auto& node = gsl::at(graph, cur);\n\t\tunsigned next = node.front() == prev ? node.back() : node.front();\n\t\tprev = cur;\n\t\tcur = next;\n\t});\n\tEnsures(result.size() == edges.size());\n\treturn result;\n}\n\n\n#endif\n", "meta": {"hexsha": "d221aad4e9f641e6ce0691dc1d2315898ddc47a3", "size": 5848, "ext": "h", "lang": "C", "max_stars_repo_path": "SalesmanExample/path_merger.h", "max_stars_repo_name": "SirEmentaler/Eugenics-Wars", "max_stars_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SalesmanExample/path_merger.h", "max_issues_repo_name": "SirEmentaler/Eugenics-Wars", "max_issues_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SalesmanExample/path_merger.h", "max_forks_repo_name": "SirEmentaler/Eugenics-Wars", "max_forks_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.55, "max_line_length": 136, "alphanum_fraction": 0.695622435, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4102067451239238}} {"text": "/* multifit_nlinear/scaling.c\n * \n * Copyright (C) 2015, 2016 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/*\n * This module handles the updating of the scaling matrix D_k in the\n * trust region subproblem:\n *\n * min m_k (dx), || D_k dx || <= Delta_k\n *\n * where m_k(dx) is a model which approximates the cost function\n * F(x_k + dx) near the current iteration point x_k\n *\n * D_k can be updated according to several different strategies.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic int init_diag_levenberg(const gsl_matrix * J, gsl_vector * diag);\nstatic int update_diag_levenberg(const gsl_matrix * J,\n gsl_vector * diag);\n\nstatic int init_diag_marquardt(const gsl_matrix * J, gsl_vector * diag);\nstatic int update_diag_marquardt (const gsl_matrix * J,\n gsl_vector * diag);\n\nstatic int init_diag_more(const gsl_matrix * J, gsl_vector * diag);\nstatic int update_diag_more(const gsl_matrix * J, gsl_vector * diag);\n\n/* Levenberg scaling, D = I */\nstatic int\ninit_diag_levenberg(const gsl_matrix * J, gsl_vector * diag)\n{\n (void)J; /* avoid unused parameter warning */\n gsl_vector_set_all(diag, 1.0);\n return GSL_SUCCESS;\n}\n\nstatic int\nupdate_diag_levenberg(const gsl_matrix * J, gsl_vector * diag)\n{\n (void)J; /* avoid unused parameter warning */\n (void)diag; /* avoid unused parameter warning */\n\n /* nothing to do */\n return GSL_SUCCESS;\n}\n\n/* initialize diagonal scaling matrix D according to Marquardt method */\nstatic int\ninit_diag_marquardt(const gsl_matrix * J, gsl_vector * diag)\n{\n return update_diag_marquardt(J, diag);\n}\n\n/* update diagonal scaling matrix D according to Marquardt method */\nstatic int\nupdate_diag_marquardt (const gsl_matrix * J, gsl_vector * diag)\n{\n const size_t p = J->size2;\n size_t j;\n\n for (j = 0; j < p; j++)\n {\n gsl_vector_const_view v = gsl_matrix_const_column(J, j);\n double norm = gsl_blas_dnrm2(&v.vector);\n\n if (norm == 0.0)\n norm = 1.0;\n\n gsl_vector_set(diag, j, norm);\n }\n\n return GSL_SUCCESS;\n}\n\n/* initialize diagonal scaling matrix D according to Eq 6.3 of\n * More, 1978 */\nstatic int\ninit_diag_more(const gsl_matrix * J, gsl_vector * diag)\n{\n int status;\n\n gsl_vector_set_zero(diag);\n status = update_diag_more(J, diag);\n\n return status;\n}\n\n/* update diagonal scaling matrix D according to Eq. 6.3 of\n * More, 1978 */\nstatic int\nupdate_diag_more (const gsl_matrix * J, gsl_vector * diag)\n{\n const size_t p = J->size2;\n size_t j;\n\n for (j = 0; j < p; j++)\n {\n gsl_vector_const_view v = gsl_matrix_const_column(J, j);\n double norm = gsl_blas_dnrm2(&v.vector);\n double *diagj = gsl_vector_ptr(diag, j);\n\n if (norm == 0.0)\n norm = 1.0;\n\n *diagj = GSL_MAX(*diagj, norm);\n }\n\n return GSL_SUCCESS;\n}\n\nstatic const gsl_multifit_nlinear_scale levenberg_type =\n{\n \"levenberg\",\n init_diag_levenberg,\n update_diag_levenberg\n};\n\nstatic const gsl_multifit_nlinear_scale marquardt_type =\n{\n \"marquardt\",\n init_diag_marquardt,\n update_diag_marquardt\n};\n\nstatic const gsl_multifit_nlinear_scale more_type =\n{\n \"more\",\n init_diag_more,\n update_diag_more\n};\n\nconst gsl_multifit_nlinear_scale *gsl_multifit_nlinear_scale_levenberg = &levenberg_type;\nconst gsl_multifit_nlinear_scale *gsl_multifit_nlinear_scale_marquardt = &marquardt_type;\nconst gsl_multifit_nlinear_scale *gsl_multifit_nlinear_scale_more = &more_type;\n", "meta": {"hexsha": "fc2efda7cb0142b0ea6817e76aeaa76def9c07b2", "size": 4303, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit_nlinear/scaling.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/scaling.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/scaling.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.0628930818, "max_line_length": 89, "alphanum_fraction": 0.7127585406, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.41004541038919395}} {"text": "/*\nCopyright (c) 2015, Patrick Weltevrede\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. 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.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include \n#include \n#include \n#include \"psrsalsa.h\"\n#include \nint linalg_solve_matrix_eq_gauss_jordan(double *matrixa, double *matrixb, int n, int m, verbose_definition verbose)\n{\n int *orig_pivot_row, *orig_pivot_column, *pivot_column_done;\n int pivotnr, pivot_col, pivot_row, rowi, coli, i;\n double *ptr1, *ptr2, tmpvalue;\n double largest_element_value;\n int currow;\n orig_pivot_row = malloc(n*sizeof(int));\n orig_pivot_column = malloc(n*sizeof(int));\n pivot_column_done = malloc(n*sizeof(int));\n if(orig_pivot_row == NULL || orig_pivot_column == NULL || pivot_column_done == NULL) {\n printerror(verbose.debug, \"ERROR linalg_solve_matrix_eq_gauss_jordan: Memory allocation error.\");\n return 1;\n }\n for(coli = 0; coli < n; coli++)\n pivot_column_done[coli] = 0;\n for(pivotnr = 0; pivotnr < n; pivotnr++) {\n largest_element_value = -1.0;\n for(rowi = 0; rowi < n; rowi++) {\n if(pivot_column_done[rowi] != 1) {\n for(coli = 0; coli < n; coli++) {\n if(pivot_column_done[coli] == 0) {\n tmpvalue = matrixa[rowi*n+coli];\n if(fabs(tmpvalue) >= largest_element_value) {\n largest_element_value = fabs(tmpvalue);\n pivot_row=rowi;\n pivot_col=coli;\n }\n }else if(pivot_column_done[coli] > 1) {\n printerror(verbose.debug, \"ERROR linalg_solve_matrix_eq_gauss_jordan: The matrix equation is singular, no solution can be determined.\");\n return 2;\n }\n }\n }\n }\n if(largest_element_value <= 0.0) {\n printerror(verbose.debug, \"ERROR linalg_solve_matrix_eq_gauss_jordan: The matrix equation is singular, no solution can be determined.\");\n return 2;\n }\n pivot_column_done[pivot_col] += 1;\n if(pivot_row != pivot_col) {\n ptr1 = matrixa + pivot_row*n;\n ptr2 = matrixa + pivot_col*n;\n for(i = 0; i < n; i++) {\n tmpvalue = *ptr1;\n *ptr1 = *ptr2;\n *ptr2 = tmpvalue;\n }\n ptr1 = matrixb + pivot_row*n;\n ptr2 = matrixb + pivot_col*n;\n for(i = 0; i < n; i++) {\n tmpvalue = *ptr1;\n *ptr1 = *ptr2;\n *ptr2 = tmpvalue;\n }\n }\n orig_pivot_row[pivotnr] = pivot_row;\n orig_pivot_column[pivotnr] = pivot_col;\n matrixa[pivot_col*n+pivot_col]=1.0;\n ptr1 = matrixa + pivot_col*n;\n for(i = 0; i < n; i++) {\n *ptr1 /= largest_element_value;\n ptr1 += 1;\n }\n ptr1 = matrixb + pivot_col*m;\n for(i = 0; i < m; i++) {\n *ptr1 /= largest_element_value;\n ptr1 += 1;\n }\n for(currow = 0; currow < n; currow++) {\n if(currow != pivot_col) {\n i = currow*n+pivot_col;\n tmpvalue = matrixa[i];\n matrixa[i] = 0.0;\n ptr1 = matrixa + n*currow;\n ptr2 = matrixa + n*pivot_col;\n for(i=1; i <= n; i++) {\n *ptr1 -= (*ptr2)*tmpvalue;\n ptr1++;\n ptr2++;\n }\n ptr1 = matrixb + currow*m;\n ptr2 = matrixb + pivot_col*m;\n for(i = 0; i < m; i++) {\n *ptr1 -= (*ptr2)*tmpvalue;\n ptr1++;\n ptr2++;\n }\n }\n }\n }\n for(coli = n-1; coli >= 0; coli--) {\n if(orig_pivot_row[coli] != orig_pivot_column[coli]) {\n for(rowi = 0; rowi <= n; rowi++) {\n tmpvalue = matrixa[rowi*n+orig_pivot_row[coli]];\n matrixa[rowi*n+orig_pivot_row[coli]] = matrixa[rowi*n+orig_pivot_column[coli]];\n matrixa[rowi*n+orig_pivot_column[coli]] = tmpvalue;\n }\n }\n }\n free(pivot_column_done);\n free(orig_pivot_row);\n free(orig_pivot_column);\n return 0;\n}\n", "meta": {"hexsha": "552a49f006895308b6cdec9cbbcd7e24f7780ab1", "size": 4824, "ext": "c", "lang": "C", "max_stars_repo_path": "src/lib/linalg.c", "max_stars_repo_name": "David-McKenna/psrsalsa", "max_stars_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z", "max_issues_repo_path": "src/lib/linalg.c", "max_issues_repo_name": "David-McKenna/psrsalsa", "max_issues_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z", "max_forks_repo_path": "src/lib/linalg.c", "max_forks_repo_name": "David-McKenna/psrsalsa", "max_forks_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z", "avg_line_length": 38.2857142857, "max_line_length": 755, "alphanum_fraction": 0.6838723051, "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4098423005068695}} {"text": "/*\n* This file contains functions used to call sequential MKL/BLAS/LAPACK routines\n*\n* Authors : Sebastien Cayrols\n* : Olivier Tissot\n* Email : sebastien.cayrols@[(gmail.com) | (inria.fr)]\n* : olivier.tissot@inria.fr\n*/\n\n/******************************************************************************/\n/* INCLUDE */\n/******************************************************************************/\n/* STD */\n#include \n#include \n#include \n#include \n/* MKL/LAPACK */\n#ifdef LAPACKEACTIVATE\n #include \n #include \n#endif\n/* MPI */\n#include \n/* CPaLAMeM */\n//#include \"cpalamem_macro.h\"\n#undef TIMERACTIVATE\n#include \"cplm_utils.h\"\n#include \"cplm_timing.h\"\n#include \"cplm_matcsr.h\"\n#include \"cplm_kernels.h\"\n#include \"cplm_QS.h\"\n//#include \"cpalamem_instrumentation.h\"\n/******************************************************************************/\n\n/******************************************************************************/\n/* CODE */\n/******************************************************************************/\n\nint CPLM_MatDenseKernelCholesky(CPLM_Mat_Dense_t* C_io)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n int ierr = 0;\n int matrix_layout = 0;\n int order = 0;\n int lda = 0;\n char uplo = 0;\n\n CPLM_ASSERT(C_io != NULL);\n CPLM_ASSERT(C_io->val != NULL);\n\n matrix_layout = (C_io->info.stor_type == ROW_MAJOR) ? LAPACK_ROW_MAJOR\n : LAPACK_COL_MAJOR;\n uplo = 'U';\n order = C_io->info.n;\n lda = C_io->info.lda;\n\n ierr = LAPACKE_dpotrf( matrix_layout,\n uplo,\n order,\n C_io->val,\n lda);CPLM_CHKERR(ierr);\n if (ierr > 0)\n {\n CPLM_Abort(\"The matrix is not SPD!\");\n }\n\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n}\n\n//TODO Remove malloc and explain why H\nint CPLM_MatDenseKernelQR( CPLM_Mat_Dense_t* A_io,\n CPLM_Mat_Dense_t* H_io,\n int index_i,\n int index_j) //to be verified\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n int ierr = 0;\n int matrix_layout = -1;\n double *tau = NULL;\n\n tau = malloc(A_io->info.N*sizeof(double));\n CPLM_ASSERT(tau != NULL);\n\n matrix_layout = (A_io->info.stor_type == ROW_MAJOR) ? LAPACK_ROW_MAJOR\n : LAPACK_COL_MAJOR;\n\n ierr = LAPACKE_dgeqrf( matrix_layout,\n A_io->info.M,\n A_io->info.N,\n A_io->val,\n A_io->info.lda,\n tau);CPLM_CHKERR(ierr);\n\n if(H_io->val != NULL)//[Q] why test on val and not on H alone?\n {\n ierr = CPLM_MatDenseTriangularFillBlock( A_io,\n H_io,\n index_i,\n index_j,\n A_io->info.N);CPLM_CHKERR(ierr);\n }\n\n ierr = LAPACKE_dorgqr( matrix_layout,\n A_io->info.M,\n A_io->info.N,\n A_io->info.N,\n A_io->val,\n A_io->info.lda,\n tau);CPLM_CHKERR(ierr);\n free(tau);\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n}\n\n\nint CPLM_MatDenseKernelLowerTriangularLeftSolve(CPLM_Mat_Dense_t* L, CPLM_Mat_Dense_t* B)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n int ierr = 0;\n int matrix_layout = 0;\n int m = 0;\n int nrhs = 0;\n char uplo = 'L'; // L is lower triangular\n char trans = 'N'; // No transpose, no conjugacy\n char diag = 'N'; // No unitary\n\n CPLM_ASSERT(L != NULL);\n CPLM_ASSERT(L->val != NULL);\n CPLM_ASSERT(B != NULL);\n CPLM_ASSERT(B->val != NULL);\n\n matrix_layout = (L->info.stor_type == ROW_MAJOR) ? LAPACK_ROW_MAJOR\n : LAPACK_COL_MAJOR;\n m = B->info.m;\n nrhs = B->info.n;\n\n ierr = LAPACKE_dtrtrs(matrix_layout,\n uplo,\n trans,\n diag,\n m,\n nrhs,\n L->val,\n L->info.lda,\n B->val,\n B->info.lda);CPLM_CHKERR(ierr);\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n}\n\n\n\n\n\nint CPLM_MatDenseKernelUpperTriangularLeftSolve(CPLM_Mat_Dense_t* R, CPLM_Mat_Dense_t* B)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n int ierr = 0;\n int matrix_layout = -1;\n int m = 0;\n int nrhs = 0;\n char uplo = 'U'; // R is upper triangular\n char trans = 'N'; // No transpose, no conjugacy\n char diag = 'N'; // No unitary\n\n CPLM_ASSERT(R != NULL);\n CPLM_ASSERT(R->val != NULL);\n CPLM_ASSERT(B != NULL);\n CPLM_ASSERT(B->val != NULL);\n\n matrix_layout = (R->info.stor_type == ROW_MAJOR) ? LAPACK_ROW_MAJOR\n : LAPACK_COL_MAJOR;\n m = B->info.m;\n nrhs = B->info.n;\n\n ierr = LAPACKE_dtrtrs(matrix_layout,\n uplo,\n trans,\n diag,\n m,\n nrhs,\n R->val,\n R->info.lda,\n B->val,\n B->info.lda);CPLM_CHKERR(ierr);\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n}\n\n\n\n\n\n\n\n\n\n\n\n//#ifdef MKLACTIVATE\n\n//B is triangular\nint CPLM_MatDenseDtrmm(CPLM_Mat_Dense_t *A_in ,\n CPLM_Mat_Dense_t *B_io ,\n char side ,\n char uplo ,\n char trans ,\n char diag)\n{\nCPLM_PUSH\n int ierr = 0;\n CBLAS_LAYOUT matrix_layout = -1;\n CBLAS_DIAG blasDiag = CblasNonUnit;\n CBLAS_SIDE blasSide = CblasLeft;\n CBLAS_UPLO blasUPLO = CblasUpper;\n CBLAS_TRANSPOSE blasTrans = CblasTrans;\n\n CPLM_ASSERT(A_in->val != NULL);\n CPLM_ASSERT(B_io->val != NULL);\n\n blasDiag = (diag == 'U') ? CblasUnit : CblasNonUnit;\n blasSide = (side == 'R') ? CblasRight : CblasLeft;\n blasUPLO = (uplo == 'L') ? CblasLower : CblasUpper;\n blasTrans = (trans == 'T') ? CblasTrans : CblasNoTrans;\n\n matrix_layout = (A_in->info.stor_type == ROW_MAJOR) ? CblasRowMajor\n : CblasColMajor;\n\n cblas_dtrmm(matrix_layout,\n blasSide,\n blasUPLO,\n blasTrans,\n blasDiag,\n A_in->info.m,\n A_in->info.n,\n 1.0,\n A_in->val,\n A_in->info.lda,\n B_io->val,\n B_io->info.lda);\nCPLM_POP\n return ierr;\n}\n//#else\n// #ifdef LAPACKEACTIVATE\n// int CPLM_MatDenseDtrmm(CPLM_Mat_Dense_t *A_in ,\n// CPLM_Mat_Dense_t *B_io ,\n// char side ,\n// char uplo ,\n// char trans ,\n// char diag)\n// {\n// CPLM_PUSH\n// int ierr = 0;\n//\n// CPLM_ASSERT(A_in->val != NULL);\n// CPLM_ASSERT(B_io->val != NULL);\n//\n// if(A_in->info.stor_type == ROW_MAJOR)\n// {\n// CPLM_Abort(\"Do not call trmm with row major\");\n// }\n//\n// dtrmm(\n// side,\n// uplo,\n// trans,\n// diag,\n// A_in->info.m,\n// A_in->info.n,\n// 1.0,\n// A_in->val,\n// A_in->info.lda,\n// B_io->val,\n// B_io->info.lda);\n// CPLM_POP\n// return ierr;\n// }\n// #endif\n//#endif\n\n\n\n\n// C=alpha A^{transa} * B^{transb} + beta C\nint CPLM_MatDenseKernelMatMult(CPLM_Mat_Dense_t* A,\n char ptransa,\n CPLM_Mat_Dense_t* B,\n char ptransb,\n CPLM_Mat_Dense_t* C,\n double alpha,\n double beta)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n int ierr = 0;\n CBLAS_TRANSPOSE transa;\n CBLAS_TRANSPOSE transb;\n // Allocate memory if needed\n if (C->val == NULL)\n {\n int Crow, Ccol, CrowGlob, CcolGlob;\n CrowGlob = (ptransa == 'N') ? A->info.M : A->info.N;\n Crow = (ptransa == 'N') ? A->info.m : A->info.n;\n CcolGlob = (ptransb == 'N') ? B->info.N : B->info.M;\n Ccol = (ptransb == 'N') ? B->info.n : B->info.m;\n ierr = CPLM_MatDenseSetInfo(C,\n CrowGlob,\n CcolGlob,\n Crow,\n Ccol,\n A->info.stor_type); // We use A storage type but this\n // is arbitrary\n CPLM_CHKERR(ierr);\n ierr = CPLM_MatDenseMalloc(C);\n CPLM_CHKERR(ierr);\n }\n\n transa = (ptransa == 'N') ? CblasNoTrans : CblasTrans;\n transb = (ptransb == 'N') ? CblasNoTrans : CblasTrans;\n\n // BLAS parameters\n CBLAS_LAYOUT layout = (A->info.stor_type == ROW_MAJOR) ? CblasRowMajor\n : CblasColMajor;\n int nbColOpA = (transa == CblasNoTrans) ? A->info.n : A->info.m;\n\n cblas_dgemm (layout,\n transa,\n transb,\n C->info.m,\n C->info.n,\n nbColOpA,\n alpha,\n A->val,\n A->info.lda,\n B->val,\n B->info.lda,\n beta,\n C->val,\n C->info.lda);CPLM_CHKERR(ierr);\n\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n\n}\n\n\n\n\n\nint CPLM_MatDenseKernelUpperTriangularRightSolve(CPLM_Mat_Dense_t* R, CPLM_Mat_Dense_t* B)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n int ierr = 0;\n CBLAS_LAYOUT matrix_layout = -1;\n#ifdef MKLACTIVATE\n MKL_INT m = 0;\n MKL_INT nrhs = 0;\n#elif defined(LAPACKEACTIVATE)\n int m = 0;\n int nrhs = 0;\n#endif\n double alpha = 1e0;\n\n CPLM_ASSERT(R != NULL);\n CPLM_ASSERT(R->val != NULL);\n CPLM_ASSERT(B != NULL);\n CPLM_ASSERT(B->val != NULL);\n\n matrix_layout = (R->info.stor_type == ROW_MAJOR) ? CblasRowMajor\n : CblasColMajor;\n m = B->info.m;\n nrhs = B->info.n;\n\n cblas_dtrsm(matrix_layout,\n CblasRight,\n CblasUpper,\n CblasNoTrans,\n CblasNonUnit,\n m,\n nrhs,\n alpha,\n R->val,\n R->info.lda,\n B->val,\n B->info.lda);\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n}\n\n\n\n\n\n// y = beta*y + alpha*A*x\nint CPLM_MatDenseKernelMatVec(CPLM_Mat_Dense_t* A_in,\n double* x_in,\n double* y_io,\n double alpha,\n double beta)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n int ierr = 0;\n CBLAS_LAYOUT layout = -1;\n\n CPLM_ASSERT(A_in != NULL);\n CPLM_ASSERT(x_in != NULL);\n CPLM_ASSERT(y_io != NULL);\n CPLM_ASSERT(A_in->val != NULL);\n\n /* if (*y_io == NULL) */\n /* { */\n /* y_io = malloc(A_in->info.m*sizeof(double)); */\n /* } */\n\n // BLAS parameters\n layout = (A_in->info.stor_type == ROW_MAJOR) ? CblasRowMajor : CblasColMajor;\n\n cblas_dgemv(layout,\n CblasNoTrans,\n A_in->info.m,\n A_in->info.n,\n alpha,\n A_in->val,\n A_in->info.lda,\n x_in,\n 1, // increment for the elements of x\n beta,\n y_io,\n 1); // increment of the elements of y\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n}\n\n\n\n\n\nint CPLM_MatDenseKernelSumColumns(CPLM_Mat_Dense_t* A_in, double* sumCol)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n int ierr = 0;\n CPLM_ASSERT(A_in->val != NULL);\n CPLM_ASSERT(sumCol != NULL);\n\n double* ones = (double*) malloc(A_in->info.n*sizeof(double));\n for (int i = 0; i < A_in->info.n; ++i)\n ones[i] = 1.E0;\n\n ierr = CPLM_MatDenseKernelMatVec(A_in, ones, sumCol, 1.0, 0.0);CPLM_CHKERR(ierr);\n\n if (ones != NULL) free(ones);\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n}\n\n\n\n\n\n#ifdef MKLACTIVATE\n// C = A + B using mkl\nint CPLM_MatDenseKernelMatAdd(CPLM_Mat_Dense_t* A_in,\n CPLM_Mat_Dense_t* B_in,\n CPLM_Mat_Dense_t* C_out,\n double alpha,\n double beta)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n\n int ierr = 0;\n char ordering = 0;\n char transa = 0;\n char transb = 0;\n\n if(!CPLM_MatDenseIsSameLocalInfo(A_in,B_in))\n {\n CPLM_MatDensePrintfInfo(\"A info\",A_in);\n CPLM_MatDensePrintfInfo(\"B info\",B_in);\n CPLM_Abort(\"A and B do not have the same structure\");\n }\n\n // Allocate memory if needed\n if(C_out->val == NULL)\n {\n ierr = CPLM_MatDenseInit(C_out, A_in->info);CPLM_CHKERR(ierr);\n ierr = CPLM_MatDenseMalloc(C_out);CPLM_CHKERR(ierr);\n }\n\n // BLAS parameters\n ordering = (A_in->info.stor_type == ROW_MAJOR) ? 'R' : 'C';\n transa = 'N';\n transb = 'N';\n\n mkl_domatadd (ordering,\n transa,\n transb,\n A_in->info.m,\n A_in->info.n,\n alpha,\n A_in->val,\n A_in->info.lda,\n beta,\n B_in->val,\n B_in->info.lda,\n C_out->val,\n C_out->info.lda);\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n}\n\n\n\n\n\nint CPLM_MatCSRKernelMatDenseMult(CPLM_Mat_CSR_t *A_in,\n CPLM_Mat_Dense_t *B_in,\n CPLM_Mat_Dense_t *C_io,\n double alpha,\n double beta)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\nCPLM_OPEN_TIMER\n int ierr = 0;\n char matdescra[6];\n char trans = 'N';\n\n CPLM_ASSERT(A_in != NULL);\n CPLM_ASSERT(B_in != NULL);\n CPLM_ASSERT(C_io != NULL);\n CPLM_ASSERT(A_in->val != NULL);\n CPLM_ASSERT(B_in->val != NULL);\n\n matdescra[0] = 'G';\n matdescra[1] = 'L';//ignored if G\n matdescra[2] = 'N';//ignored if G\n matdescra[3] = 'C';\n\n if(C_io->val == NULL)\n {\n ierr = CPLM_MatDenseSetInfo(C_io,\n A_in->info.m,\n B_in->info.n,\n A_in->info.m,\n B_in->info.n,\n B_in->info.stor_type);CPLM_CHKERR(ierr);\n ierr = CPLM_MatDenseMalloc(C_io);CPLM_CHKERR(ierr);\n }\n\n#ifdef DEBUG\n CPLM_MatCSRPrintf2D(\"M1\",A_in);\n CPLM_MatDensePrintf2D(\"* M2\",B_in);\n#endif\nCPLM_TIC(step1, \"ConvertTo1BasedIndexing\")\n // If COL_MAJOR we need to use 1-base indexes (don't ask why...)\n if (B_in->info.stor_type == COL_MAJOR)\n {\n matdescra[3] = 'F';\n CPLM_MatCSRConvertTo1BasedIndexing(A_in);\n }\nCPLM_TAC(step1)\nCPLM_TIC(step2, \"Call SpBLAS\")\n mkl_dcsrmm(&trans,\n &A_in->info.m,\n &B_in->info.n,\n &A_in->info.n,\n &alpha,\n matdescra,\n A_in->val,\n A_in->colInd,\n A_in->rowPtr,\n &(A_in->rowPtr[1]),\n B_in->val,\n &(B_in->info.lda),\n &beta,\n C_io->val,\n &C_io->info.lda);\nCPLM_TAC(step2)\n // Back to 0-base indexes :)\nCPLM_TIC(step3, \"ConvertTo0BasedIndexing\")\n if (B_in->info.stor_type == COL_MAJOR)\n {\n CPLM_MatCSRConvertTo0BasedIndexing(A_in);\n }\nCPLM_TAC(step3)\n\n#ifdef DEBUG\n CPLM_MatDensePrintf2D(\"= \",C_io);\n#endif\n\nCPLM_CLOSE_TIMER\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n}\n\n\n\n\nint CPLM_MatCSRKernelGenMatDenseMult(double *val_in,\n int *colInd_in,\n int *rowPtrB_in,\n int *rowPtrE_in,\n int nrowA_in,\n int ncolA_in,\n CPLM_Mat_Dense_t *B_in,\n CPLM_Mat_Dense_t *C_io,\n double alpha,\n double beta)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\nCPLM_OPEN_TIMER\n int ierr = 0;\n char matdescra[6];\n\n matdescra[0] = 'G';\n matdescra[1] = 'L';//ignored if G\n matdescra[2] = 'N';//ignored if G\n char trans = 'N';\n\n CPLM_ASSERT(C_io->val != NULL);\n\n if (B_in->info.stor_type == COL_MAJOR)\n matdescra[3] = 'F';\n else\n matdescra[3] = 'C';\n\nCPLM_TIC(step1, \"Call SpBLAS\")\n mkl_dcsrmm(&trans,\n &nrowA_in,\n &B_in->info.n,\n &ncolA_in,\n &alpha,\n matdescra,\n val_in,\n colInd_in,\n rowPtrB_in,\n rowPtrE_in,\n B_in->val,\n &B_in->info.lda,\n &beta,\n C_io->val,\n &C_io->info.lda);\nCPLM_TAC(step1)\n\nCPLM_CLOSE_TIMER\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n}\n\n\n\n\n\nvoid CPLM_MatCSRPARDISOSetParameters(MKL_INT* iparam_io)\n{\nCPLM_PUSH\n CPLM_ASSERT(iparam_io != NULL);\n\n memset(iparam_io,0,64*sizeof(MKL_INT));\n\n iparam_io[0] = 1; // Non standard solver\n iparam_io[1] = 2; // Metis permutation to reduce fill-in\n iparam_io[4] = 0; // Return Metis permutation\n iparam_io[9] = 13; // Pivot perturbation\n iparam_io[24] = 0; // Sequential forward and backward solve\n iparam_io[26] = 0; // Check A\n iparam_io[34] = 1; // C-style array indexing (starts from 0)\n // iparam_io[17] = -1;\n // iparam_io[18] = -1;\nCPLM_POP\n}\n\n\n\n\n\nint CPLM_MatCSRPARDISOFree(CPLM_Mat_CSR_t* A_in,\n _MKL_DSS_HANDLE_t pardisoHandle_io,\n MKL_INT* iparam_in,\n MKL_INT mtype_in)\n{\nCPLM_PUSH\n MKL_INT maxfct = 1;\n MKL_INT mnum = 1;\n MKL_INT phase = -1;\n MKL_INT n = A_in->info.m;\n MKL_INT nrhs = 0;\n MKL_INT msglvl = 0;\n MKL_INT error = 0;\n MKL_INT iDummy = -1;\n double dDummy = -1e0;\n\n pardiso(pardisoHandle_io,\n &maxfct,\n &mnum,\n &mtype_in,\n &phase,\n &n,\n &dDummy,\n A_in->rowPtr,\n A_in->colInd,\n &iDummy,\n &nrhs,\n iparam_in,\n &msglvl,\n &dDummy, // b: not needed here\n &dDummy, // x: not needed here\n &error);\n\nCPLM_POP\n return error;\n}\n\n\n\n\n\nint CPLM_MatCSRPARDISOFactorization( CPLM_Mat_CSR_t* A_in,\n _MKL_DSS_HANDLE_t pardisoHandle_out,\n MKL_INT* iparam_in,\n MKL_INT mtype_in,\n MKL_INT* perm_out)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n MKL_INT maxfct = 1;\n MKL_INT mnum = 1;\n MKL_INT phase = 12;\n MKL_INT n = A_in->info.m;\n MKL_INT nrhs = 0;\n MKL_INT msglvl = 0;\n MKL_INT error = 0;\n double dDummy = -1e0;\n\n CPLM_ASSERT(A_in != NULL);\n CPLM_ASSERT(A_in->val != NULL);\n CPLM_ASSERT(pardisoHandle_out != NULL);\n CPLM_ASSERT(iparam_in != NULL);\n // CPLM_ASSERT(perm_out != NULL);\n\n pardiso(pardisoHandle_out,\n &maxfct,\n &mnum,\n &mtype_in,\n &phase,\n &n,\n A_in->val,\n A_in->rowPtr,\n A_in->colInd,\n perm_out, // the permutation returned by PARDISO\n &nrhs,\n iparam_in,\n &msglvl,\n &dDummy, // b: not needed here\n &dDummy, // x: not needed here\n &error);\n\nCPLM_END_TIME\nCPLM_POP\n return error;\n}\n\n\n\n\n\nint CPLM_MatCSRPARDISOGeneralSolve(CPLM_Mat_CSR_t* A_in,\n CPLM_Mat_Dense_t* B_in,\n CPLM_Mat_Dense_t* X_out,\n MKL_INT phase,\n _MKL_DSS_HANDLE_t pardisoHandle_in,\n MKL_INT* iparam_in,\n MKL_INT mtype_in,\n MKL_INT* perm_in)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n\n int ierr = 0;\n MKL_INT maxfct = 1;\n MKL_INT mnum = 1;\n MKL_INT n = 0;\n MKL_INT nrhs = 0;\n MKL_INT msglvl = 0;\n MKL_INT error = 0;\n\n CPLM_ASSERT(A_in != NULL);\n CPLM_ASSERT(B_in != NULL);\n CPLM_ASSERT(X_out != NULL);\n CPLM_ASSERT(A_in->val != NULL);\n CPLM_ASSERT(B_in->val != NULL);\n CPLM_ASSERT(pardisoHandle_in != NULL);\n CPLM_ASSERT(iparam_in != NULL);\n // CPLM_ASSERT(perm_in != NULL);\n\n if (X_out->val == NULL)\n {\n X_out->info = B_in->info;\n ierr = CPLM_MatDenseMalloc(X_out);CPLM_CHKERR(ierr);\n }\n else if (!CPLM_MatDenseIsSameLocalInfo(X_out,B_in))\n {\n X_out->info = B_in->info;\n ierr = CPLM_MatDenseRealloc(X_out);CPLM_CHKERR(ierr);\n }\n\n n = (MKL_INT) A_in->info.m;\n nrhs = (MKL_INT) B_in->info.n;\n\n pardiso(pardisoHandle_in,\n &maxfct,\n &mnum,\n &mtype_in,\n &phase,\n &n,\n A_in->val,\n A_in->rowPtr,\n A_in->colInd,\n perm_in,\n &nrhs,\n iparam_in,\n &msglvl,\n B_in->val,\n X_out->val,\n &error);\n\nCPLM_END_TIME\nCPLM_POP\n return error || ierr;\n}\n\n\n\n\n\nint CPLM_MatCSRPARDISOSolve( CPLM_Mat_CSR_t* A_in,\n CPLM_Mat_Dense_t* B_in,\n CPLM_Mat_Dense_t* X_out,\n _MKL_DSS_HANDLE_t pardisoHandle_in,\n MKL_INT* iparam_in,\n MKL_INT mtype_in,\n MKL_INT* perm_in)\n{\nCPLM_PUSH\n MKL_INT phase = 33;\n int ierr = CPLM_MatCSRPARDISOGeneralSolve( A_in,\n B_in,\n X_out,\n phase,\n pardisoHandle_in,\n iparam_in,\n mtype_in,\n perm_in);\nCPLM_POP\n return ierr;\n}\n\n\n\n\n\nint CPLM_MatCSRPARDISOSolveForward(CPLM_Mat_CSR_t* A_in,\n CPLM_Mat_Dense_t* B_in,\n CPLM_Mat_Dense_t* X_out,\n _MKL_DSS_HANDLE_t pardisoHandle_in,\n MKL_INT* iparam_in,\n MKL_INT mtype_in,\n MKL_INT* perm_in)\n{\nCPLM_PUSH\n MKL_INT phase = 331;\n int ierr = CPLM_MatCSRPARDISOGeneralSolve( A_in,\n B_in,\n X_out,\n phase,\n pardisoHandle_in,\n iparam_in,\n mtype_in,\n perm_in);\n if (ierr != 0)\n {\n CPLM_Abort(\"PARDISO Solve forward\");\n }\nCPLM_POP\n return ierr;\n}\n\n\n\n\n\nint CPLM_MatCSRPARDISOSolveBackward( CPLM_Mat_CSR_t* A_in,\n CPLM_Mat_Dense_t* B_in,\n CPLM_Mat_Dense_t* X_out,\n _MKL_DSS_HANDLE_t pardisoHandle_in,\n MKL_INT* iparam_in,\n MKL_INT mtype_in,\n MKL_INT* perm_in)\n{\nCPLM_PUSH\n MKL_INT phase = 333;\n int ierr = CPLM_MatCSRPARDISOGeneralSolve( A_in,\n B_in,\n X_out,\n phase,\n pardisoHandle_in,\n iparam_in,\n mtype_in,\n perm_in);\n if (ierr != 0)\n {\n CPLM_Abort(\"PARDISO Solve backward\");\n }\nCPLM_POP\n return ierr;\n}\n#endif\n\n\n\n\n\nint CPLM_MatDenseNorm(CPLM_Mat_Dense_t *A_in, const char type, double *norm)\n{\n CPLM_PUSH\n int ierr = 0;\n int major = (A_in->info.stor_type == COL_MAJOR) ? LAPACK_COL_MAJOR\n : LAPACK_ROW_MAJOR;\n\n *norm = LAPACKE_dlange(major,\n type,\n A_in->info.m,\n A_in->info.n,\n A_in->val,\n A_in->info.lda);\n\n CPLM_POP\n return ierr;\n}\n\nint CPLM_MatDenseMatDotProd(CPLM_Mat_Dense_t* A, CPLM_Mat_Dense_t* B, CPLM_Mat_Dense_t* C, MPI_Comm comm)\n{\nCPLM_PUSH\nCPLM_BEGIN_TIME\n int ierr = 0;\n // Do local dot product\n ierr = CPLM_MatDenseKernelMatDotProd(A, B, C);\n\n // Sum local dot products in place (no mem alloc needed)\n ierr = MPI_Allreduce(MPI_IN_PLACE, C->val, C->info.nval, MPI_DOUBLE, MPI_SUM, comm);CPLM_checkMPIERR(ierr,\"MatDenseMatDotProd::MPI_Allreduce\");\nCPLM_END_TIME\nCPLM_POP\n return ierr;\n}\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n/* HANDLER */\n/******************************************************************************/\n/*\nvoid CPLM_MatDenseSVDHandler(int ierr)\n{\n\n if (ierr > 0)\n {\n CPLM_eprintf(\"the eigensolver did not converge!\");\n }\n else if (ierr < 0)\n {\n CPLM_eprintf(\"parameter %d has an illegal value!\", -ierr + 1);\n }\n\n}\n*/\n", "meta": {"hexsha": "3269027a064936109e98df63d62cfd7f0b20b209", "size": 25266, "ext": "c", "lang": "C", "max_stars_repo_path": "utils/cplm_light/cplm_kernels.c", "max_stars_repo_name": "W-Wuxian/preAlps", "max_stars_repo_head_hexsha": "9718968d3474be821ceb676ceff8e1dee1dae2f0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-03-28T12:30:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T17:42:29.000Z", "max_issues_repo_path": "utils/cplm_light/cplm_kernels.c", "max_issues_repo_name": "W-Wuxian/preAlps", "max_issues_repo_head_hexsha": "9718968d3474be821ceb676ceff8e1dee1dae2f0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-14T16:11:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:11:37.000Z", "max_forks_repo_path": "utils/cplm_light/cplm_kernels.c", "max_forks_repo_name": "W-Wuxian/preAlps", "max_forks_repo_head_hexsha": "9718968d3474be821ceb676ceff8e1dee1dae2f0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-11-17T22:41:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T11:22:04.000Z", "avg_line_length": 25.2912912913, "max_line_length": 145, "alphanum_fraction": 0.4774004591, "num_tokens": 7055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4092859536173254}} {"text": "#ifndef _NAMASTER_H_\n#define _NAMASTER_H_\n\n#ifndef NO_DOXY\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#endif //NO_DOXY\n\n#define NMT_MAX(a,b) (((a)>(b)) ? (a) : (b)) // maximum\n#define NMT_MIN(a,b) (((a)<(b)) ? (a) : (b)) // minimum\n\n#ifdef _SPREC\ntypedef float flouble;\ntypedef float complex fcomplex;\n#else //_SPREC\ntypedef double flouble;\ntypedef double complex fcomplex;\n#endif //_SPREC\n\n/*! \\mainpage NaMaster C API\n *\n * Welcome to the documentation of NaMaster's C API. Navigate through the tabs above to learn more\n * about the different functionality implemented in the code.\n *\n * \\section general_notes General notes\n * - Most users will prefer to use the python wrapper \"pymaster\", which mostly calls the\n C-based functions.\n * - NaMaster uses a \"row-major\" order to define the ordering of power spectra into vectors.\n E.g. the cross-correlation of two spin-2 fields 'a' and 'b' would give rise to 4 power\n spectra: Ea-Eb, Ea-Bb, Ba-Eb and Ba-Bb. These are stored into 1-dimensional arrays using\n exactly that order. For the case of a spin-0 - spin-2 correlation, the ordering is\n [T-E, T-B], where T is the spin-0 field and (E,B) are the harmonic components of the\n spin-2 field.\n * - The abbreviation MCM will often be used instead of \"mode-coupling matrix\".\n * - SHT will sometimes be used for \"Spherical Harmonic Transform\". In the context of flat-sky\n fields, this should be understood as a standard Fast Fourier Transform (FFT) (with\n appropriate trigonometric factors if dealing with spin-2 fields).\n * - FWHM will sometimes be used for \"Full-width at half-max\".\n *\n * \\section more_info More info\n *\n * Please refer to the README and LICENSE files for further information on installation,\n * credits and licensing. Do not hesitate to contact the authors (preferably via github\n * issues on https://github.com/LSSTDESC/NaMaster) if you encounter any problems using\n * the code.\n */\n\n/**\n * @brief Flat-sky bandpowers.\n *\n * This structure defines bandpowers for flat-sky power spectra.\n * These are currently defined only by band edges (assumed\n * flat weights within band).\n */\ntypedef struct {\n int n_bands; //!< Number of bandpowers stored\n flouble *ell_0_list; //!< Lower edge of each bandpower\n flouble *ell_f_list; //!< Upper edge of each bandpower\n} nmt_binning_scheme_flat;\n\n/**\n * @brief nmt_binning_scheme_flat constructor for constant bandpowers\n *\n * nmt_binning_scheme_flat constructor for bandpowers with\n * constant width \\p nlb, from ell = 2 to ell = \\p lmax.\n * @param nlb Constant band width\n * @param lmax Maximum multipole\n * @return Allocated binning structure.\n */\nnmt_binning_scheme_flat *nmt_bins_flat_constant(int nlb,flouble lmax);\n\n/**\n * @brief nmt_binning_scheme_flat generic constructor.\n *\n * @param nell Number of bandpowers\n * @param l0 Lower edge of all bandpowers (should be allocated to nell elements).\n * @param lf Lower edge of all bandpowers (should be allocated to nell elements).\n * @return Allocated binning structure.\n */\nnmt_binning_scheme_flat *nmt_bins_flat_create(int nell,flouble *l0,flouble *lf);\n\n/**\n * @brief nmt_binning_scheme_flat destructor\n */\nvoid nmt_bins_flat_free(nmt_binning_scheme_flat *bin);\n\n/**\n * @brief Returns average of input power spectrum into bandpowers.\n *\n * @param bin nmt_binning_scheme_flat structure defining the bandpowers.\n * @param nl Number of elements in the input power spectra.\n * @param larr Array containing the \\p nl multipoles at which the input power\n * spectrum is defined.\n * @param cls_in Array of \\p ncls input power spectra.\n * @param cls_out Array of \\p ncls averaged output power spectra.\n * Should be allocated to the number of bandpowers defined \\p bin.\n * @param ncls Number of input/output power spectra.\n */\nvoid nmt_bin_cls_flat(nmt_binning_scheme_flat *bin,int nl,flouble *larr,flouble **cls_in,\n\t\t flouble **cls_out,int ncls);\n\n/**\n * @brief Returns binned power spectra interpolated into an given set of multipoles.\n *\n * Nearest-neighbours interpolation is used.\n * @param bin nmt_binning_scheme_flat structure defining the bandpowers.\n * @param cls_in Array of \\p ncls input power spectra. Must have the same number of\n * elements as bandpowers defined by \\p bin.\n * @param nl Number of elements in the output power spectra.\n * @param larr Array containing the \\p nl multipoles at which the output power\n * spectrum are requested.\n * @param cls_out Array of \\p ncls interpolated output power spectra.\n * @param ncls Number of input/output power spectra.\n */\nvoid nmt_unbin_cls_flat(nmt_binning_scheme_flat *bin,flouble **cls_in,\n\t\t\tint nl,flouble *larr,flouble **cls_out,int ncls);\n\n/**\n * @brief Returns effective multipoles.\n *\n * Returns the mid point of each bandpower defined in \\p bin.\n * @param bin nmt_binning_scheme_flat structure defining the bandpowers.\n * @param larr Output array containing mid-points of the bandpowers.\n * Should be preallocated to the correct number of bandpowers.\n */\nvoid nmt_ell_eff_flat(nmt_binning_scheme_flat *bin,flouble *larr);\n\n/**\n * @brief Fast bin-searching routine for flat-sky bandpowers\n *\n * Returns the bandpower index in which a given ell falls. The functions is designed\n * to be fast if a good guess for the bandpower index is supplied. A typical use would\n * be to iterate over ell values and pass, as a guess index, the index found in the\n * previous iteration.\n * @param bin nmt_binning_scheme_flat structure defining the bandpowers.\n * @param l Multipole for which you want the bandpower index.\n * @param il Guessed bandpower index.\n * @return Bandpower index.\n */\nint nmt_bins_flat_search_fast(nmt_binning_scheme_flat *bin,flouble l,int il);\n\n/**\n * @brief Full-sky bandpowers.\n *\n * This structure defines bandpowers for full-sky power spectra.\n * Although a given multipole ell can only contribute to one bandpower,\n * the distribution of ells per bandpower and their relative weights\n * is left completely free.\n */\ntypedef struct {\n int n_bands; //!< Number of bandpowers.\n int *nell_list; //!< Number of multipoles belonging to each bandpower.\n int **ell_list; //!< List of multipoles in each bandpowers.\n flouble **w_list; //!< List of weights associated to each multipole in \\p ell_list.\n flouble **f_ell; //!< Multiplicative ell factor\n int ell_max; //!< Maximum multipole included.\n} nmt_binning_scheme;\n\n/**\n * @brief nmt_binning_scheme constructor for constant bandpowers.\n *\n * nmt_binning_scheme constructor for bandpowers with constant\n * width \\p nlb, from ell = 2 to ell = \\p lmax.\n * @param nlb Constant band width\n * @param lmax Maximum multipole\n * @param is_l2 If not zero, will assume l*(l+1)/2pi weighting\n * @return Allocated binning structure.\n */\nnmt_binning_scheme *nmt_bins_constant(int nlb,int lmax,int is_l2);\n\n/**\n * @brief nmt_binning_scheme generic constructor.\n *\n * @param nell Number of elements in all subsequent arrays.\n * @param bpws Array of bandpower indices.\n * @param ells Array of multipole values. This function collects all multipoles\n * into their associated bandpowers.\n * @param weights Array of weights associated to each multipole. Weights are\n * normalized to 1 within each bandpower.\n * @param f_ell Array of ell-dependent prefactor (e.g. l*(l+1)/2pi is a typical choice).\n * Pass NULL if you don't want any prefactor.\n * normalized to 1 within each bandpower.\n * @param lmax Maximum multipole to consider.\n * @return Allocated binning structure.\n */\nnmt_binning_scheme *nmt_bins_create(int nell,int *bpws,int *ells,flouble *weights,\n\t\t\t\t flouble *f_ell,int lmax);\n\n/**\n * @brief nmt_binning_scheme constructor from file\n *\n * Builds a nmt_binning_scheme structure from an ASCII file.\n * @param fname Path to file containing information to build bandpowers.\n * The file should contain three columns, corresponding to:\n * bandpower index, multipole and weight (in this order).\n * See definition of nmt_bins_create().\n * @param lmax Maximum multipole to be considered.\n * @return Allocated binning structure.\n */\nnmt_binning_scheme *nmt_bins_read(char *fname,int lmax);\n\n/**\n * @brief nmt_binning_scheme destructor\n */\nvoid nmt_bins_free(nmt_binning_scheme *bin);\n\n/**\n * @brief Returns average of input power spectrum into bandpowers.\n *\n * @param bin nmt_binning_scheme structure defining the bandpowers.\n * @param cls_in Array of \\p ncls input power spectra. They should be\n * defined in all ells that go into any bandpower defined by \\p bin.\n * @param cls_out Array of \\p ncls averaged output power spectra.\n * Should be allocated to the number of bandpowers defined \\p bin.\n * @param ncls Number of input/output power spectra.\n */\nvoid nmt_bin_cls(nmt_binning_scheme *bin,flouble **cls_in,flouble **cls_out,int ncls);\n\n/**\n * @brief Returns binned power spectra interpolated into output multipoles.\n *\n * Top-hat interpolation is used (i.e. a given ell is associated with the binned power\n * spectrum value at the bandpower that ell corresponds to).\n * @param bin nmt_binning_scheme structure defining the bandpowers.\n * @param cls_in Array of \\p ncls input power spectra. Must have the same number of\n * elements as bandpowers defined by \\p bin.\n * @param cls_out Array of \\p ncls interpolated output power spectra.\n * @param ncls Number of input/output power spectra.\n */\nvoid nmt_unbin_cls(nmt_binning_scheme *bin,flouble **cls_in,flouble **cls_out,int ncls);\n\n/**\n * @brief Returns effective multipoles.\n *\n * Return the weighted average multipole values within each bandpower defined by \\p bin.\n * @param bin nmt_binning_scheme structure defining the bandpowers.\n * @param larr Output array containing the effective multipole in each bandpower.\n * Should be preallocated to the correct number of bandpowers.\n */\nvoid nmt_ell_eff(nmt_binning_scheme *bin,flouble *larr);\n\n/**\n * @brief Flat-sky Fourier-space function\n *\n * Unlike multipoles in harmonic space, in the case of full-sky operations,\n * wavenumbers k in Fourier space for flat-sky fields are in general continuous\n * variables. This structure helps define functions of these continuous variables.\n */\ntypedef struct {\n int is_const; //!< If >0, this function is just a constant\n flouble x0; //!< Lower edge of spline interpolation\n flouble xf; //!< Upper edge of spline interpolation\n flouble y0; //!< Function will take this value for x < \\p x0\n flouble yf; //!< Function will take this value for x > \\p xf\n gsl_spline *spl; //!< GSL spline interpolator.\n} nmt_k_function;\n\n/**\n * @brief nmt_k_function creator.\n *\n * @param nk Number of elements in input arrays.\n * @param karr k-values at which the input function is sampled.\n * @param farr Function values at k = \\p karr.\n * @param y0 Constant function value below interpolation range.\n * @param yf Constant function value above interpolation range.\n * @param is_const If non-zero, will create a constant function.\n * In this case all previous arguments other than \\p y0 are ignored\n * and the function will take this value for all k.\n */\nnmt_k_function *nmt_k_function_alloc(int nk,flouble *karr,flouble *farr,\n\t\t\t\t flouble y0,flouble yf,int is_const);\n\n/**\n * @brief nmt_k_function destructor\n */\nvoid nmt_k_function_free(nmt_k_function *f);\n\n/**\n * @brief nmt_k_function evaluator.\n *\n * Returns value of function at \\p k.\n * @param f nmt_k_function to evaluate.\n * @param k Value of k for which you want f(k).\n * @param intacc GSL interpolation accelerator. If you don't want any, just pass a NULL pointer.\n */\nflouble nmt_k_function_eval(nmt_k_function *f,flouble k,gsl_interp_accel *intacc);\n\n/**\n * @brief Flat-sky information.\n *\n * This structure contains all the information defining a given rectangular flat-sky patch.\n * The structure also contains information about the optimal way of sampling the Fourier\n * version of this patch into rings of |k|.\n */\ntypedef struct {\n int nx; //!< Number of grid points in the x dimension\n int ny; //!< Number of grid points in the y dimension\n long npix; //!< Total number of pixels (given by \\p nx * \\p ny\n flouble lx; //!< Length of the x dimension (in steradians)\n flouble ly; //!< Length of the y dimension (in steradians)\n flouble pixsize; //!< Pixel area (given by \\p lx * \\p ly / ( \\p nx * \\p ny))\n int n_ell; //!< Number of |k|-values for Fourier-space sampling.\n flouble dell; //!< Width of the Fourier-space rings. This is found as min(2 π / \\p lx,2 π / \\p ly).\n flouble i_dell; //!< 1 / \\p dell\n flouble *ell_min; //!< Array of \\p n_ell values containing the lower edges of each of the |k| rings.\n // int *n_cells;\n} nmt_flatsky_info;\n\n/**\n * @brief nmt_flatsky_info constructor\n *\n * Builds nmt_flatsky_info from patch dimensions.\n * @param nx Number of grid points in the x dimension\n * @param ny Number of grid points in the y dimension\n * @param lx Length of the x dimension (in steradians)\n * @param ly Length of the y dimension (in steradians)\n * @return Allocated nmt_flatsky_info structure.\n */\nnmt_flatsky_info *nmt_flatsky_info_alloc(int nx,int ny,flouble lx,flouble ly);\n\n/**\n * @brief nmt_flatsky_info destructor.\n */\nvoid nmt_flatsky_info_free(nmt_flatsky_info *fs);\n\n/**\n * @brief Flat-sky field\n *\n * This structure contains all the information defining a spin-s flat-sky field.\n * This includes field values, masking, purification and contamination.\n */\ntypedef struct {\n nmt_flatsky_info *fs; //!< Structure defining patch geometry.\n long npix; //!< Number of pixels in all maps (also contained in \\p fs).\n int pure_e; //!< >0 if E-modes have been purified.\n int pure_b; //!< >0 if B-modes have been purified.\n flouble *mask; //!< Field's mask (an array of \\p npix values).\n fcomplex **a_mask; //!< Fourier transform of the mask. Only computed if E or B are purified.\n int spin; //!< field's spin (>=0).\n int nmaps; //!< Number of maps in the field (2 for spin-2, 1 for spin-0).\n flouble **maps; //!< Observed field values. When initialized, these maps are already multiplied by the mask, contaminant deprojected and purified if requested.\n fcomplex **alms; //!< Fourier-transfoms of the maps.\n int ntemp; //!< Number of contaminant templates\n flouble ***temp; //!< Contaminant template maps (mask-multiplied but NOT purified).\n fcomplex ***a_temp; //!< Fourier-transfomrs of template maps (mask-multiplied AND purified if requested).\n gsl_matrix *matrix_M; //!< Inverse contaminant covariance matrix (see scientific documentation or companion paper).\n nmt_k_function *beam; //!< Function defining a circularly-symmetric beam function. Power spectra will be beam-deconvolved.\n int lite; //!< lightweight field (no maps, temp, a_temp or a_mask)\n int mask_only; //!< this field only contains a mask, and beam. No alms, maps or anything else.\n} nmt_field_flat;\n\n/**\n * @brief nmt_field_flat destructor\n */\nvoid nmt_field_flat_free(nmt_field_flat *fl);\n\n/**\n * @brief nmt_field_flat constructor\n *\n * Builds an nmt_field_flat structure from input maps and patch parameters.\n * @param nx Number of grid points in the x dimension.\n * @param ny Number of grid points in the y dimension.\n * @param lx Length of the x dimension (in steradians).\n * @param ly Length of the y dimension (in steradians).\n * @param mask Field's mask (an array of \\p nx * \\p ny values).\n * @param spin Field's spin.\n * @param maps Observed field values BEFORE multiplying by the mask\n (this is irrelevant for binary masks).\n * @param ntemp Number of contaminant templates affecting this field.\n * @param temp Contaminant template maps (again, NOT multiplied by the mask).\n * @param nl_beam Number of multipole values defining this field's beam.\n * @param l_beam Multipole values at which this field's beam is defined.\n * @param beam Beam values at ell = \\p l_beam. Pass a NULL pointer if you don't\n want any beam (\\p nl_beam and \\p l_beam will be ignored).\n * @param pure_e Set to >0 if you want purified E-modes.\n * @param pure_b Set to >0 if you want purified B-modes.\n * @param tol_pinv Contaminant deprojection requires the inversion of the template\n covariance matrix. This could be ill-defined if some templates are linearly\n\t related. In this case we use a pseudo-inverse that accounts for this\n\t possibility in a consistent way. Effectively this is a singular-value\n\t decomposition. All eigenvalues that are smaller than \\p tol_pinv the largest\n\t eigenvalue will be discarded.\n * @param masked_input if not 0, input maps and templates have already been masked.\n This is not advisable if using purification.\n * @param is_lite if not 0, only the map alms and the mask will be stored. You can then\n use this field to compute the standard pseudo-C_ell with deprojection and purification,\n but you won't be able to compute the deprojection bias or examine any maps.\n * @param mask_only if not 0, this field will only store a mask and a beam. You will\n be able to use it to compute the PCL and covariance mode coupling matrices, but that's\n it (no actual power spectra, deprojection biases etc.).\n */\nnmt_field_flat *nmt_field_flat_alloc(int nx,int ny,flouble lx,flouble ly,\n\t\t\t\t flouble *mask,int spin,flouble **maps,int ntemp,flouble ***temp,\n\t\t\t\t int nl_beam,flouble *l_beam,flouble *beam,\n\t\t\t\t int pure_e,int pure_b,double tol_pinv,int masked_input,\n int is_lite,int mask_only);\n/**\n * @brief Gaussian realizations of flat-sky fields\n *\n * Generates a Gaussian realization of an arbitrary list of possibly-correlated\n * fields with different spins.\n * @param nx Number of grid points in the x dimension.\n * @param ny Number of grid points in the y dimension.\n * @param lx Length of the x dimension (in steradians).\n * @param ly Length of the y dimension (in steradians).\n * @param nfields Number of fields to generate.\n * @param spin_arr Array (size \\p nfields) containing the spins of the fields to be generated.\n * @param nl_beam Number of multipoles at which the field beams are defined.\n * @param l_beam Array of multipoles at which the field beams are defined.\n * @param beam_fields Array of beams (one per field).\n * @param nl_cell Number of multipole values at which the input power spectra are provided.\n * @param l_cell Array of multipole values at which the input power spectra are provided.\n * @param cell_fields Array of input power spectra. Shape should be [\\p n_cls][\\p nl_cell],\n where \\p n_cls is the number of power spectra needed to define all the fields.\n\t This should be \\p n_cls = n_maps * (n_maps + 1) / 2, where n_maps is the total\n\t number of maps required (1 for each spin-0 field, 2 for each spin-2 field). Power\n\t spectra must be provided only for the upper-triangular part in row-major order\n\t (e.g. if n_maps is 3, there will be 6 power spectra ordered as [1-1,1-2,1-3,2-2,2-3,3-3].\n * @param seed Seed for this particular realization.\n * @return Gaussian realization.\n */\nflouble **nmt_synfast_flat(int nx,int ny,flouble lx,flouble ly,int nfields,int *spin_arr,\n\t\t\t int nl_beam,flouble *l_beam,flouble **beam_fields,\n\t\t\t int nl_cell,flouble *l_cell,flouble **cell_fields,\n\t\t\t int seed);\n\n/**\n * @brief E- or B-mode purifies a given pair of flat-sky (Q,U) maps.\n *\n * This function is mostly used internally by NaMaster, and its standalone use is discouraged.\n * @param fl nmt_field_flat containing information about what should be purified.\n * @param mask Sky mask (should be appropriately apodized - see scientific documentation).\n * @param walm0 Fourier transform of the mask.\n * @param maps_in Maps to be purified (should NOT be mask-multiplied).\n * @param maps_out Output purified maps.\n * @param alms Fourier transform of the output purified maps.\n */\nvoid nmt_purify_flat(nmt_field_flat *fl,flouble *mask,fcomplex **walm0,\n\t\t flouble **maps_in,flouble **maps_out,fcomplex **alms);\n\n/**\n * @brief Curved-sky information.\n *\n * This structure contains all the information defining a given full-sky patch.\n * It describes either a HEALPix grid (in which case is_healpix!=0) or a CAR\n * patch (for is_healpix==0). If the latter, then the CAR pixelization must\n * conform to the Clenshaw-Curtis sampling. In this case the colatitude theta\n * must be sampled at N points going from 0 to pi (including both), separated\n * by an interval Dtheta = pi/(N-1). Not all iso-latitude rings must be stored\n * in the patch (i.e. ny!=N necessarily). See the documentation for \n * nmt_curvedsky_info_alloc for further information on the constraints that\n * some of the members of this structure must fulfill.\n */\ntypedef struct {\n int is_healpix; //!< is this HEALPix pixelization?\n long n_eq; //!< equivalent of nside, number of pixels in the equatorial ring\n int lmax_sht; //!< Maximum multipole to compute spherical harmonic transform\n int nx_short; //!< Number of grid points in the x dimension before completing the circle\n int nx; //!< Number of grid points in the phi dimension\n int ny; //!< Number of grid points in the theta dimension\n long npix; //!< Total number of pixels (given by \\p nx * \\p ny\n flouble Delta_theta; //!< pixel size in theta direction\n flouble Delta_phi; //!< pixel size in phi direction\n flouble phi0; // longitude of first pixel\n flouble theta0; // colatitude of last ring\n} nmt_curvedsky_info;\n\n/**\n * @brief Makes a copy of a nmt_curvedsky_info structure\n *\n * @param cs_in input structure to be copied.\n * @return copy of input nmt_curvedsky_info structure.\n */\nnmt_curvedsky_info *nmt_curvedsky_info_copy(nmt_curvedsky_info *cs_in);\n\n/**\n * @brief nmt_curvedsky_info creator\n *\n * If generating a Clenshaw-Curtis grid, then Dtheta and Dphi must be (close to)\n * exact divisor of pi and 2pi respectively. Likewise, theta0 must be an integer\n * multiple of Dtheta, and the number of pixels in the theta direction must be\n * such that the map actually fits on the sphere (i.e. theta0-(ny-1)*Dtheta >=0).\n * @param is_healpix is this HEALPix pixelization.\n * @param nside if is_healpix, this should be the HEALPix Nside parameter.\n * @param lmax_sht maximum multipole up to which spherical harmonic transforms will be computed.\n * @param nx0 number of pixels in the phi direction.\n * @param ny0 number of pixels in the theta direction.\n * @param Dtheta pixel size in the theta direction. In radians. Must be positive.\n * @param Dphi pixel size in the phi direction. In radians, must be positive.\n * @param theta0 colatitude of the last ring in the map. In radians.\n * @param phi0 minimum azimuth covered by the map. In radians.\n * @return nmt_curvedsky_info struct.\n */\nnmt_curvedsky_info *nmt_curvedsky_info_alloc(int is_healpix,long nside,\n\t\t\t\t\t int lmax_sht,\n\t\t\t\t\t int nx0,int ny0,flouble Dtheta,flouble Dphi,\n\t\t\t\t\t flouble phi0,flouble theta0);\n\n\n/**\n * @brief Compare two nmt_curvedsky_info structs.\n *\n * @return true (!=0) if both structs are equivalent, and false (0) if they aren't.\n */\nint nmt_diff_curvedsky_info(nmt_curvedsky_info *c1, nmt_curvedsky_info *c2);\n\n/**\n * @brief Extend CAR map to cover the full circle.\n *\n * CAR maps only cover a particular part of the sky, but the SHT routines need as\n * input maps that are complete in the azimuth direction. This routine takes in\n * a raw CAR map with its corresponding nmt_curvedsky_info and returns the \n * phi-complete map (with zeros in all pixels outside the original map).\n * If the input map is in HEALPix, this routine just returns a copy of it.\n * @param cs curved sky geometry info.\n * @param map_in input incomplete map.\n * @return phi-complete map.\n */\nflouble *nmt_extend_CAR_map(nmt_curvedsky_info *cs,flouble *map_in);\n\n/**\n * @brief Full-sky field\n *\n * This structure contains all the information defining a spin-s full-sky field.\n * This includes field values, masking, purification and contamination.\n */\ntypedef struct {\n nmt_curvedsky_info *cs; //!< pixelization parameters\n long npix; //!< Number of pixels in all maps\n long nalms; //!< Number of complex harmonic coefficients\n int lmax; //!< Maximum multipole used\n int pure_e; //!< >0 if E-modes have been purified\n int pure_b; //!< >0 if B-modes have been purified\n flouble *mask; //!< Field's mask (an array of \\p npix values).\n fcomplex **a_mask; //!< Spherical transform of the mask. Only computed if E or B are purified.\n int spin; //!< field's spin (>=0).\n int nmaps; //!< Number of maps in the field (2 for spin-2, 1 for spin-0).\n flouble **maps; //!< Observed field values. When initialized, these maps are already multiplied by the mask, contaminant-deprojected and purified if requested.\n fcomplex **alms; //!< Spherical harmonic transfoms of the maps.\n int ntemp; //!< Number of contaminant templates\n flouble ***temp; //!< Contaminant template maps (mask-multiplied but NOT purified).\n fcomplex ***a_temp; //!< Spherical harmonic transfomrs of template maps (mask-multiplied AND purified if requested).\n gsl_matrix *matrix_M; //!< Inverse contaminant covariance matrix (see scientific documentation or companion paper).\n flouble *beam; //!< Field's beam (defined on all multipoles up to \\p lmax).\n int lite; //!< lightweight field (no maps, temp, a_temp or a_mask)\n int mask_only; //!< this field only contains a mask, and beam. No alms, maps or anything else.\n} nmt_field;\n\n/**\n * @brief nmt_field destructor.\n */\nvoid nmt_field_free(nmt_field *fl);\n\n/**\n * @brief nmt_field constructor\n *\n * Builds an nmt_field structure from input maps and resolution parameters.\n * @param cs curved sky geometry info.\n * @param mask Field's mask.\n * @param spin Field's spin.\n * @param maps Observed field values BEFORE multiplying by the mask\n (this is irrelevant for binary masks).\n * @param ntemp Number of contaminant templates affecting this field.\n * @param temp Contaminant template maps (again, NOT multiplied by the mask).\n * @param beam Harmonic coefficients of the beam (defined for all multipoles up to\n * the maximum multipole sampled by the map). Pass a NULL pointer if you don't want any beam.\n * @param pure_e Set to >0 if you want purified E-modes.\n * @param pure_b Set to >0 if you want purified B-modes.\n * @param n_iter_mask_purify E/B purification requires a number of harmonic-space\n operations on an appropriately apodized mask. This parameter sets the\n number of iterations requested to compute the spherical harmonic transform\n of the field's mask. Higher values will produce more accurate results (at\n\t the cost of computational time).\n * @param tol_pinv Contaminant deprojection requires the inversion of the template\n covariance matrix. This could be ill-defined if some templates are linearly\n\t related. In this case we use a pseudo-inverse that accounts for this\n\t possibility in a consistent way. Effectively this is a singular-value\n\t decomposition. All eigenvalues that are smaller than \\p tol_pinv the largest\n\t eigenvalue will be discarded.\n * @param niter number of iterations when computing alms (for all transforms other than the mask's).\n * @param masked_input if not 0, input maps and templates have already been masked.\n This is not advisable if using purification.\n * @param is_lite if not 0, only the map alms and the mask will be stored. You can then\n use this field to compute the standard pseudo-C_ell with deprojection and purification,\n but you won't be able to compute the deprojection bias or examine any maps.\n * @param mask_only if not 0, this field will only store a mask and a beam. You will\n be able to use it to compute the PCL and covariance mode coupling matrices, but that's\n it (no actual power spectra, deprojection biases etc.).\n */\nnmt_field *nmt_field_alloc_sph(nmt_curvedsky_info *cs,flouble *mask,int spin,flouble **maps,\n\t\t\t int ntemp,flouble ***temp,flouble *beam,\n\t\t\t int pure_e,int pure_b,int n_iter_mask_purify,double tol_pinv,\n\t\t\t int niter,int masked_input,int is_lite,int mask_only);\n\n/**\n * @brief nmt_field constructor from file.\n *\n * Builds an nmt_field structure from data written in files.\n * @param is_healpix is the map stored in healpix format?\n * @param fname_mask Path to FITS file containing the field's mask (single HEALPix map).\n * @param spin Field's spin.\n * @param fname_maps Path to FITS file containing the field's observed maps\n (1(2) maps if \\p spin=0(!=0)).\n * @param fname_temp Path to FITS file containing the field's contaminant templates.\n If \\p spin > 0, the file should contain an even number\n of files. Each consecutive pair of maps will be interpreted as the Q and U\n\t components of a given contaminant. Pass \"none\" if you don't want any contaminants.\n * @param fname_beam Path to ASCII file containing the field's beam. The file should\n contain two columns: l (multipole) and b_l (beam SHT at that multipole).\n\t Pass \"none if you don't want a beam.\n * @param pure_e >0 if you want E-mode purification.\n * @param pure_b >0 if you want B-mode purification.\n * @param n_iter_mask_purify E/B purification requires a number of harmonic-space\n operations on an appropriately apodized mask. This parameter sets the\n number of iterations requested to compute the spherical harmonic transform\n of the field's mask. Higher values will produce more accurate results (at\n\t the cost of computational time).\n * @param tol_pinv Contaminant deprojection requires the inversion of the template\n covariance matrix. This could be ill-defined if some templates are linearly\n\t related. In this case we use a pseudo-inverse that accounts for this\n\t possibility in a consistent way. Effectively this is a singular-value\n\t decomposition. All eigenvalues that are smaller than \\p tol_pinv the largest\n\t eigenvalue will be discarded.\n * @param niter number of iterations when computing alms (other than the mask's).\n */\nnmt_field *nmt_field_read(int is_healpix,char *fname_mask,char *fname_maps,char *fname_temp,\n\t\t\t char *fname_beam,int spin,int pure_e,int pure_b,\n\t\t\t int n_iter_mask_purify,double tol_pinv,int niter);\n\n/**\n * @brief Gaussian realizations of full-sky fields\n *\n * Generates a Gaussian realization of an arbitrary list of possibly-correlated fields with different spins.\n * @param cs curved sky geometry info.\n * @param lmax Maximum multipole used.\n * @param nfields Number of fields to generate.\n * @param spin_arr Array (size \\p nfields) containing the spins of the fields to be generated.\n * @param beam_fields Array of beams (one per field). Must be defined at all ell <= \\p lmax.\n * @param cells Array of input power spectra (defined at all ell <= \\p lmax). Shape\n should be [\\p n_cls][\\p lmax+1], where \\p n_cls is the number of power spectra\n\t needed to define all the fields. This should be \\p n_cls = n_maps * (n_maps + 1) / 2,\n\t where n_maps is the total number of maps required (1 for each spin-0 field, 2 for\n\t each spin-2 field). Power spectra must be provided only for the upper-triangular part\n\t in row-major order (e.g. if n_maps is 3, there will be 6 power spectra ordered as\n\t [1-1,1-2,1-3,2-2,2-3,3-3].\n * @param seed Seed for this particular realization.\n * @return Gaussian realization.\n */\nflouble **nmt_synfast_sph(nmt_curvedsky_info *cs,int nfields,int *spin_arr,int lmax,\n\t\t\t flouble **cells,flouble **beam_fields,int seed);\n\n/**\n * @brief E- or B-mode purifies a given pair of full-sky (Q,U) maps.\n *\n * This function is mostly used internally by NaMaster, and its standalone use is discouraged.\n * @param fl nmt_field containing information about what should be purified.\n * @param mask Sky mask (should be appropriately apodized - see scientific documentation).\n * @param walm0 Spherical harmonic transform of the mask.\n * @param maps_in Maps to be purified (should NOT be mask-multiplied).\n * @param maps_out Output purified maps.\n * @param alms Spherical harmonic transform of the output purified maps.\n * @param niter number of iterations when computing alms.\n */\nvoid nmt_purify(nmt_field *fl,flouble *mask,fcomplex **walm0,\n\t\tflouble **maps_in,flouble **maps_out,fcomplex **alms,int niter);\n\n/**\n * @brief Apodize full-sky mask.\n *\n * Produces apodized version of a full-sky mask for a number of apodization schemes.\n * @param nside HEALPix resolution parameter.\n * @param mask_in Input mask to be apodized.\n * @param mask_out Output apodized mask.\n * @param aposize Apodization scale (in degrees).\n * @param apotype String defining the apodization procedure. Three values allowed: 'C1', 'C2' and 'Smooth'. These correspond to:\n * - \\p apotype = \"C1\". All pixels are multiplied by a factor \\f$f\\f$, given by:\n *\\f[\n * f=\\left\\{\n * \\begin{array}{cc}\n * x-\\sin(2\\pi x)/(2\\pi) & x<1\\\\\n * 1 & {\\rm otherwise}\n * \\end{array}\n * \\right.,\n * \\f]\n where \\f$x=\\sqrt{(1-\\cos\\theta)/(1-\\cos(\\theta_*))}\\f$, \\f$\\theta_*\\f$ is the\n\tapodization scale and \\f$\\theta\\f$ is the angular separation between a pixel and\n\tthe nearest masked pixel (i.e. where the mask takes a zero value).\n * - \\p apotype = \"C2\". The same as the C1 case, but the function in this case is:\n *\\f[\n * f=\\left\\{\n * \\begin{array}{cc}\n * \\frac{1}{2}\\left[1-\\cos(\\pi x)\\right] & x<1\\\\\n * 1 & {\\rm otherwise}\n * \\end{array}\n * \\right.,\n * \\f]\n * - \\p apotype = \"Smooth\". This apodization is carried out in three steps:\n * -# All pixels within a disc of radius \\f$2.5\\theta_*\\f$ of a masked pixel are masked.\n * -# The resulting map is smooth with a Gaussian window function with standard\n deviation \\f$\\sigma=\\theta_*\\f$.\n * -# One final pass is made through all pixels to ensure that all originally masked\n * pixels are still masked after the smoothing operation.\n */\nvoid nmt_apodize_mask(long nside,flouble *mask_in,flouble *mask_out,flouble aposize,char *apotype);\n\n\n/**\n * @brief Apodize flat-sky mask.\n *\n * Produces apodized version of a flat-sky mask for a number of apodization schemes.\n * @param nx Number of grid points in the x dimension\n * @param ny Number of grid points in the y dimension\n * @param lx Length of the x dimension (in steradians)\n * @param ly Length of the y dimension (in steradians)\n * @param mask_in Input mask to be apodized.\n * @param mask_out Output apodized mask.\n * @param aposize Apodization scale (in degrees).\n * @param apotype String defining the apodization procedure. See definitions of nmt_apodize_mask().\n */\nvoid nmt_apodize_mask_flat(int nx,int ny,flouble lx,flouble ly,\n\t\t\t flouble *mask_in,flouble *mask_out,flouble aposize,char *apotype);\n\n/**\n * @brief Flat-sky mode-coupling matrix.\n *\n * Structure containing information about the mode-coupling matrix (MCM) for flat-sky pseudo-CLs.\n */\ntypedef struct {\n int ncls; //!< Number of power spectra (1, 2 or 4 depending of the spins of the fields being correlated.\n flouble ellcut_x[2]; //!< Range of ells in the x direction to be masked in Fourie space\n flouble ellcut_y[2]; //!< Range of ells in the y direction to be masked in Fourie space\n int pe1; //!< Is the E-mode component of the first field purified?\n int pe2; //!< Is the E-mode component of the second field purified?\n int pb1; //!< Is the B-mode component of the first field purified?\n int pb2; //!< Is the B-mode component of the second field purified?\n nmt_flatsky_info *fs; //!< Contains information about rectangular flat-sky patch.\n int is_teb; //!< Does it hold all MCM elements to compute all of spin0-spin0, 0-2 and 2-2 correlations?\n int *n_cells; //!< Number of unmasked Fourier-space grid points contributing to a given bandpower\n flouble **coupling_matrix_unbinned; //!< Unbinned MCM\n flouble **coupling_matrix_binned; //!< Binned MCM\n nmt_binning_scheme_flat *bin; //!< Bandpowers defining the binning\n flouble lmax; //!< Maximum k-mode used\n gsl_matrix *coupling_matrix_binned_gsl; //!< GSL version of MCM (prepared for inversion)\n gsl_permutation *coupling_matrix_perm; //!< Complements \\p coupling_matrix_binned_gsl for inversion.\n} nmt_workspace_flat;\n\n/**\n * @brief nmt_workspace_flat destructor\n */\nvoid nmt_workspace_flat_free(nmt_workspace_flat *w);\n\n/**\n * @brief Computes mode-coupling matrix.\n *\n * Computes MCM for a given pair of flat-sky fields.\n * @param fl1 nmt_field_flat structure defining the first field to correlate.\n * @param fl2 nmt_field_flat structure defining the second field to correlate.\n * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers.\n * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked.\n * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked.\n * if \\p lmx_x < \\p lmn_x, no Fourier-space masked is performed.\n * @param lmn_y Same as \\p lmn_x for the y direction.\n * @param lmx_y Same as \\p lmx_x for the y direction.\n * @param is_teb if !=0, all mode-coupling matrices (0-0,0-2,2-2) will be computed at the same time.\n */\nnmt_workspace_flat *nmt_compute_coupling_matrix_flat(nmt_field_flat *fl1,nmt_field_flat *fl2,\n\t\t\t\t\t\t nmt_binning_scheme_flat *bin,\n\t\t\t\t\t\t flouble lmn_x,flouble lmx_x,\n\t\t\t\t\t\t flouble lmn_y,flouble lmx_y,int is_teb);\n\n/**\n * @brief Computes deprojection bias.\n *\n * Computes contaminant deprojection bias for a pair of fields.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field_flat structure defining the first field to correlate.\n * @param fl2 nmt_field_flat structure defining the second field to correlate.\n * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers.\n * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked.\n * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked.\n * if \\p lmx_x < \\p lmn_x, no Fourier-space masked is performed.\n * @param lmn_y Same as \\p lmn_x for the y direction.\n * @param lmx_y Same as \\p lmx_x for the y direction.\n * @param nl_prop Number of multipoles over which the proposed power spectrum is defined.\n * @param l_prop Array of multipoles over which the proposed power spectrum is defined.\n * @param cl_proposal Proposed power spectrum. Should have shape [ncls][\\p nl_prop], where\n \\p ncls is the appropriate number of power spectra given the spins of the input\n\t fields (e.g. \\p ncls = 2*2 = 4 if both fields have spin=2).\n * @param cl_bias Ouptput deprojection bias. Should be allocated to shape [ncls][nbpw],\n where \\p ncls is defined above and \\p nbpw is the number of bandpowers\n\t defined by \\p bin.\n */\nvoid nmt_compute_deprojection_bias_flat(nmt_field_flat *fl1,nmt_field_flat *fl2,\n\t\t\t\t\tnmt_binning_scheme_flat *bin,\n\t\t\t\t\tflouble lmn_x,flouble lmx_x,flouble lmn_y,flouble lmx_y,\n\t\t\t\t\tint nl_prop,flouble *l_prop,flouble **cl_proposal,\n\t\t\t\t\tflouble **cl_bias);\n\n/**\n * @brief Mode-couples an input power spectrum\n *\n * This function applies the effects of the mode-coupling the pseudo-CL estimator for a given\n * input power spectrum. This function should be used in conjunction with nmt_decouple_cl_l_flat()\n * to compute the theory prediction of the pseudo-CL estimator. See the scientific documentation\n * or the companion paper for further details on how this is done in particular for the flat-sky\n * approximation.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param w nmt_workspace_flat structure containing the mode-coupling matrix\n * @param nl Number of multipoles on which the input power spectrum is defined.\n * @param larr Array of multipoles on which the input power spectrum is defined.\n * @param cl_in Array of input power spectra. Should have shape [ncls][nl], where ncls is the\n appropriate number of power spectra given the fields being correlated (e.g. ncls=4=2*2\n\t for two spin-2 fields.\n * @param cl_out Array of output power spectra. Should have shape [ncls][nbpw], where ncls is\n defined above and nbpw is the number of bandpowers used to define \\p w.\n */\nvoid nmt_couple_cl_l_flat_fast(nmt_workspace_flat *w,int nl,flouble *larr,flouble **cl_in,\n\t\t\t\t flouble **cl_out);\n/**\n * @brief Mode-couples an input power spectrum\n *\n * Faster (but less accurate) version of nmt_couple_cl_l_flat_fast().\n * @param w nmt_workspace_flat structure containing the mode-coupling matrix\n * @param nl Number of multipoles on which the input power spectrum is defined.\n * @param larr Array of multipoles on which the input power spectrum is defined.\n * @param cl_in Array of input power spectra. Should have shape [ncls][nl], where ncls is the\n appropriate number of power spectra given the fields being correlated (e.g. ncls=4=2*2\n\t for two spin-2 fields.\n * @param cl_out Array of output power spectra. Should have shape [ncls][nbpw], where ncls is\n defined above and nbpw is the number of bandpowers used to define \\p w.\n */\nvoid nmt_couple_cl_l_flat_quick(nmt_workspace_flat *w,int nl,flouble *larr,flouble **cl_in,\n\t\t\t\tflouble **cl_out);\n\n/**\n * @brief Inverts mode-coupling matrix\n *\n * Multiplies coupled power spectra by inverse mode-coupling matrix.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param w nmt_workspace_flat containing the mode-coupling matrix.\n * @param cl_in Input coupled power spectra. Should have shape [ncls][nbpw], where\n \\p ncls is the appropriate number of power spectra given the fields used\n\t to define \\p w (e.g. 4=2*2 for two spin-2 fields) and \\p nbpw is the number\n\t of bandpowers used when defining \\p w.\n * @param cl_noise_in Noise bias (same shape as \\p cl_in).\n * @param cl_bias Deprojection bias (same shape as \\p cl_in, see nmt_compute_deprojection_bias_flat()).\n * @param cl_out Mode-decoupled power spectrum (same shape as \\p cl_in).\n */\nvoid nmt_decouple_cl_l_flat(nmt_workspace_flat *w,flouble **cl_in,flouble **cl_noise_in,\n\t\t\t flouble **cl_bias,flouble **cl_out);\n\n/**\n * @brief Coupled pseudo-CL\n *\n * Computes the pseudo-CL power spectrum of two fields without accounting for the mode-coupling\n * matrix.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field_flat structure defining the first field to correlate.\n * @param fl2 nmt_field_flat structure defining the second field to correlate.\n * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers.\n * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked.\n * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked.\n * if \\p lmx_x < \\p lmn_x, no Fourier-space masked is performed.\n * @param lmn_y Same as \\p lmn_x for the y direction.\n * @param lmx_y Same as \\p lmx_x for the y direction.\n * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][nbpw], where\n \\p ncls is the appropriate number of power spectra (e.g. 4=2*2 for two spin-2\n\t fields), and \\p nbpw is the number of bandpowers defined by \\p bin.\n */\nvoid nmt_compute_coupled_cell_flat(nmt_field_flat *fl1,nmt_field_flat *fl2,\n\t\t\t\t nmt_binning_scheme_flat *bin,flouble **cl_out,\n\t\t\t\t flouble lmn_x,flouble lmx_x,flouble lmn_y,flouble lmx_y);\n\n/**\n * @brief Computes pseudo-CL specrum.\n *\n * Wrapper function containing all the steps to compute a power spectrum. For performance\n * reasons, the blind use of this function is discouraged against a smarter combination of\n * nmt_workspace_flat structures and nmt_compute_coupled_cell_flat().\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field_flat structure defining the first field to correlate.\n * @param fl2 nmt_field_flat structure defining the second field to correlate.\n * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers.\n * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked.\n * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked.\n * if \\p lmx_x < \\p lmn_x, no Fourier-space masked is performed.\n * @param lmn_y Same as \\p lmn_x for the y direction.\n * @param lmx_y Same as \\p lmx_x for the y direction.\n * @param w0 nmt_workspace_flat structure containing the mode-coupling matrix. If NULL, a new\n computation of the MCM will be carried out and stored in the output nmt_workspace_flat.\n\t Otherwise, \\p w0 will be used and returned by this function.\n * @param nl_prop Number of multipoles over which the proposed power spectrum is defined.\n * @param l_prop Array of multipoles over which the proposed power spectrum is defined.\n * @param cl_prop Proposed power spectrum. Should have shape [ncls][\\p nl_prop], where\n \\p ncls is the appropriate number of power spectra given the spins of the input\n\t fields (e.g. \\p ncls = 2*2 = 4 if both fields have spin=2).\n * @param cl_noise Noise bias. Should have shape [ncls][nbpw], where \\p ncls is\n * defined above and \\p nbpw is the number of bandpowers defined by \\p bin.\n * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][nbpw],\n where \\p ncls is defined above and \\p nbpw is the number of bandpowers defined\n\t by \\p bin.\n * @return Newly allocated nmt_workspace_flat structure containing the mode-coupling matrix\n if \\p w0 is NULL (will return \\p w0 otherwise).\n */\nnmt_workspace_flat *nmt_compute_power_spectra_flat(nmt_field_flat *fl1,nmt_field_flat *fl2,\n\t\t\t\t\t\t nmt_binning_scheme_flat *bin,\n\t\t\t\t\t\t flouble lmn_x,flouble lmx_x,\n\t\t\t\t\t\t flouble lmn_y,flouble lmx_y,\n\t\t\t\t\t\t nmt_workspace_flat *w0,flouble **cl_noise,\n\t\t\t\t\t\t int nl_prop,flouble *l_prop,flouble **cl_prop,\n\t\t\t\t\t\t flouble **cl_out);\n\n/**\n * @brief Full-sky mode-coupling matrix.\n *\n * Structure containing information about the mode-coupling matrix (MCM) for full-sky pseudo-CLs.\n */\ntypedef struct {\n int lmax; //!< Maximum multipole used\n int lmax_fields; //!< Resolution of fields being correlated.\n int lmax_mask; //!< Mask resolution\n int is_teb; //!< Does it hold all MCM elements to compute all of spin0-spin0, 0-2 and 2-2 correlations?\n int ncls; //!< Number of power spectra (1, 2 or 4 depending of the spins of the fields being correlated.\n nmt_curvedsky_info *cs; //!< curved sky geometry information.\n flouble *beam_prod; //!< Product of field beams.\n flouble *pcl_masks; //!< Pseudo-CL of the masks.\n flouble **coupling_matrix_unbinned; //!< Unbinned mode-coupling matrix\n nmt_binning_scheme *bin; //!< Bandpowers defining the binning\n gsl_matrix *coupling_matrix_binned; //!< GSL version of MCM (prepared for inversion)\n gsl_permutation *coupling_matrix_perm; //!< Complements \\p coupling_matrix_binned_gsl for inversion.\n} nmt_workspace;\n \ntypedef struct {\n int lmax;\n int lmax_mask;\n int npcl;\n int s1;\n int s2;\n int has_00;\n flouble ***xi_00;\n int has_0s;\n flouble ****xi_0s;\n int has_ss;\n flouble ****xi_pp;\n flouble ****xi_mm;\n int pure_e1;\n int pure_e2;\n int pure_b1;\n int pure_b2;\n int pure_any;\n int npure_0s;\n int npure_ss;\n} nmt_master_calculator;\n\nnmt_master_calculator *nmt_compute_master_coefficients(int lmax, int lmax_mask,\n int npcl, flouble **pcl_masks,\n int s1, int s2,\n int pure_e1, int pure_b1,\n int pure_e2, int pure_b2,\n int do_teb, int l_toeplitz,\n int l_exact, int dl_band);\nvoid nmt_master_calculator_free(nmt_master_calculator *c);\n\n/**\n * @brief Computes mode-coupling matrix.\n *\n * Computes MCM for a given pair of full-sky fields.\n * @param fl1 nmt_field structure defining the first field to correlate.\n * @param fl2 nmt_field structure defining the second field to correlate.\n * @param bin nmt_binning_scheme defining the power spectrum bandpowers.\n * @param is_teb if !=0, all mode-coupling matrices (0-0,0-2,2-2) will be computed at the same time.\n * @param niter number of iterations when computing alms.\n * @param lmax_mask maximum multipole to which the masks should be resolved. If smaller than the maximum multipole of fl1/fl2, it will be set to that.\n * @return Newly allocated nmt_workspace structure containing the mode-coupling matrix.\n */\nnmt_workspace *nmt_compute_coupling_matrix(nmt_field *fl1,nmt_field *fl2,nmt_binning_scheme *bin,\n\t\t\t\t\t int is_teb,int niter,int lmax_mask,\n int l_toeplitz,int l_exact,int dl_band);\n\n/**\n * @brief Updates the mode coupling matrix with a new one.Saves nmt_workspace structure to file\n *\n * The new matrix must be provided as a single 1D array of size n_rows\\f$^2\\f$.\n * Here n_rows=n_cls * n_ell is the size of the flattened power spectra, where n_cls is the number\n * of power spectra (1, 2 or 4 for spin0-0, spin0-2 and spin2-2 correlations) and n_ells=lmax+1\n * (by default lmax=3*nside-1 for HEALPix, and pi/dx for CAR (where dx is the minimum angular pixel size)). The ordering of the power spectra should be such that the\n * l-th element of the i-th power spectrum is stored with index l * n_cls + i.\n * @param w nmt_workspace to be updated.\n * @param n_rows size of the flattened power spectra.\n * @param new_matrix new mode-coupling matrix (flattened).\n */\nvoid nmt_update_coupling_matrix(nmt_workspace *w,int n_rows,double *new_matrix);\n\n/**\n * @brief Updates the binning scheme associated to this workspace.\n *\n * Also rebins the MCM and re-inverts it.\n * @param w nmt_workspace to be updated.\n * @param bin new nmt_binning_scheme.\n */\nvoid nmt_workspace_update_binning(nmt_workspace *w,\n\t\t\t\t nmt_binning_scheme *bin);\n\n/**\n * @brief Updates the beams associated to this workspace.\n *\n * Also recomputes the binned MCM and its inverse\n * @param w workspace.\n * @param nl1 Number of elements of b1.\n * @param b1 First field's beam (harmonic space). One element per multipole.\n * @param nl2 Number of elements of b1.\n * @param b2 Second field's beam (harmonic space). One element per multipole.\n */\nvoid nmt_workspace_update_beams(nmt_workspace *w,\n\t\t\t\tint nl1,double *b1,\n\t\t\t\tint nl2,double *b2);\n\n/**\n * @brief nmt_workspace destructor\n */\nvoid nmt_workspace_free(nmt_workspace *w);\n\n/**\n * @brief Computes deprojection bias.\n *\n * Computes contaminant deprojection bias for a pair of fields.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field structure defining the first field to correlate.\n * @param fl2 nmt_field structure defining the second field to correlate.\n * @param cl_proposal Proposed power spectrum. Should have shape [ncls][lmax+1], where\n \\p ncls is the appropriate number of power spectra given the spins of the input\n\t fields (e.g. \\p ncls = 2*2 = 4 if both fields have spin=2).\n * @param cl_bias Ouptput deprojection bias. Should be allocated to shape [ncls][lmax+1],\n where \\p ncls is defined above.\n * @param niter number of iterations when computing alms.\n */\nvoid nmt_compute_deprojection_bias(nmt_field *fl1,nmt_field *fl2,\n\t\t\t\t flouble **cl_proposal,flouble **cl_bias,int niter);\n\n/**\n * @brief Noise bias from uncorrelated noise map\n *\n * Computes deprojection bias due to an source of uncorrelated noise given an input noise variance map.\n * See companion paper for more details.\n * @param fl1 nmt_field structure defining the properties of the field for which this noise bias\n applies.\n * @param map_var Noise variance map (should contain per-pixel noise variance).\n * @param cl_bias Ouptput noise bias. Should be allocated to shape [ncls][lmax+1],\n where \\p ncls is the appropriate number of power spectra given the spins of the input\n\t fields (e.g. \\p ncls = 2*2 = 4 if both fields have spin=2).\n * @param niter number of iterations when computing alms.\n */\nvoid nmt_compute_uncorr_noise_deprojection_bias(nmt_field *fl1,flouble *map_var,flouble **cl_bias,\n\t\t\t\t\t\tint niter);\n\n/**\n * @brief Mode-couples an input power spectrum\n *\n * This function applies the effects of the mode-coupling the pseudo-CL estimator for a given\n * input power spectrum. This function should be used in conjunction with nmt_decouple_cl_l()\n * to compute the theory prediction of the pseudo-CL estimator.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param w nmt_workspace structure containing the mode-coupling matrix\n * @param cl_in Array of input power spectra. Should have shape [ncls][lmax+1], where ncls\n is the appropriate number of power spectra given the fields being correlated\n\t (e.g. ncls=4=2*2 for two spin-2 fields).\n * @param cl_out Array of output power spectra. Should have shape [ncls][lmax+1], where\n ncls is defined above.\n */\nvoid nmt_couple_cl_l(nmt_workspace *w,flouble **cl_in,flouble **cl_out);\n\n/**\n * @brief Inverts mode-coupling matrix\n *\n * Multiplies coupled power spectra by inverse mode-coupling matrix.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param w nmt_workspace containing the mode-coupling matrix.\n * @param cl_in Input coupled power spectra. Should have shape [ncls][lmax+1], where\n \\p ncls is the appropriate number of power spectra given the fields used\n\t to define \\p w (e.g. 4=2*2 for two spin-2 fields).\n * @param cl_noise_in Noise bias (same shape as \\p cl_in).\n * @param cl_bias Deprojection bias (same shape as \\p cl_in, see nmt_compute_deprojection_bias()).\n * @param cl_out Mode-decoupled power spectrum. Should have shape [ncls][nbpw], where\n ncls is defined above and nbpw is the number of bandpowers used to define \\p w.\n */\nvoid nmt_decouple_cl_l(nmt_workspace *w,flouble **cl_in,flouble **cl_noise_in,\n\t\t flouble **cl_bias,flouble **cl_out);\n\n/**\n * @brief Returns the bandpower window functions for this workspace.\n *\n * This function returns, in a flattened array, the bandpower window functions associated with the\n * mode-coupling matrix stored in this workspace. The effect of the PCL estimator on the unbinned\n * theory prediction can be fully accounted for by convolving it with these window functions.\n * @param w nmt_workspace containing the mode-coupling matrix.\n * @param bpw_win_out output 1D array allocated to the right size (n_cls * n_bpw * n_cls * (lmax+1)).\n */\nvoid nmt_compute_bandpower_windows(nmt_workspace *w,double *bpw_win_out);\n\n/**\n * @brief Coupled pseudo-CL\n *\n * Computes the pseudo-CL power spectrum of two fields without accounting for the mode-coupling\n * matrix. This is essentially equivalent to running HEALPix's 'anafast' on the purified and\n * contaminant-deprojected input fields.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field structure defining the first field to correlate.\n * @param fl2 nmt_field structure defining the second field to correlate.\n * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][lmax+1], where\n \\p ncls is the appropriate number of power spectra (e.g. 4=2*2 for two spin-2 fields).\n */\nvoid nmt_compute_coupled_cell(nmt_field *fl1,nmt_field *fl2,flouble **cl_out);\n\n/**\n * @brief Computes pseudo-CL specrum.\n *\n * Wrapper function containing all the steps to compute a power spectrum. For performance\n * reasons, the blind use of this function is discouraged against a smarter combination of\n * nmt_workspace structures and nmt_compute_coupled_cell().\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field structure defining the first field to correlate.\n * @param fl2 nmt_field structure defining the second field to correlate.\n * @param bin nmt_binning_scheme defining the power spectrum bandpowers.\n * @param w0 nmt_workspace structure containing the mode-coupling matrix. If NULL, a new\n computation of the MCM will be carried out and stored in the output nmt_workspace.\n\t Otherwise, \\p w0 will be used and returned by this function.\n * @param cl_proposal Proposed power spectrum. Should have shape [ncls][lmax+1], where\n \\p ncls is the appropriate number of power spectra given the spins of the input\n\t fields (e.g. \\p ncls = 2*2 = 4 if both fields have spin=2).\n * @param cl_noise Noise bias (same shape as \\p cl_prop).\n * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][nbpw],\n where \\p ncls is defined above and \\p nbpw is the number of bandpowers defined\n\t by \\p bin.\n * @param niter number of iterations when computing alms.\n * @param lmax_mask maximum multipole to which the masks should be resolved. If smaller than the maximum multipole of fl1/fl2, it will be set to that.\n * @return Newly allocated nmt_workspace structure containing the mode-coupling matrix\n if \\p w0 is NULL (will return \\p w0 otherwise).\n */\nnmt_workspace *nmt_compute_power_spectra(nmt_field *fl1,nmt_field *fl2,\n\t\t\t\t\t nmt_binning_scheme *bin,nmt_workspace *w0,\n\t\t\t\t\t flouble **cl_noise,flouble **cl_proposal,flouble **cl_out,\n\t\t\t\t\t int niter,int lmax_mask,int l_toeplitz,\n int l_exact,int dl_band);\n\n/**\n * @brief Flat-sky Gaussian covariance matrix\n *\n * Structure containing the information necessary to compute Gaussian covariance matrices\n * for the pseudo-CL spectra of two flat-sky spin-0 fields.\n *\n */\ntypedef struct {\n nmt_binning_scheme_flat *bin; //!< Bandpowers defining the binning\n flouble **xi00_1122; //!< First (a1b1-a2b2), 00, mode coupling matrix (see scientific documentation)\n flouble **xi00_1221; //!< Second (a1b2-a2b1), 00, mode coupling matrix (see scientific documentation)\n flouble **xi02_1122; //!< First (a1b1-a2b2), 02, mode coupling matrix (see scientific documentation)\n flouble **xi02_1221; //!< Second (a1b2-a2b1), 02, mode coupling matrix (see scientific documentation)\n flouble **xi22p_1122; //!< First (a1b1-a2b2), 22p, mode coupling matrix (see scientific documentation)\n flouble **xi22p_1221; //!< Second (a1b2-a2b1), 22p, mode coupling matrix (see scientific documentation)\n flouble **xi22m_1122; //!< First (a1b1-a2b2), 22m, mode coupling matrix (see scientific documentation)\n flouble **xi22m_1221; //!< Second (a1b2-a2b1), 22m, mode coupling matrix (see scientific documentation)\n} nmt_covar_workspace_flat;\n\n/**\n * @brief nmt_covar_workspace_flat destructor.\n */\nvoid nmt_covar_workspace_flat_free(nmt_covar_workspace_flat *cw);\n\n/**\n * @brief nmt_covar_workspace_flat constructor\n *\n * Builds an nmt_covar_workspace_flat structure from two nmt_workspace_flat structures, corresponding\n * to the two sets of power spectra for which the covariance is required.\n * @param fla1 nmt_field_field for the first field going into the first (a-th) power spectrum.\n * @param fla2 nmt_field_field for the second field going into the first (a-th) power spectrum.\n * @param flb1 nmt_field_field for the first field going into the second (b-th) power spectrum.\n * @param flb2 nmt_field_field for the second field going into the second (b-th) power spectrum.\n * @param ba nmt_binning_scheme_flat used for the first power spectrum.\n * @param bb nmt_binning_scheme_flat used for the second power spectrum.\n */\nnmt_covar_workspace_flat *nmt_covar_workspace_flat_init(nmt_field_flat *fla1,nmt_field_flat *fla2,\n\t\t\t\t\t\t\tnmt_binning_scheme_flat *ba,\n\t\t\t\t\t\t\tnmt_field_flat *flb1,nmt_field_flat *flb2,\n\t\t\t\t\t\t\tnmt_binning_scheme_flat *bb);\n\n/**\n * @brief Compute flat-sky Gaussian covariance matrix\n *\n * Computes the covariance matrix for two sets of power spectra given input predicted spectra\n * and two nmt_covar_workspace_flat structures.\n * @param cw nmt_covar_workspace_flat structure containing the information necessary to compute the\n covariance matrix.\n * @param spin_a field a spin.\n * @param spin_b field b spin.\n * @param spin_c field c spin.\n * @param spin_d field d spin.\n * @param wa nmt_workspace_flat structure containing the mode-coupling matrix for the first power spectra (between fields a and b).\n * @param wb nmt_workspace_flat structure containing the mode-coupling matrix for the second power spectra (between fields c and d).\n * @param nl Number of multipoles in which input power spectra are computed.\n * @param larr Array of multipoles in which input power spectra are computed.\n * @param clac Cross-power spectra between field 1 in the first set and field 1 in the second set (ac)\n * @param clad Cross-power spectra between field 1 in the first set and field 2 in the second set (ad)\n * @param clbc Cross-power spectra between field 2 in the first set and field 1 in the second set (bc)\n * @param clbd Cross-power spectra between field 2 in the first set and field 2 in the second set (bd)\n * @param covar_out flattened covariance matrix. Should be allocated to shape [ncls_1 * nbpw_1 * ncls_2 * nbpw_2],\n where nbpw_X and ncls_X are the number of bandpowers and different power spectra in the X-th set of fields.\n */\nvoid nmt_compute_gaussian_covariance_flat(nmt_covar_workspace_flat *cw,\n\t\t\t\t\t int spin_a,int spin_b,int spin_c,int spin_d,\n\t\t\t\t\t nmt_workspace_flat *wa,nmt_workspace_flat *wb,\n\t\t\t\t\t int nl,flouble *larr,\n\t\t\t\t\t flouble **clac,flouble **clad,\n\t\t\t\t\t flouble **clbc,flouble **clbd,flouble *covar_out);\n\n/**\n * @brief Full-sky Gaussian covariance matrix\n *\n * Structure containing the information necessary to compute Gaussian covariance matrices\n * for the pseudo-CL spectra of two full-sky spin-0 fields.\n */\ntypedef struct {\n int lmax; //!< Maximum multipole for the first set of power spectra\n flouble **xi00_1122; //!< First (a1b1-a2b2), 00, mode coupling matrix (see scientific documentation)\n flouble **xi00_1221; //!< Second (a1b2-a2b1), 00, mode coupling matrix (see scientific documentation)\n flouble **xi02_1122; //!< First (a1b1-a2b2), 02, mode coupling matrix (see scientific documentation)\n flouble **xi02_1221; //!< Second (a1b2-a2b1), 02, mode coupling matrix (see scientific documentation)\n flouble **xi22p_1122; //!< First (a1b1-a2b2), 22+, mode coupling matrix (see scientific documentation)\n flouble **xi22p_1221; //!< Second (a1b2-a2b1), 22+, mode coupling matrix (see scientific documentation)\n flouble **xi22m_1122; //!< First (a1b1-a2b2), 22-, mode coupling matrix (see scientific documentation)\n flouble **xi22m_1221; //!< Second (a1b2-a2b1), 22-, mode coupling matrix (see scientific documentation)\n} nmt_covar_workspace;\n\n/**\n * @brief nmt_covar_workspace destructor.\n */\nvoid nmt_covar_workspace_free(nmt_covar_workspace *cw);\n\n/**\n * @brief nmt_covar_workspace constructor\n *\n * Builds an nmt_covar_workspace structure from two pairs of nmt_field structures, corresponding\n * to the two sets of power spectra for which the covariance is required.\n * @param fla1 nmt_field for the first field going into the first (a-th) power spectrum.\n * @param fla2 nmt_field for the second field going into the first (a-th) power spectrum.\n * @param flb1 nmt_field for the first field going into the second (b-th) power spectrum.\n * @param flb2 nmt_field for the second field going into the second (b-th) power spectrum.\n * @param lmax maximum multipole up to which the coupling coefficients will be calculated.\n * @param niter number of iterations when computing alms.\n */\nnmt_covar_workspace *nmt_covar_workspace_init(nmt_field *fla1,nmt_field *fla2,\n\t\t\t\t\t nmt_field *flb1,nmt_field *flb2,\n\t\t\t\t\t int lmax,int niter,\n int l_toeplitz,int l_exact,int dl_band);\n\n/**\n * @brief Compute full-sky Gaussian covariance matrix\n *\n * Computes the covariance matrix for two sets of power spectra given input predicted spectra\n * and a nmt_covar_workspace structure.\n * @param cw nmt_covar_workspace structure containing the information necessary to compute the\n covariance matrix.\n * @param spin_a field a spin.\n * @param spin_b field b spin.\n * @param spin_c field c spin.\n * @param spin_d field d spin.\n * @param wa nmt_workspace structure containing the mode-coupling matrix for the first power spectra.\n * @param wb nmt_workspace structure containing the mode-coupling matrix for the second power spectra.\n * @param clac Cross-power spectra between field 1 in the first set and field 1 in the second set (ac)\n All power spectra should be defined for all ell < lmax.\n * @param clad Cross-power spectra between field 1 in the first set and field 2 in the second set (ad)\n * @param clbc Cross-power spectra between field 2 in the first set and field 1 in the second set (bc)\n * @param clbd Cross-power spectra between field 2 in the first set and field 2 in the second set (bd)\n * @param covar_out flattened covariance matrix. Should be allocated to shape [ncls_1 * nbpw_1 * ncls_2 * nbpw_2],\n where nbpw_X and ncls_X are the number of bandpowers and different power spectra in the X-th set of fields.\n */\nvoid nmt_compute_gaussian_covariance(nmt_covar_workspace *cw,\n\t\t\t\t int spin_a,int spin_b,int spin_c,int spin_d,\n\t\t\t\t nmt_workspace *wa,nmt_workspace *wb,\n\t\t\t\t flouble **clac,flouble **clad,\n\t\t\t\t flouble **clbc,flouble **clbd,\n\t\t\t\t flouble *covar_out);\n\n/**\n * @brief Compute full-sky Gaussian covariance matrix\n *\n * Computes the covariance matrix for two sets of power spectra given input predicted spectra\n * and a nmt_covar_workspace structure. Calculation done for the mode-coupled pseudo-Cls.\n * @param cw nmt_covar_workspace structure containing the information necessary to compute the\n covariance matrix.\n * @param spin_a field a spin.\n * @param spin_b field b spin.\n * @param spin_c field c spin.\n * @param spin_d field d spin.\n * @param wa nmt_workspace structure containing the mode-coupling matrix for the first power spectra.\n * @param wb nmt_workspace structure containing the mode-coupling matrix for the second power spectra.\n * @param clac Cross-power spectra between field 1 in the first set and field 1 in the second set (ac)\n All power spectra should be defined for all ell < lmax.\n * @param clad Cross-power spectra between field 1 in the first set and field 2 in the second set (ad)\n * @param clbc Cross-power spectra between field 2 in the first set and field 1 in the second set (bc)\n * @param clbd Cross-power spectra between field 2 in the first set and field 2 in the second set (bd)\n * @param covar_out flattened covariance matrix. Should be allocated to shape [ncls_1 * nbpw_1 * ncls_2 * nbpw_2],\n where nbpw_X and ncls_X are the number of bandpowers and different power spectra in the X-th set of fields.\n */\nvoid nmt_compute_gaussian_covariance_coupled(nmt_covar_workspace *cw,\n int spin_a,int spin_b,int spin_c,int spin_d,\n nmt_workspace *wa,nmt_workspace *wb,\n flouble **clac,flouble **clad,\n flouble **clbc,flouble **clbd,\n flouble *covar_out);\n\n/**\n * @brief Saves nmt_workspace structure to file\n *\n * The output file uses the FITS standard. In combination with nmt_workspace_read_fits(),\n * this can be used to save the information contained in a given workspace and reuse it for\n * future power spectrum computations. The same workspace can be used on any pair of fields\n * with the same masks.\n * @param w nmt_workspace to be saved.\n * @param fname Path to output file.\n */\nvoid nmt_workspace_write_fits(nmt_workspace *w,char *fname);\n\n/**\n * @brief Builds nmt_workspace structure from file\n *\n * The input file uses the FITS standard. In combination with nmt_workspace_write_fits(),\n * this can be used to save the information contained in a given workspace and reuse it for\n * future power spectrum computations. The same workspace can be used on any pair of fields\n * with the same masks.\n * @param fname Path to input file.\n */\nnmt_workspace *nmt_workspace_read_fits(char *fname);\n\n/**\n * @brief Builds nmt_workspace_flat structure from file\n *\n * The input file uses the FITS standard. In combination with nmt_workspace_flat_write_fits(),\n * this can be used to save the information contained in a given workspace and reuse it for\n * future power spectrum computations. The same workspace can be used on any pair of fields\n * with the same masks.\n * @param fname Path to input file.\n */\nnmt_workspace_flat *nmt_workspace_flat_read_fits(char *fname);\n\n/**\n * @brief Saves nmt_workspace_flat structure to file\n *\n * The output file uses the FITS standard. In combination with nmt_workspace_flat_read_fits(),\n * this can be used to save the information contained in a given workspace and reuse it for\n * future power spectrum computations. The same workspace can be used on any pair of fields\n * with the same masks.\n * @param w nmt_workspace_flat to be saved.\n * @param fname Path to output file.\n */\nvoid nmt_workspace_flat_write_fits(nmt_workspace_flat *w,char *fname);\n\n/**\n * @brief Saves nmt_covar_workspace structure to file\n *\n * The output file uses the FITS standard. In combination with nmt_covar_workspace_read_fits(),\n * this can be used to save the information contained in a given workspace and reuse it for\n * future covariance matrix computations. The same workspace can be used on any pair of power spectra\n * between fields with the same masks.\n * @param cw nmt_covar_workspace to be saved.\n * @param fname Path to output file.\n */\nvoid nmt_covar_workspace_write_fits(nmt_covar_workspace *cw,char *fname);\n\n/**\n * @brief Builds nmt_covar_workspace structure from file\n *\n * The input file uses the FITS standard. In combination with nmt_covar_workspace_write_fits(),\n * this can be used to save the information contained in a given workspace and reuse it for\n * future covariance matrix computations. The same workspace can be used on any pair of power spectra\n * between fields with the same masks.\n * @param fname Path to input file.\n */\nnmt_covar_workspace *nmt_covar_workspace_read_fits(char *fname);\n\n/**\n * @brief Saves nmt_covar_workspace_flat structure to file\n *\n * The output file uses the FITS standard. In combination with nmt_covar_workspace_flat_read_fits(),\n * this can be used to save the information contained in a given workspace and reuse it for\n * future covariance matrix computations. The same workspace can be used on any pair of power spectra\n * between fields with the same masks.\n * @param cw nmt_covar_workspace_flat to be saved.\n * @param fname Path to output file.\n */\nvoid nmt_covar_workspace_flat_write_fits(nmt_covar_workspace_flat *cw,char *fname);\n\n/**\n * @brief Builds nmt_covar_workspace_flat structure from file\n *\n * The input file uses the FITS standard. In combination with nmt_covar_workspace_flat_write_fits(),\n * this can be used to save the information contained in a given workspace and reuse it for\n * future covariance matrix computations. The same workspace can be used on any pair of power spectra\n * between fields with the same masks.\n * @param fname Path to input file.\n */\nnmt_covar_workspace_flat *nmt_covar_workspace_flat_read_fits(char *fname);\n\n#endif //_NAMASTER_H_\n", "meta": {"hexsha": "391c6a9126191b6e75b13a587a9e24e5f2f048bd", "size": 71703, "ext": "h", "lang": "C", "max_stars_repo_path": "src/namaster.h", "max_stars_repo_name": "LSSTDESC/NaMaster", "max_stars_repo_head_hexsha": "3707cf5d78688340f81d836f24a48435149d4df3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T15:59:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T19:47:36.000Z", "max_issues_repo_path": "src/namaster.h", "max_issues_repo_name": "LSSTDESC/NaMaster", "max_issues_repo_head_hexsha": "3707cf5d78688340f81d836f24a48435149d4df3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 96.0, "max_issues_repo_issues_event_min_datetime": "2018-08-20T07:35:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T13:38:23.000Z", "max_forks_repo_path": "src/namaster.h", "max_forks_repo_name": "LSSTDESC/NaMaster", "max_forks_repo_head_hexsha": "3707cf5d78688340f81d836f24a48435149d4df3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2018-08-16T21:15:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:28:48.000Z", "avg_line_length": 50.4950704225, "max_line_length": 165, "alphanum_fraction": 0.7329121515, "num_tokens": 18078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.40919377937218904}} {"text": "#include \n\nstatic PetscErrorCode SetInitialCondition(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx){\n\n u[0] = x[0];\n return 0;\n}\n\n\nstatic PetscErrorCode PrintFVGradients(DM dm){\n PetscFunctionBeginUser;\n PetscErrorCode ierr;\n\n // Convert the dm to a plex\n DM plex;\n DMConvert(dm, DMPLEX, &plex);\n\n // Get the start/end\n PetscInt fStart;\n PetscInt fEnd;\n ierr = DMPlexGetHeightStratum(plex, 1, &fStart, &fEnd);CHKERRQ(ierr);\n\n // Extract the cell geometry, and the dm that holds the information\n Vec faceGeometry;\n DM dmFace;\n ierr = DMPlexGetGeometryFVM(plex, &faceGeometry, NULL, NULL);CHKERRQ(ierr);\n\n ierr = VecGetDM(faceGeometry, &dmFace);CHKERRQ(ierr);\n\n const PetscScalar *facegeom;\n ierr = VecGetArrayRead(faceGeometry, &facegeom);CHKERRQ(ierr);\n\n // Get the dim\n PetscInt dim;\n ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);\n\n // March over each cell volume\n for (PetscInt f = fStart; f < fEnd; ++f) {\n PetscFVFaceGeom *fg;\n\n ierr = DMPlexPointLocalRead(dmFace, f, facegeom, &fg);CHKERRQ(ierr);\n\n printf(\"Face Grad %d: \", f);\n for(PetscInt d =0; d< dim; d++){\n printf(\"%f/%f, \", fg->grad[0][d], fg->grad[1][d]);\n }\n printf(\"\\n\");\n }\n\n PetscFunctionReturn(0);\n}\n\nint main(int argc, char **argv)\n{\n DM dm;\n PetscErrorCode ierr;\n\n ierr = PetscInitialize(&argc, &argv, NULL, \"HELP\");if (ierr) return(ierr);\n ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, 2, PETSC_FALSE, NULL, NULL, NULL, NULL, PETSC_TRUE, &dm);CHKERRQ(ierr);\n ierr = DMViewFromOptions(dm, NULL, \"-dm_view\");CHKERRQ(ierr);\n ierr = DMSetFromOptions(dm);CHKERRQ(ierr);\n\n {\n DM gdm;\n\n ierr = DMPlexConstructGhostCells(dm, NULL, NULL, &gdm);CHKERRQ(ierr);\n ierr = DMDestroy(&dm);CHKERRQ(ierr);\n dm = gdm;\n }\n ierr = DMViewFromOptions(dm, NULL, \"-dm_view_ghost\");CHKERRQ(ierr);\n\n PetscFV fvm;\n PetscDS ds;\n\n ierr = PetscFVCreate(PETSC_COMM_WORLD, &fvm);CHKERRQ(ierr);\n ierr = PetscFVSetFromOptions(fvm);CHKERRQ(ierr);\n ierr = PetscFVSetNumComponents(fvm, 1);CHKERRQ(ierr);\n ierr = PetscFVSetSpatialDimension(fvm, 2);CHKERRQ(ierr);\n ierr = PetscObjectSetName((PetscObject) fvm, \"outputField\");CHKERRQ(ierr);\n\n /* FV is now structured with one field having all physics as components */\n ierr = DMAddField(dm, NULL, (PetscObject) fvm);CHKERRQ(ierr);\n ierr = PetscFVDestroy(&fvm);CHKERRQ(ierr);\n ierr = DMCreateDS(dm);CHKERRQ(ierr);\n ierr = DMGetDS(dm, &ds);CHKERRQ(ierr);\n\n Vec X;\n PetscErrorCode (*func[1]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {SetInitialCondition};\n\n ierr = DMCreateGlobalVector(dm, &X);CHKERRQ(ierr);\n ierr = PetscObjectSetName((PetscObject) X, \"solution\");CHKERRQ(ierr);\n ierr = DMProjectFunction(dm, 0.0, func, NULL, INSERT_ALL_VALUES, X);CHKERRQ(ierr);\n ierr = VecViewFromOptions(X, NULL, \"-vec_view\");CHKERRQ(ierr);\n\n PrintFVGradients(dm);\n\n ierr = VecDestroy(&X);CHKERRQ(ierr);\n ierr = DMDestroy(&dm);CHKERRQ(ierr);\n return PetscFinalize();\n}\n", "meta": {"hexsha": "2fcf99d20c7ccbf6fa018e91ada2371d3b07b4d7", "size": 3212, "ext": "c", "lang": "C", "max_stars_repo_path": "fvOutput.c", "max_stars_repo_name": "mmcgurn/MattFlowCases", "max_stars_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fvOutput.c", "max_issues_repo_name": "mmcgurn/MattFlowCases", "max_issues_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fvOutput.c", "max_forks_repo_name": "mmcgurn/MattFlowCases", "max_forks_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.801980198, "max_line_length": 150, "alphanum_fraction": 0.6513075965, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4089413254121543}} {"text": "#include \n#include \"sweeny_bfs.h\"\n#include \"../src/queue_2.h\"\n#include \n#include \n#include \n#include \n#include \n\n// Define Macro SEQUENTIAL to use sequential BFS; Default is interleaved BFS\n\n#define MIN(a,b) a<=b ? a: b\n#define MAX(a,b) a>=b? a:b\n\nstatic char setup=0; // 0 not setup; 1 ibfs; 2 sbfs\nstatic char verbose=0;\nstatic double rcWeights[4]; // array with precalculated mc weights\nstatic double p_min_del,p_max_del, p_min_ins,p_max_ins;\nstatic __s8 dN,dB;\nstatic char equilibration=1;\nstatic __u32 DX;\nstatic __u32 N;\nstatic __u32 seed;\nstatic double q; \nstatic double coupling;\nstatic double beta;\nstatic double v;\nstatic double K;\nstatic __u32 steps;\nstatic __s8 *bonds;\nstatic gsl_rng * r; \nstatic __u32 edge[2];\nstatic __s32 adj1[4];\nstatic __s32 adj2[4];\nstatic __u32 offset_1;\nstatic __u32 offset_2;\nstatic __u32 cs2;\nstatic struct queue_2_node *todo_pool;\nstatic __u32 *visited;\nstatic __u32 cs1;\nstatic __u32 activeEdges=0;\nstatic __u32 cutoff;\nstatic __u32 *num_bonds , *num_cluster, *size_giant;\nstatic __u64 *sec_cs_moment, *four_cs_moment;\n\n/******************************************************************************\n *****************************************************************************/\nstatic char init(void)\n{\n K=coupling*beta;\n v = exp(K) - 1.0;\n N = DX*DX;\n // Deletion accept. ratios\n rcWeights[0] = pow(v,-1); //db==-1,dN==0\n rcWeights[1] = rcWeights[0]*q; //db==-1,dN=1\n // Insertion accept. ratios\n rcWeights[2] = v; //db==1,dN==0\n rcWeights[3] = v*pow(q,-1); //db==1,dN==-1\n \n p_min_del = MIN(rcWeights[0],rcWeights[1]); \n p_max_del = MAX(rcWeights[0],rcWeights[1]);\n p_min_ins = MIN(rcWeights[2],rcWeights[3]);\n p_max_ins = MAX(rcWeights[2],rcWeights[3]); \n\n r = gsl_rng_alloc (gsl_rng_mt19937);\n if(!r)\n return 0;\n gsl_rng_set(r,seed);\n __u32 i;\n bonds = malloc(sizeof(*bonds)*2*N);\n if(!bonds) {\n return 0;\n }\n for(i=0;i<2*N;i++) bonds[i] = -1;\n visited = calloc(N,sizeof(*visited));\n if(!visited) {\n return 0;\n }\n todo_pool = malloc(N*sizeof(struct queue_2_node));\n if(!todo_pool) {\n return 0;\n }\n return 1; \n\n}\n/******************************************************************************\n *****************************************************************************/\nstatic void destroy(void)\n{\n if(!setup)return;\n free(todo_pool);\n free(bonds);\n gsl_rng_free(r);\n free(visited);\n}\n/******************************************************************************\n *****************************************************************************/\nstatic inline __u32 ltcXnext(__u32 idx)\n{\n if((idx+1) % DX)\n return idx+1;\n else\n return idx +1- DX ;\n}\n/******************************************************************************\n *****************************************************************************/\nstatic inline __u32 ltcXprev(__u32 idx)\n{\n if((idx%DX))\n return idx-1;\n else\n return idx + DX -1;\n}\n/******************************************************************************\n *****************************************************************************/\n static inline __u32 ltcYnext(__u32 idx)\n{\n\n if(idx <= N -1 && idx >= N - DX)\n return idx +DX- N ;\n else\n return idx+DX;\n}\n/******************************************************************************\n *****************************************************************************/\nstatic inline __u32 ltcYprev(__u32 idx)\n{\n if(idx <= DX - 1) \n return idx + N - DX;\n else\n return idx - DX;\n\n}\n/******************************************************************************\n *****************************************************************************/\nstatic void Adjacent(__u32 bidx)\n{\n\n if(bidx%2) { \n bidx = (bidx -1)/2;\n edge[0] = bidx;\n edge[1] = ltcXnext(bidx);\n }\n else {\n bidx = bidx/2;\n edge[0] = bidx;\n edge[1] = ltcYprev(bidx);\n }\n\n\n}\n/******************************************************************************\n *****************************************************************************/\nstatic void neighbours(__u32 idx,__u8 a) {\n if(a == 1)\n {\n if(bonds[2*idx] == 1) adj1[0] = ltcYprev(idx);\n else adj1[0] = -1;\n if(bonds[(2*idx)+1] == 1) adj1[1] = ltcXnext(idx);\n else adj1[1] = -1;\n if(bonds[2*ltcYnext(idx)] == 1)\tadj1[2] = ltcYnext(idx);\n else adj1[2] = -1;\n if(bonds[(2*ltcXprev(idx))+1] ==1)adj1[3] = ltcXprev(idx);\n else adj1[3] = -1;\n }\n else {\n if(bonds[2*idx] == 1)adj2[0] = ltcYprev(idx);\n else adj2[0] = -1;\n if(bonds[(2*idx)+1] == 1)adj2[1] = ltcXnext(idx);\n else adj2[1] = -1;\n if(bonds[2*ltcYnext(idx)] == 1)\tadj2[2] = ltcYnext(idx);\n else adj2[2] = -1;\n if(bonds[(2*ltcXprev(idx))+1] == 1)adj2[3] = ltcXprev(idx);\n else adj2[3] = -1;\n }\n\n}\n/******************************************************************************\n *****************************************************************************/\nstatic __u8 breadthFirstSearch_s(__u32 start, __u32 goal)\n{\n static struct queue_2 todo1;\n __u32 i=0,activeP1=0;\n init_queue_2(&todo1); //todo_pool);\n cs1=0;\n enqueue_2(&todo1,start); \n cs1++; // Increase cluster size of bfs 1\n visited[start] = offset_1; // mark starting point as visited\n while(!queue_2_empty_p(&todo1)) { \n dequeue_2(&todo1,&activeP1);\n neighbours(activeP1,1);\n for(i=0;i<4;i++) {\n if(adj1[i] != -1) {\n if(visited[adj1[i]] == offset_1) continue;\n if((__u32)adj1[i] == goal) {\n while(!queue_2_empty_p(&todo1)){ dequeue_2(&todo1,&activeP1);}\n return 1;\n }\n enqueue_2(&todo1,adj1[i]);\n visited[adj1[i]] = offset_1;\n cs1++;\n }\n }\n }\n return 0;\n}\n/******************************************************************************\n *****************************************************************************/\nstatic __u8 breadthFirstSearch(__u32 start, __u32 goal)\n{\n static struct queue_2 todo1,todo2;\n __u32 i=0,activeP1=0,activeP2=0;\n init_queue_2(&todo1);\n init_queue_2(&todo2);\n cs1=0;\n cs2=0;\n enqueue_2(&todo1,start); // Put starting point onto queue_2 1\n cs1++; // Increase cluster size of bfs 1\n visited[start] = offset_1; // mark starting point as visited\n enqueue_2(&todo2,goal); // Put goal point onto queue_2 2\n visited[goal] = offset_2; // mark goal point as visited\n cs2++; // increase cluster size of bfs 2\n while(!queue_2_empty_p(&todo1) && !queue_2_empty_p(&todo2)) { \n dequeue_2(&todo2,&activeP2); // get next vertex of bfs 2\n neighbours(activeP2,2);\t // get all adjacent vertices of current vertex\n for(i=0;i<4;i++) {\n\n if(adj2[i] != -1) { // if accessable (edge exists)\n\t if(visited[adj2[i]] == offset_2) continue; // already visited\n\t if((__u32)adj2[i] == start || visited[adj2[i]] == offset_1) { // reconnected\n\n while(!queue_2_empty_p(&todo1)){ dequeue_2(&todo1,&activeP1);}\n while(!queue_2_empty_p(&todo2)){ dequeue_2(&todo2,&activeP2);}\n\t return 1; // 1 indicates success\n\t }\n\t enqueue_2(&todo2,adj2[i]);\n\t visited[adj2[i]] = offset_2; // mark as visited\n\t cs2++; // increase cluster size\n\t }\n }\n dequeue_2(&todo1,&activeP1);\n neighbours(activeP1,1);\n for(i=0;i<4;i++) {\n\tif(adj1[i] != -1) {\n\t if(visited[adj1[i]] == offset_1) continue;\n\t if((__u32)adj1[i] == goal || visited[adj1[i]] == offset_2) {\n while(!queue_2_empty_p(&todo1)){ dequeue_2(&todo1,&activeP1);}\n while(!queue_2_empty_p(&todo2)){ dequeue_2(&todo2,&activeP2);}\n\t\t\treturn 1;\n\t }\n\t enqueue_2(&todo1,adj1[i]);\n\t visited[adj1[i]] = offset_1;\n\t cs1++;\n\t}\n }\n }\n while(!queue_2_empty_p(&todo1)){dequeue_2(&todo1,&activeP1);}\n while(!queue_2_empty_p(&todo2)){dequeue_2(&todo2,&activeP2);}\n return 0; \n}\n/******************************************************************************\n *****************************************************************************/\nstatic inline __u8 connected(__u32 start, __u32 goal) {\n offset_1+=2;\n offset_2+=2;\n return breadthFirstSearch(start,goal);\n}\n\n/******************************************************************************\n *****************************************************************************/\n__u8 static inline connected_s(__u32 start, __u32 goal) {\n ++offset_1;\n return breadthFirstSearch_s(start,goal);\n}\n/******************************************************************************\n *****************************************************************************/\nstatic inline void sweep_ibfs(void)\n{\n static __u32 bidx;\n static double rnd_num;\n __u32 i=0;\n \n for(;i<2*N ;++i) {\n bidx = gsl_rng_uniform_int(r,2*N);\n rnd_num = gsl_rng_uniform(r);\n Adjacent(bidx);\n if(bonds[bidx] == 1) { //edge is active hence delete it\n dB = -1;\n if(rnd_num < p_min_del) { // accept bond deletion\n bonds[bidx]*=-1;\n activeEdges--;\n }\n else {\n if(rnd_num < p_max_del) {\n bonds[bidx]*=-1;\n dN = (connected(edge[0],edge[1])? 0 : 1);\n if(rnd_num >= rcWeights[dB == -1? dN : 2-dN]) bonds[bidx]*=-1; // undo bond deletion\n else activeEdges--; // accept bond deletion\n }\n\n }\n\n }\n else {\t\n // Insert cedge. If adjacent vertices are already connected, the new \n // edge will be a non-tree edge, i.e. dN = 0\n dB = 1;\n if(rnd_num < p_min_ins) { // accept bond insertion\n bonds[bidx] *=-1;\n activeEdges++;\n }\n else {\n if(rnd_num < p_max_ins) {\n dN = ( connected(edge[0],edge[1]) ?0 : -1);\n if(rnd_num < rcWeights[dB == -1? dN : 2-dN]) {\n bonds[bidx]*=-1;\n activeEdges++;\n }\n }\n\n }\n }\n }\n}\n/******************************************************************************\n *****************************************************************************/\nstatic inline void sweep_sbfs(void)\n{\n static __u32 bidx;\n static double rnd_num;\n __u32 i=0;\n \n for(;i<2*N ;++i) {\n bidx = gsl_rng_uniform_int(r,2*N);\n rnd_num = gsl_rng_uniform(r);\n Adjacent(bidx);\n if(bonds[bidx] == 1) { //edge is active hence delete it\n dB = -1;\n if(rnd_num < p_min_del) { // accept bond deletion\n bonds[bidx]*=-1;\n activeEdges--;\n }\n else {\n if(rnd_num < p_max_del) {\n bonds[bidx]*=-1;\n dN = (connected_s(edge[0],edge[1])? 0 : 1);\n if(rnd_num >= rcWeights[dB == -1? dN : 2-dN]) bonds[bidx]*=-1; // undo bond deletion\n else activeEdges--; // accept bond deletion\n }\n\n }\n\n }\n else {\t\n // Insert cedge. If adjacent vertices are already connected, the new \n // edge will be a non-tree edge, i.e. dN = 0\n dB = 1;\n if(rnd_num < p_min_ins) { // accept bond insertion\n bonds[bidx] *=-1;\n activeEdges++;\n }\n else {\n if(rnd_num < p_max_ins) {\n dN = ( connected_s(edge[0],edge[1]) ?0 : -1);\n if(rnd_num < rcWeights[dB == -1? dN : 2-dN]) {\n bonds[bidx]*=-1;\n activeEdges++;\n }\n }\n\n }\n }\n }\n}\n/******************************************************************************\n *****************************************************************************/\nstatic void extract_observables(__u32 i) {\n static __u32 j=0;\n static __u32 clust_cnt=0;\n static __u64 sum=0,sum_2;\n static __u32 maxc=0,chksum=0;\n num_bonds[i] = activeEdges;\n offset_1=0;\n for(j=0;j maxc) maxc = cs1;\n sum+=cs1*cs1;\n sum_2+=pow(cs1,4);\n chksum+=cs1;\n }\n\n }\n num_cluster[i] = clust_cnt;\n size_giant[i] = maxc;\n sec_cs_moment[i] = sum;\n four_cs_moment[i] = sum_2;\n maxc=clust_cnt=sum=sum_2=chksum=0;\n offset_1=3;\n offset_2=2;\n}\n/******************************************************************************\n *****************************************************************************/\nstatic void generateTimeSeries(void)\n{ \n \n __u32 i;\n if(setup==1) {\n for(i=0;i\n#include \n#include \n#include \"gsl_sf_expint.h\"\n\n#include \"error.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n/*\n Chebyshev expansions: based on SLATEC e1.f, W. Fullerton\n \n Series for AE11 on the interval -1.00000D-01 to 0.\n\t\t\t\t\twith weighted error 1.76E-17\n\t\t\t\t\t log weighted error 16.75\n\t\t\t significant figures required 15.70\n\t\t\t\t decimal places required 17.55\n\n\n Series for AE12 on the interval -2.50000D-01 to -1.00000D-01\n\t\t\t\t\twith weighted error 5.83E-17\n\t\t\t\t\t log weighted error 16.23\n\t\t\t significant figures required 15.76\n\t\t\t\t decimal places required 16.93\n\n\n Series for E11 on the interval -4.00000D+00 to -1.00000D+00\n\t\t\t\t\twith weighted error 1.08E-18\n\t\t\t\t\t log weighted error 17.97\n\t\t\t significant figures required 19.02\n\t\t\t\t decimal places required 18.61\n\n\n Series for E12 on the interval -1.00000D+00 to 1.00000D+00\n\t\t\t\t\twith weighted error 3.15E-18\n\t\t\t\t\t log weighted error 17.50\n\t\t\tapprox significant figures required 15.8\n\t\t\t\t decimal places required 18.10\n\n\n Series for AE13 on the interval 2.50000D-01 to 1.00000D+00\n\t\t\t\t\twith weighted error 2.34E-17\n\t\t\t\t\t log weighted error 16.63\n\t\t\t significant figures required 16.14\n\t\t\t\t decimal places required 17.33\n\n\n Series for AE14 on the interval 0.\t to 2.50000D-01\n\t\t\t\t\twith weighted error 5.41E-17\n\t\t\t\t\t log weighted error 16.27\n\t\t\t significant figures required 15.38\n\t\t\t\t decimal places required 16.97\n*/\n\nstatic double AE11_data[39] = {\n 0.121503239716065790,\n -0.065088778513550150,\n 0.004897651357459670,\n -0.000649237843027216,\n 0.000093840434587471,\n 0.000000420236380882,\n -0.000008113374735904,\n 0.000002804247688663,\n 0.000000056487164441,\n -0.000000344809174450,\n 0.000000058209273578,\n 0.000000038711426349,\n -0.000000012453235014,\n -0.000000005118504888,\n 0.000000002148771527,\n 0.000000000868459898,\n -0.000000000343650105,\n -0.000000000179796603,\n 0.000000000047442060,\n 0.000000000040423282,\n -0.000000000003543928,\n -0.000000000008853444,\n -0.000000000000960151,\n 0.000000000001692921,\n 0.000000000000607990,\n -0.000000000000224338,\n -0.000000000000200327,\n -0.000000000000006246,\n 0.000000000000045571,\n 0.000000000000016383,\n -0.000000000000005561,\n -0.000000000000006074,\n -0.000000000000000862,\n 0.000000000000001223,\n 0.000000000000000716,\n -0.000000000000000024,\n -0.000000000000000201,\n -0.000000000000000082,\n 0.000000000000000017\n};\nstatic cheb_series AE11_cs = {\n AE11_data,\n 38,\n -1, 1,\n 20\n};\n\nstatic double AE12_data[25] = {\n 0.582417495134726740,\n -0.158348850905782750,\n -0.006764275590323141,\n 0.005125843950185725,\n 0.000435232492169391,\n -0.000143613366305483,\n -0.000041801320556301,\n -0.000002713395758640,\n 0.000001151381913647,\n 0.000000420650022012,\n 0.000000066581901391,\n 0.000000000662143777,\n -0.000000002844104870,\n -0.000000000940724197,\n -0.000000000177476602,\n -0.000000000015830222,\n 0.000000000002905732,\n 0.000000000001769356,\n 0.000000000000492735,\n 0.000000000000093709,\n 0.000000000000010707,\n -0.000000000000000537,\n -0.000000000000000716,\n -0.000000000000000244,\n -0.000000000000000058\n};\nstatic cheb_series AE12_cs = {\n AE12_data,\n 24,\n -1, 1,\n 15\n};\n\nstatic double E11_data[19] = {\n -16.11346165557149402600,\n 7.79407277874268027690,\n -1.95540581886314195070,\n 0.37337293866277945612,\n -0.05692503191092901938,\n 0.00721107776966009185,\n -0.00078104901449841593,\n 0.00007388093356262168,\n -0.00000620286187580820,\n 0.00000046816002303176,\n -0.00000003209288853329,\n 0.00000000201519974874,\n -0.00000000011673686816,\n 0.00000000000627627066,\n -0.00000000000031481541,\n 0.00000000000001479904,\n -0.00000000000000065457,\n 0.00000000000000002733,\n -0.00000000000000000108\n};\nstatic cheb_series E11_cs = {\n E11_data,\n 18,\n -1, 1,\n 13\n};\n\nstatic double E12_data[16] = {\n -0.03739021479220279500,\n 0.04272398606220957700,\n -0.13031820798497005440,\n 0.01441912402469889073,\n -0.00134617078051068022,\n 0.00010731029253063780,\n -0.00000742999951611943,\n 0.00000045377325690753,\n -0.00000002476417211390,\n 0.00000000122076581374,\n -0.00000000005485141480,\n 0.00000000000226362142,\n -0.00000000000008635897,\n 0.00000000000000306291,\n -0.00000000000000010148,\n 0.00000000000000000315\n};\nstatic cheb_series E12_cs = {\n E12_data,\n 15,\n -1, 1,\n 10\n};\n\nstatic double AE13_data[25] = {\n -0.605773246640603460,\n -0.112535243483660900,\n 0.013432266247902779,\n -0.001926845187381145,\n 0.000309118337720603,\n -0.000053564132129618,\n 0.000009827812880247,\n -0.000001885368984916,\n 0.000000374943193568,\n -0.000000076823455870,\n 0.000000016143270567,\n -0.000000003466802211,\n 0.000000000758754209,\n -0.000000000168864333,\n 0.000000000038145706,\n -0.000000000008733026,\n 0.000000000002023672,\n -0.000000000000474132,\n 0.000000000000112211,\n -0.000000000000026804,\n 0.000000000000006457,\n -0.000000000000001568,\n 0.000000000000000383,\n -0.000000000000000094,\n 0.000000000000000023\n};\nstatic cheb_series AE13_cs = {\n AE13_data,\n 24,\n -1, 1,\n 15\n};\n\nstatic double AE14_data[26] = {\n -0.18929180007530170,\n -0.08648117855259871,\n 0.00722410154374659,\n -0.00080975594575573,\n 0.00010999134432661,\n -0.00001717332998937,\n 0.00000298562751447,\n -0.00000056596491457,\n 0.00000011526808397,\n -0.00000002495030440,\n 0.00000000569232420,\n -0.00000000135995766,\n 0.00000000033846628,\n -0.00000000008737853,\n 0.00000000002331588,\n -0.00000000000641148,\n 0.00000000000181224,\n -0.00000000000052538,\n 0.00000000000015592,\n -0.00000000000004729,\n 0.00000000000001463,\n -0.00000000000000461,\n 0.00000000000000148,\n -0.00000000000000048,\n 0.00000000000000016,\n -0.00000000000000005\n};\nstatic cheb_series AE14_cs = {\n AE14_data,\n 25,\n -1, 1,\n 13\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\n\nint gsl_sf_expint_E1_e(const double x, gsl_sf_result * result)\n{\n const double xmaxt = -GSL_LOG_DBL_MIN; /* XMAXT = -LOG (R1MACH(1)) */\n const double xmax = xmaxt - log(xmaxt); /* XMAX = XMAXT - LOG(XMAXT) */\n\n /* CHECK_POINTER(result) */\n\n if(x < -xmax) {\n OVERFLOW_ERROR(result);\n }\n else if(x <= -10.0) {\n const double s = exp(-x)/x;\n gsl_sf_result result_c;\n cheb_eval_e(&AE11_cs, 20.0/x+1.0, &result_c);\n result->val = s * (1.0 + result_c.val);\n result->err = s * result_c.err;\n result->err += 2.0 * GSL_DBL_EPSILON * (fabs(x) + 1.0) * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(x <= -4.0) {\n const double s = exp(-x)/x;\n gsl_sf_result result_c;\n cheb_eval_e(&AE12_cs, (40.0/x+7.0)/3.0, &result_c);\n result->val = s * (1.0 + result_c.val);\n result->err = s * result_c.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(x <= -1.0) {\n const double ln_term = -log(fabs(x));\n gsl_sf_result result_c;\n cheb_eval_e(&E11_cs, (2.0*x+5.0)/3.0, &result_c);\n result->val = ln_term + result_c.val;\n result->err = result_c.err + GSL_DBL_EPSILON * fabs(ln_term);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(x == 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x <= 1.0) {\n const double ln_term = -log(fabs(x));\n gsl_sf_result result_c;\n cheb_eval_e(&E12_cs, x, &result_c);\n result->val = ln_term - 0.6875 + x + result_c.val;\n result->err = result_c.err + GSL_DBL_EPSILON * fabs(ln_term);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(x <= 4.0) {\n const double s = exp(-x)/x;\n gsl_sf_result result_c;\n cheb_eval_e(&AE13_cs, (8.0/x-5.0)/3.0, &result_c);\n result->val = s * (1.0 + result_c.val);\n result->err = s * result_c.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(x <= xmax) {\n const double s = exp(-x)/x;\n gsl_sf_result result_c;\n cheb_eval_e(&AE14_cs, 8.0/x-1.0, &result_c);\n result->val = s * (1.0 + result_c.val);\n result->err = s * (GSL_DBL_EPSILON + result_c.err);\n result->err += 2.0 * (x + 1.0) * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n UNDERFLOW_ERROR(result);\n }\n}\n\n\nint gsl_sf_expint_E2_e(const double x, gsl_sf_result * result)\n{\n const double xmaxt = -GSL_LOG_DBL_MIN;\n const double xmax = xmaxt - log(xmaxt);\n\n /* CHECK_POINTER(result) */\n\n if(x < -xmax) {\n OVERFLOW_ERROR(result);\n }\n else if(x < 100.0) {\n const double ex = exp(-x);\n gsl_sf_result result_E1;\n int stat_E1 = gsl_sf_expint_E1_e(x, &result_E1);\n result->val = ex - x*result_E1.val;\n result->err = fabs(x) * (GSL_DBL_EPSILON*ex + result_E1.err);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_E1;\n }\n else if(x < xmax) {\n const double c1 = -2.0;\n const double c2 = 6.0;\n const double c3 = -24.0;\n const double c4 = 120.0;\n const double c5 = -720.0;\n const double c6 = 5040.0;\n const double c7 = -40320.0;\n const double c8 = 362880.0;\n const double c9 = -3628800.0;\n const double c10 = 39916800.0;\n const double c11 = -479001600.0;\n const double c12 = 6227020800.0;\n const double c13 = -87178291200.0;\n const double y = 1.0/x;\n const double sum6 = c6+y*(c7+y*(c8+y*(c9+y*(c10+y*(c11+y*(c12+y*c13))))));\n const double sum = y*(c1+y*(c2+y*(c3+y*(c4+y*(c5+y*sum6)))));\n result->val = exp(-x) * (1.0 + sum)/x;\n result->err = 2.0 * (x + 1.0) * GSL_DBL_EPSILON * result->val;\n return GSL_SUCCESS;\n }\n else {\n UNDERFLOW_ERROR(result);\n }\n}\n\n\nint gsl_sf_expint_Ei_e(const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n {\n int status = gsl_sf_expint_E1_e(-x, result);\n result->val = -result->val;\n return status;\n }\n}\n\n#if 0\nstatic double recurse_En(int n, double x, double E1)\n{\n int i;\n double En = E1;\n double ex = exp(-x);\n for(i=2; i<=n; i++) {\n En = 1./(i-1) * (ex - x * En);\n }\n return En;\n}\n#endif\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_expint_E1(const double x)\n{\n EVAL_RESULT(gsl_sf_expint_E1_e(x, &result));\n}\n\ndouble gsl_sf_expint_E2(const double x)\n{\n EVAL_RESULT(gsl_sf_expint_E2_e(x, &result));\n}\n\ndouble gsl_sf_expint_Ei(const double x)\n{\n EVAL_RESULT(gsl_sf_expint_Ei_e(x, &result));\n}\n", "meta": {"hexsha": "fa53aa745d48620a3da94e86dc470a4d5dc8db2c", "size": 11466, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/expint.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/expint.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/expint.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.5367483296, "max_line_length": 79, "alphanum_fraction": 0.6663178092, "num_tokens": 4288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.4089412186659735}} {"text": "/****************************************************************************\n * *\n * Copyright (C) 2001 ~ 2016 Neutrino International Inc. *\n * *\n * Author : Brian Lin , Skype: wolfram_lin *\n * *\n * QtFFT acts as an interface between Qt and FFT libraries. *\n * Please keep QtFFT as simple as possible. *\n * *\n * Qt Version : 5.4.1 *\n * CIOS Version : 1.6.0 *\n * *\n ****************************************************************************/\n\n#ifndef QT_FFT_H\n#define QT_FFT_H\n\n#include \n#include \n#include \n#ifndef QT_STATIC\n#include \n#endif\n\n#include \n\n#ifdef QT_QTGMP_LIB\n#include \n#endif\n\n#ifdef QT_QTGSL_LIB\n#include \n#endif\n\n#ifdef QT_QTCUDA_LIB\n#include \n#endif\n\nextern \"C\" {\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n}\n\nQT_BEGIN_NAMESPACE\n\n#ifndef QT_STATIC\n# if defined(QT_BUILD_QTFFT_LIB)\n# define Q_FFT_EXPORT Q_DECL_EXPORT\n# else\n# define Q_FFT_EXPORT Q_DECL_IMPORT\n# endif\n#else\n# define Q_FFT_EXPORT\n#endif\n\nnamespace N\n{\n\nclass Q_FFT_EXPORT Wavelet ;\nclass Q_FFT_EXPORT Hankel ;\nclass Q_FFT_EXPORT AbstractFFT ;\nclass Q_FFT_EXPORT CooleyFFT ;\nclass Q_FFT_EXPORT KissFFT ;\nclass Q_FFT_EXPORT GSLFFT ;\nclass Q_FFT_EXPORT FFTW ;\nclass Q_FFT_EXPORT AccelerateFFT ;\n\n\nclass Q_FFT_EXPORT Wavelet\n{\n public:\n\n gsl_wavelet * wavelet ;\n gsl_wavelet_workspace * work ;\n gsl_wavelet_direction direction ;\n\n explicit Wavelet (void) ;\n virtual ~Wavelet (void) ;\n\n bool allocate (const gsl_wavelet_type * T,size_t k) ;\n bool workspace (size_t n) ;\n QString Name (void) ;\n\n int Transform (double * data,size_t stride,size_t n) ;\n int TransformForward (double * data,size_t stride,size_t n) ;\n int TransformInverse (double * data,size_t stride,size_t n) ;\n int Transform2d (double * data,size_t tda,size_t size1,size_t size2) ;\n int Transform2dForward (double * data,size_t tda,size_t size1,size_t size2) ;\n int Transform2dInverse (double * data,size_t tda,size_t size1,size_t size2) ;\n int TransformMatrix (gsl_matrix * m) ;\n int TransformMatrixForward (gsl_matrix * m) ;\n int TransformMatrixInverse (gsl_matrix * m) ;\n int nsTransform (double * data,size_t tda,size_t size1,size_t size2) ;\n int nsTransformForward (double * data,size_t tda,size_t size1,size_t size2) ;\n int nsTransformInverse (double * data,size_t tda,size_t size1,size_t size2) ;\n int nsTransformMatrix (gsl_matrix * m) ;\n int nsTransformMatrixForward (gsl_matrix * m) ;\n int nsTransformMatrixInverse (gsl_matrix * m) ;\n\n protected:\n\n private:\n\n};\n\nclass Q_FFT_EXPORT Hankel\n{\n public:\n\n gsl_dht * hankel ;\n\n explicit Hankel (void) ;\n explicit Hankel (int size) ;\n explicit Hankel (int size,double nu, double xmax) ;\n Hankel (const Hankel & hankel) ;\n virtual ~Hankel (void) ;\n\n bool Allocate (int size) ;\n bool New (int size,double nu, double xmax) ;\n int Initialize (double nu,double xmax) ;\n int Apply (double * In,double * Out) ;\n double x (int n) ;\n double k (int n) ;\n\n protected:\n\n private:\n\n};\n\nclass Q_FFT_EXPORT AbstractFFT\n{\n public:\n\n typedef enum {\n fftForward = 0 ,\n fftBackward = 1 }\n TransformDirection ;\n\n TransformDirection direction ;\n Cpp::ValueTypes vType ;\n int sourceType ; // 0 - Undecided , 1 - Real , 2 - Complex\n int targetType ; // 0 - Undecided , 1 - Real , 2 - Complex\n int dimension ;\n\n explicit AbstractFFT (void);\n virtual ~AbstractFFT (void);\n\n virtual int type (void) const = 0 ;\n virtual bool isSupported (Cpp::ValueTypes type,int dimension) const = 0 ;\n virtual int AllocateSource (CUIDs elements,QByteArray & Source) = 0 ;\n virtual int AllocateTarget (CUIDs elements,QByteArray & Target) = 0 ;\n virtual bool Prepare (CUIDs elements ,\n VarArgs & Paraments ,\n QByteArray & Source ,\n QByteArray & Target ) = 0 ;\n virtual void Execution (void) = 0 ;\n\n protected:\n\n private:\n\n};\n\nclass Q_FFT_EXPORT CooleyFFT : public AbstractFFT\n{\n public:\n\n explicit CooleyFFT (void) ;\n virtual ~CooleyFFT (void) ;\n\n virtual int type (void) const ;\n virtual bool isSupported (Cpp::ValueTypes T,int dimension) const ;\n virtual int AllocateSource (CUIDs elements,QByteArray & Source) ;\n virtual int AllocateTarget (CUIDs elements,QByteArray & Target) ;\n virtual bool Prepare (CUIDs elements ,\n VarArgs & Paraments ,\n QByteArray & Source ,\n QByteArray & Target ) ;\n virtual void Execution (void) ;\n\n protected:\n\n private:\n\n};\n\nclass Q_FFT_EXPORT KissFFT : public AbstractFFT\n{\n public:\n\n explicit KissFFT (void) ;\n virtual ~KissFFT (void) ;\n\n virtual int type (void) const ;\n virtual bool isSupported (Cpp::ValueTypes T,int dimension) const ;\n virtual int AllocateSource (CUIDs elements,QByteArray & Source) ;\n virtual int AllocateTarget (CUIDs elements,QByteArray & Target) ;\n virtual bool Prepare (CUIDs elements ,\n VarArgs & Paraments ,\n QByteArray & Source ,\n QByteArray & Target ) ;\n virtual void Execution (void) ;\n\n protected:\n\n private:\n\n};\n\nclass Q_FFT_EXPORT GSLFFT : public AbstractFFT\n{\n public:\n\n explicit GSLFFT (void) ;\n virtual ~GSLFFT (void) ;\n\n virtual int type (void) const ;\n virtual bool isSupported (Cpp::ValueTypes T,int dimension) const ;\n virtual int AllocateSource (CUIDs elements,QByteArray & Source) ;\n virtual int AllocateTarget (CUIDs elements,QByteArray & Target) ;\n virtual bool Prepare (CUIDs elements ,\n VarArgs & Paraments ,\n QByteArray & Source ,\n QByteArray & Target ) ;\n virtual void Execution (void) ;\n\n protected:\n\n private:\n\n};\n\nclass Q_FFT_EXPORT FFTW : public AbstractFFT\n{\n public:\n\n explicit FFTW (void) ;\n virtual ~FFTW (void) ;\n\n virtual int type (void) const ;\n virtual bool isSupported (Cpp::ValueTypes T,int dimension) const ;\n virtual int AllocateSource (CUIDs elements,QByteArray & Source) ;\n virtual int AllocateTarget (CUIDs elements,QByteArray & Target) ;\n virtual bool Prepare (CUIDs elements ,\n VarArgs & Paraments ,\n QByteArray & Source ,\n QByteArray & Target ) ;\n virtual void Execution (void) ;\n\n void Cleanup (void);\n\n fftw_complex * array (int size);\n fftw_complex * fromByteArray (int & size,QByteArray & Array);\n QByteArray toByteArray (fftw_complex * complex,int size);\n void Execute (const fftw_plan plan);\n void Destroy (fftw_plan plan);\n\n fftw_plan Frequency (int N,double * data,fftw_complex * dout,unsigned int flags = FFTW_MEASURE) ;\n void Retrieve (int component,int index,int length,double * data,fftw_complex * dout) ;\n\n void Execute (const fftwf_plan plan);\n void Destroy (fftwf_plan plan);\n\n #ifndef DISABLE_FFTW_LDOUBLE\n void Execute (const fftwl_plan plan);\n void Destroy (fftwl_plan plan);\n #endif\n\n protected:\n\n fftw_plan fftplan ;\n fftwf_plan fftfplan ;\n #ifndef DISABLE_FFTW_LDOUBLE\n fftwl_plan fftlplan ;\n #endif\n\n private:\n\n int fftSize (int fft,int length) ;\n int fftSize (int fft,CUIDs elements) ;\n\n};\n\nclass Q_FFT_EXPORT AccelerateFFT : public AbstractFFT\n{ // Apple iPhone OS Accelerate Framework\n public:\n\n explicit AccelerateFFT (void) ;\n virtual ~AccelerateFFT (void) ;\n\n virtual int type (void) const ;\n virtual bool isSupported (Cpp::ValueTypes T,int dimension) const ;\n virtual int AllocateSource (CUIDs elements,QByteArray & Source) ;\n virtual int AllocateTarget (CUIDs elements,QByteArray & Target) ;\n virtual bool Prepare (CUIDs elements ,\n VarArgs & Paraments ,\n QByteArray & Source ,\n QByteArray & Target ) ;\n virtual void Execution (void) ;\n\n protected:\n\n private:\n\n};\n\n}\n\nQT_END_NAMESPACE\n\nQ_DECLARE_METATYPE(N::Wavelet)\nQ_DECLARE_METATYPE(N::Hankel)\nQ_DECLARE_METATYPE(N::CooleyFFT)\nQ_DECLARE_METATYPE(N::KissFFT)\nQ_DECLARE_METATYPE(N::GSLFFT)\nQ_DECLARE_METATYPE(N::FFTW)\nQ_DECLARE_METATYPE(N::AccelerateFFT)\n\nQ_DECLARE_INTERFACE(N::AbstractFFT , \"com.neutrino.math.fft\" )\n\n#endif\n", "meta": {"hexsha": "d0ce83806b61aaf63d8e15bb19385f557de02e67", "size": 10351, "ext": "h", "lang": "C", "max_stars_repo_path": "include/QtFFT/qtfft.h", "max_stars_repo_name": "Vladimir-Lin/QtFFT", "max_stars_repo_head_hexsha": "add93f193c2fcfbd56df8e360cfee6d7ccab6cef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/QtFFT/qtfft.h", "max_issues_repo_name": "Vladimir-Lin/QtFFT", "max_issues_repo_head_hexsha": "add93f193c2fcfbd56df8e360cfee6d7ccab6cef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/QtFFT/qtfft.h", "max_forks_repo_name": "Vladimir-Lin/QtFFT", "max_forks_repo_head_hexsha": "add93f193c2fcfbd56df8e360cfee6d7ccab6cef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0840840841, "max_line_length": 111, "alphanum_fraction": 0.5498985605, "num_tokens": 2343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4087324291821003}} {"text": "/* linalg/trimult.c\n *\n * Copyright (C) 2019 Patrick Alken\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the\n * Free Software Foundation; either version 3, or (at your option) any\n * later version.\n *\n * This source is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * This module contains code to compute L^T L where L is a lower triangular matrix\n */\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"recurse.h\"\n\nstatic int triangular_multsymm_L2(CBLAS_UPLO_t Uplo, gsl_matrix * T);\nstatic int triangular_multsymm_L3(CBLAS_UPLO_t Uplo, gsl_matrix * T);\nstatic int triangular_mult_L2(CBLAS_UPLO_t Uplo, gsl_matrix * A);\nstatic int triangular_mult_L3(CBLAS_UPLO_t Uplo, gsl_matrix * A);\n\nint\ngsl_linalg_tri_LTL(gsl_matrix * L)\n{\n return triangular_multsymm_L3(CblasLower, L);\n}\n\nint\ngsl_linalg_tri_UL(gsl_matrix * LU)\n{\n return triangular_mult_L3(CblasUpper, LU);\n}\n\n/*\ntriangular_multsymm_L2()\n Compute L^T L or U U^T\n\nInputs: Uplo - CblasUpper or CblasLower\n T - on output the upper (or lower) part of T\n is replaced by L^T L or U U^T\n\nReturn: success/error\n\nNotes:\n1) Based on LAPACK routine DLAUU2 using Level 2 BLAS\n*/\n\nstatic int\ntriangular_multsymm_L2(CBLAS_UPLO_t Uplo, gsl_matrix * T)\n{\n const size_t N = T->size1;\n\n if (N != T->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else\n {\n gsl_vector_view v1, v2;\n size_t i;\n\n if (Uplo == CblasUpper)\n {\n }\n else\n {\n for (i = 0; i < N; ++i)\n {\n double Tii = gsl_matrix_get(T, i, i);\n\n if (i < N - 1)\n {\n double tmp;\n\n v1 = gsl_matrix_subcolumn(T, i, i, N - i);\n gsl_blas_ddot(&v1.vector, &v1.vector, &tmp);\n gsl_matrix_set(T, i, i, tmp);\n\n if (i > 0)\n {\n gsl_matrix_view m = gsl_matrix_submatrix(T, i + 1, 0, N - i - 1, i);\n\n v1 = gsl_matrix_subcolumn(T, i, i + 1, N - i - 1);\n v2 = gsl_matrix_subrow(T, i, 0, i);\n\n gsl_blas_dgemv(CblasTrans, 1.0, &m.matrix, &v1.vector, Tii, &v2.vector);\n }\n }\n else\n {\n v1 = gsl_matrix_row(T, N - 1);\n gsl_blas_dscal(Tii, &v1.vector);\n }\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ntriangular_multsymm_L3()\n Compute L^T L or U U^T\n\nInputs: Uplo - CblasUpper or CblasLower\n T - on output the upper (or lower) part of T\n is replaced by L^T L or U U^T\n\nReturn: success/error\n\nNotes:\n1) Based on ReLAPACK routine DLAUUM using Level 3 BLAS\n*/\n\nstatic int\ntriangular_multsymm_L3(CBLAS_UPLO_t Uplo, gsl_matrix * T)\n{\n const size_t N = T->size1;\n\n if (N != T->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else if (N <= CROSSOVER_TRIMULT)\n {\n return triangular_multsymm_L2(Uplo, T);\n }\n else\n {\n /* partition matrix:\n *\n * T11 T12\n * T21 T22\n *\n * where T11 is N1-by-N1\n */\n int status;\n const size_t N1 = GSL_LINALG_SPLIT(N);\n const size_t N2 = N - N1;\n gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1);\n gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2);\n gsl_matrix_view T21 = gsl_matrix_submatrix(T, N1, 0, N2, N1);\n gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2);\n\n /* recursion on T11 */\n status = triangular_multsymm_L3(Uplo, &T11.matrix);\n if (status)\n return status;\n\n if (Uplo == CblasLower)\n {\n /* T11 += T21^T T21 */\n gsl_blas_dsyrk(Uplo, CblasTrans, 1.0, &T21.matrix, 1.0, &T11.matrix);\n\n /* T21 = T22^T * T21 */\n gsl_blas_dtrmm(CblasLeft, Uplo, CblasTrans, CblasNonUnit, 1.0, &T22.matrix, &T21.matrix);\n }\n else\n {\n /* T11 += T12 T12^T */\n gsl_blas_dsyrk(Uplo, CblasNoTrans, 1.0, &T12.matrix, 1.0, &T11.matrix);\n\n /* T12 = T12 * T22^T */\n gsl_blas_dtrmm(CblasRight, Uplo, CblasTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix);\n }\n\n /* recursion on T22 */\n status = triangular_multsymm_L3(Uplo, &T22.matrix);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ntriangular_mult_L2()\n Compute U L or L U\n\nInputs: Uplo - CblasUpper or CblasLower (for the first triangular factor)\n A - on input, matrix in LU format;\n on output, U L or L U\n\nReturn: success/error\n*/\n\nstatic int\ntriangular_mult_L2(CBLAS_UPLO_t Uplo, gsl_matrix * A)\n{\n const size_t N = A->size1;\n\n if (N != A->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else\n {\n size_t i;\n\n /* quick return */\n if (N == 1)\n return GSL_SUCCESS;\n\n if (Uplo == CblasUpper)\n {\n /* compute U * L and store in A */\n\n for (i = 0; i < N; ++i)\n {\n double * Aii = gsl_matrix_ptr(A, i, i);\n double Uii = *Aii;\n\n if (i < N - 1)\n {\n gsl_vector_view lb = gsl_matrix_subcolumn(A, i, i + 1, N - i - 1);\n gsl_vector_view ur = gsl_matrix_subrow(A, i, i + 1, N - i - 1);\n double tmp;\n\n gsl_blas_ddot(&lb.vector, &ur.vector, &tmp);\n *Aii += tmp;\n\n if (i > 0)\n {\n gsl_matrix_view U_TR = gsl_matrix_submatrix(A, 0, i + 1, i, N - i - 1);\n gsl_matrix_view L_BL = gsl_matrix_submatrix(A, i + 1, 0, N - i - 1, i);\n gsl_vector_view ut = gsl_matrix_subcolumn(A, i, 0, i);\n gsl_vector_view ll = gsl_matrix_subrow(A, i, 0, i);\n \n gsl_blas_dgemv(CblasTrans, 1.0, &L_BL.matrix, &ur.vector, Uii, &ll.vector);\n gsl_blas_dgemv(CblasNoTrans, 1.0, &U_TR.matrix, &lb.vector, 1.0, &ut.vector);\n }\n }\n else\n {\n gsl_vector_view v = gsl_matrix_subrow(A, N - 1, 0, N - 1);\n gsl_blas_dscal(Uii, &v.vector);\n }\n }\n }\n else\n {\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ntriangular_mult_L3()\n Compute U L or L U\n\nInputs: Uplo - CblasUpper or CblasLower (for the first triangular factor)\n A - on input, matrix in LU format;\n on output, U L or L U\n\nReturn: success/error\n*/\n\nstatic int\ntriangular_mult_L3(CBLAS_UPLO_t Uplo, gsl_matrix * A)\n{\n const size_t N = A->size1;\n\n if (N != A->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else if (N <= CROSSOVER_TRIMULT)\n {\n return triangular_mult_L2(Uplo, A);\n }\n else\n {\n /* partition matrix:\n *\n * A11 A12\n * A21 A22\n *\n * where A11 is N1-by-N1\n */\n int status;\n const size_t N1 = GSL_LINALG_SPLIT(N);\n const size_t N2 = N - N1;\n gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, N1, N1);\n gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, N1, N2);\n gsl_matrix_view A21 = gsl_matrix_submatrix(A, N1, 0, N2, N1);\n gsl_matrix_view A22 = gsl_matrix_submatrix(A, N1, N1, N2, N2);\n\n /* recursion on A11 */\n status = triangular_mult_L3(Uplo, &A11.matrix);\n if (status)\n return status;\n\n if (Uplo == CblasLower)\n {\n }\n else\n {\n /* form U * L */\n\n /* A11 += A12 A21 */\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &A12.matrix, &A21.matrix, 1.0, &A11.matrix);\n\n /* A12 = A12 * L22 */\n gsl_blas_dtrmm(CblasRight, CblasLower, CblasNoTrans, CblasUnit, 1.0, &A22.matrix, &A12.matrix);\n\n /* A21 = U22 * A21 */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &A22.matrix, &A21.matrix);\n }\n\n /* recursion on A22 */\n status = triangular_mult_L3(Uplo, &A22.matrix);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "006429728d59f4d2c76f654752c826be2460fcfc", "size": 8850, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/linalg/trimult.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/linalg/trimult.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/trimult.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.4179104478, "max_line_length": 107, "alphanum_fraction": 0.5540112994, "num_tokens": 2645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4085922251906215}} {"text": "/*\n This file is part of the Astrometry.net suite.\n Copyright 2006-2008 Dustin Lang, Keir Mierle and Sam Roweis.\n\n The Astrometry.net suite is free software; you can redistribute\n it and/or modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation, version 2.\n\n The Astrometry.net suite is distributed in the hope that it will be\n useful, but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with the Astrometry.net suite ; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n#ifndef AN_GSL_UTILS_H\n#define AN_GSL_UTILS_H\n\n#include \n#include \n\nvoid gslutils_use_error_system();\n\n/**\n Solves a least-squares matrix equation\n A X_i = B_i\n\n For NB pairs of X_i, B_i.\n\n NOTE: THIS DESTROYS A!\n\n A: MxN matrix\n B: array of NB x length-M vectors\n X: must be an array big enough to hold NB vectors.\n (they will be length-N).\n resids: if non-NULL, must be an array big enough to hold NB vectors\n (they will be length-M).\n\n The result vectors are freshly allocated and should be freed with gsl_vector_free().\n */\nint gslutils_solve_leastsquares(gsl_matrix* A, gsl_vector** B,\n gsl_vector** X, gsl_vector** resids,\n int NB);\n\n/**\n Same as above, but using varargs. There must be exactly 3 * NB additional\n arguments, in the order:\n\n B0, &X0, &resid0, B1, &X1, &resid1, ...\n\n ie, the types must be repeating triples of:\n \n gsl_vector* b, gsl_vector** x, gsl_vector** resid\n\n */\nint gslutils_solve_leastsquares_v(gsl_matrix* A, int NB, ...);\n\n// C = A B\nvoid gslutils_matrix_multiply(gsl_matrix* C, const gsl_matrix* A, const gsl_matrix* B);\n\nint gslutils_invert_3x3(const double* A, double* B);\n\n#endif\n", "meta": {"hexsha": "11d60a031e3e828f3134f56ae11d0ac9c8b1bfe7", "size": 2025, "ext": "h", "lang": "C", "max_stars_repo_path": "External/astrometry.net/astrometry/include/gslutils.h", "max_stars_repo_name": "simonct/CoreAstro", "max_stars_repo_head_hexsha": "eafd0aea314c427da616e1707a49aaeaf5ea6991", "max_stars_repo_licenses": ["OML"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-08-29T06:56:58.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-15T10:35:59.000Z", "max_issues_repo_path": "External/astrometry.net/astrometry/include/gslutils.h", "max_issues_repo_name": "simonct/CoreAstro", "max_issues_repo_head_hexsha": "eafd0aea314c427da616e1707a49aaeaf5ea6991", "max_issues_repo_licenses": ["OML"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "External/astrometry.net/astrometry/include/gslutils.h", "max_forks_repo_name": "simonct/CoreAstro", "max_forks_repo_head_hexsha": "eafd0aea314c427da616e1707a49aaeaf5ea6991", "max_forks_repo_licenses": ["OML"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.223880597, "max_line_length": 87, "alphanum_fraction": 0.7190123457, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4085284086640056}} {"text": "#include \n#include \n#include \n#include \n#include \n#include\"mpi.h\"\n\nconst double PI = 3.14159;\n\ndouble rz(double red);\n\nstruct galaxy {\n double x, y, z, d, w;\n};\n\nint main (int argc, char **argv) {\n\n FILE * DD;\n FILE * PP;\n FILE * RR;\n\n const int Nr = 150;\n const int Nm = 100;\n const double RMIN = 0.0;\n const double RMAX = 150.0;\n const double RSTEP = 1.0;\n const double MSTEP = 0.01;\n\n const int maxNgal = 40000000;\n\n int dummy;\n\n char DDname[400];\n char PPname[400];\n char RRname[400];\n \n int i;\n int bit;\n int bittot;\n\n int *n;\n\n sprintf(DDname,argv[1]);\n sprintf(RRname,argv[2]);\n sprintf(PPname,argv[3]);\n\n struct galaxy * gald;\n struct galaxy * galr;\n\n double * DRcount;\n double * DRcount_in_place;\n gald = (struct galaxy*)malloc(maxNgal*sizeof(struct galaxy));\n galr = (struct galaxy*)malloc(maxNgal*sizeof(struct galaxy));\n DRcount = (double*)calloc(Nr*Nm,sizeof(double));\n DRcount_in_place = (double*)calloc(Nr*Nm,sizeof(double));\n struct galaxy * galpd, * galpr;\n galpd = gald;\n galpr = galr;\n\n DD = fopen(DDname,\"r\");\n RR = fopen(RRname,\"r\");\n\n double ra, dec, red, dist;\n double dd;\n int Nd = 0;\n double weight;\n double ddummy;\n int indexFKP;\n double weightFKP;\n double weight1, weight2, weight3, weight4;\n char line [2000];\n\n int N = 0;\n double sumW = 0;\n double sumW_in_place = 0;\n\n for (int i = 0; i < 0; i ++) {\n fgets (line, 2000, DD);\n printf(\"%s\\n\", line);\n }\n while (fscanf(DD,\"%lf %lf %lf\\n\",&ra,&dec,&red) != EOF) {\n ra *= PI/180.0;\n dec *= PI/180.0;\n dist = rz(red);\n galpd->x = dist*cos(dec)*cos(ra);\n galpd->y = dist*cos(dec)*sin(ra);\n galpd->z = dist*sin(dec);\n galpd->d = dist;\n// galpd->w = weight1 * weight2;\n galpd++;\n Nd++;\n }\n fclose(DD);\n\n N = 0;\n for (int i = 0; i < 0; i ++) {\n fgets (line, 2000, RR);\n printf(\"%s\\n\", line);\n }\n while (fscanf(RR,\"%le %le %le\\n\",&ra,&dec,&red) != EOF) {\n ra *= PI/180.0;\n dec *= PI/180.0;\n dist = rz(red);\n galpr->x = dist*cos(dec)*cos(ra);\n galpr->y = dist*cos(dec)*sin(ra);\n galpr->z = dist*sin(dec);\n galpr->d = dist;\n// galpr->w = weight1 * weight2;\n galpr++;\n N++;\n }\n fclose(RR); \n\n MPI_Init (&argc, &argv);\n int numproc;\n int totproc;\n MPI_Comm_rank (MPI_COMM_WORLD, &numproc);\n MPI_Comm_size (MPI_COMM_WORLD, &totproc);\n \n n = (int *) calloc(totproc + 1, sizeof(int));\n n[0] = 1;\n for (i = 1; i < totproc; i++) {\n n[i] = (int)floor(double(N)/totproc*i);\n }\n n[totproc] = N;\n bit = n[numproc];\n bittot = n[numproc + 1];\n \n\n sprintf(PPname, \"%s.DR\",PPname);\n double mu;\n double d1, d2, d3;\n double x1, y1, z1, x2, y2, z2, gd1, gd2, w1, w2;\n double r2, rat;\n double xb, yb, zb, db2;\n double rr;\n galpd = gald;\n int j;\n\n for (i = 0; i < Nd; i++) {\n x1 = galpd->x; y1 = galpd->y; z1 = galpd->z; gd1 = galpd->d; //w1 = galpd->w;\n galpr = galr + bit;\n for (j = bit; j < bittot; j++) {\n x2 = galpr->x; y2 = galpr->y; z2 = galpr->z; gd2 = galpr->d; //w2 = galpr->w;\n //sumW += w1*w2;\n sumW += 1.0;\n d1 = x1 - x2;\n d2 = y1 - y2;\n d3 = z1 - z2;\n r2 = d1*d1 + d2*d2 + d3*d3;\n if (r2 > RMAX*RMAX || r2 < RMIN*RMIN) {\n\t galpr++;\n continue;\n }\n rat = gd1/gd2;\n xb = x1 + x2*rat;\n yb = y1 + y2*rat;\n zb = z1 + z2*rat;\n db2 = xb*xb + yb*yb + zb*zb;\n mu = fabs((xb*d1 + yb*d2 + zb*d3)/sqrt(r2)/sqrt(db2));\n rr = sqrt(r2);\n int binr = (int)((rr - RMIN)/RSTEP);\n int binm = (int)(mu/MSTEP);\n if (binr >= 0 && binm >= 0 && binr < Nr && binm < Nm){\n int ind = binr + Nr*binm;\n// DRcount[ind] += w1*w2;\n DRcount[ind] += 1.0;\n }\n galpr++;\n }\n galpd++;\n }\n free(gald);\n free(galr);\n free(n);\n\n MPI_Reduce(DRcount, DRcount_in_place, Nr*Nm, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);\n MPI_Reduce(&sumW, &sumW_in_place, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);\n printf(\"weighted number = %le %d\\n\", sumW, numproc);\n if (numproc == 0) {\n PP = fopen(PPname,\"w\");\n printf(\"%s\\n\", PPname);\n fprintf(PP,\"# weighted number: %lf\\n\",sumW_in_place);\n fprintf(PP,\"# RBINS: %d\\n\", Nr);\n fprintf(PP,\"# MBINS: %d\\n\", Nm);\n int k, l;\n for (k = 0; k < Nm; k++) {\n for (l = 0; l < Nr; l++) {\n fprintf(PP,\"%lf \",DRcount_in_place[k*Nr + l]);\n }\n fprintf(PP,\"\\n\");\n }\n fclose(PP);\n }\n\n free(DRcount);\n free(DRcount_in_place);\n\n MPI_Finalize ();\n\n return 0;\n}\n\ndouble f (double x, void * p) {\n double Om = 0.310;\n double ff = 2997.92458/sqrt(Om*(1.0 + x)*(1.0 + x)*(1.0 + x) + 1.0 - Om);\n return ff;\n}\n\ndouble rz (double red) {\n gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);\n double result, error;\n gsl_function F;\n F.function = &f;\n gsl_integration_qags(&F, 0, red, 0, 1e-7, 1000, w, &result, &error);\n gsl_integration_workspace_free (w);\n return result;\n}\n", "meta": {"hexsha": "073cde0737835744e8f1e0d067129369c3fc3f5b", "size": 4978, "ext": "c", "lang": "C", "max_stars_repo_path": "backup/DRpar.c", "max_stars_repo_name": "echaussidon/LSS", "max_stars_repo_head_hexsha": "205ce48a288acacbd41358e6d0215f4aff355049", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T14:52:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T08:54:18.000Z", "max_issues_repo_path": "backup/DRpar.c", "max_issues_repo_name": "echaussidon/LSS", "max_issues_repo_head_hexsha": "205ce48a288acacbd41358e6d0215f4aff355049", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2017-10-26T22:06:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:29:06.000Z", "max_forks_repo_path": "backup/DRpar.c", "max_forks_repo_name": "echaussidon/LSS", "max_forks_repo_head_hexsha": "205ce48a288acacbd41358e6d0215f4aff355049", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-10-26T17:30:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T09:24:38.000Z", "avg_line_length": 22.7305936073, "max_line_length": 87, "alphanum_fraction": 0.5510245078, "num_tokens": 1859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.4084384567450588}} {"text": "#ifndef FIT_GSL_H\n#define FIT_GSL_H\n\n#include \n#include \n\nclass Fit;\n\t\n//! Structure for fitting data\nstruct FitData {\n size_t n;// number of points to be fitted (size of X, Y and sigma arrays)\n size_t p;// number of fit parameters\n double * X;// the data to be fitted (abscissae) \n double * Y; // the data to be fitted (ordinates)\n double * sigma; // the weighting data\n Fit *fitter; //pointer to the fitter object (used only for the NonLinearFit class)\n};\n\nint expd3_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);\nint expd3_df (const gsl_vector * x, void *params, gsl_matrix * J);\nint expd3_f (const gsl_vector * x, void *params, gsl_vector * f);\ndouble expd3_d (const gsl_vector * x, void *params);\n\nint expd2_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);\nint expd2_df (const gsl_vector * x, void *params, gsl_matrix * J);\nint expd2_f (const gsl_vector * x, void *params, gsl_vector * f);\ndouble expd2_d (const gsl_vector * x, void *params);\n\nint exp_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);\nint exp_df (const gsl_vector * x, void *params, gsl_matrix * J);\nint exp_f (const gsl_vector * x, void *params, gsl_vector * f);\ndouble exp_d (const gsl_vector * x, void *params);\n\nint boltzmann_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);\nint boltzmann_df (const gsl_vector * x, void *params, gsl_matrix * J);\nint boltzmann_f (const gsl_vector * x, void *params, gsl_vector * f);\ndouble boltzmann_d (const gsl_vector * x, void *params);\n\r\nint logistic_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);\r\nint logistic_df (const gsl_vector * x, void *params, gsl_matrix * J);\r\nint logistic_f (const gsl_vector * x, void *params, gsl_vector * f);\r\ndouble logistic_d (const gsl_vector * x, void *params);\r\n\nint gauss_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);\nint gauss_df (const gsl_vector * x, void *params, gsl_matrix * J);\nint gauss_f (const gsl_vector * x, void *params,gsl_vector * f);\ndouble gauss_d (const gsl_vector * x, void *params);\n\nint gauss_multi_peak_f (const gsl_vector * x, void *params, gsl_vector * f);\ndouble gauss_multi_peak_d (const gsl_vector * x, void *params);\nint gauss_multi_peak_df (const gsl_vector * x, void *params, gsl_matrix * J);\nint gauss_multi_peak_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);\n\nint lorentz_multi_peak_f (const gsl_vector * x, void *params, gsl_vector * f);\ndouble lorentz_multi_peak_d (const gsl_vector * x, void *params);\nint lorentz_multi_peak_df (const gsl_vector * x, void *params, gsl_matrix * J);\nint lorentz_multi_peak_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);\n\nint user_f(const gsl_vector * x, void *params, gsl_vector * f);\ndouble user_d(const gsl_vector * x, void *params);\nint user_df(const gsl_vector * x, void *params,gsl_matrix * J);\nint user_fdf(const gsl_vector * x, void *params,gsl_vector * f, gsl_matrix * J);\n\n#endif\n", "meta": {"hexsha": "9d3b4d22a10251a0899bae7ce687812b26326f21", "size": 3057, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/qtiplot/qtiplot/src/analysis/fit_gsl.h", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "thirdparty/qtiplot/qtiplot/src/analysis/fit_gsl.h", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "thirdparty/qtiplot/qtiplot/src/analysis/fit_gsl.h", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 47.0307692308, "max_line_length": 96, "alphanum_fraction": 0.7252208047, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.40840531854916623}} {"text": "#include \n#include \n#include \n#include \n#include \"del2mat.h\"\n\n#define DEL2MAT_MULT ((void(*)(void))Del2Mat_mult)\n#define DEL2MAT_DIAG ((void(*)(void))Del2Mat_diag)\n\nint main(int argc,char **argv) \n{\n PetscInt n;\n PetscScalar h;\n Del2Mat shell;\n Mat A;\n Vec x,b; \n KSP ksp;\n PC pc;\n /* PETSc initialization */ \n PetscInitialize(&argc, &argv, PETSC_NULL, PETSC_NULL);\n /* number of nodes in each direction \n * excluding those at the boundary */\n n = 32;\n h = 1.0/(n+1); /* grid spacing */\n /* setup linear system (shell) matrix */\n MatCreate(PETSC_COMM_SELF, &A);\n MatSetSizes(A, n*n*n, n*n*n, n*n*n, n*n*n);\n MatSetType(A, MATSHELL);\n shell.N = n;\n PetscMalloc((n+2)*(n+2)*(n+2)*sizeof(PetscScalar),&shell.F);\n PetscMemzero(shell.F, (n+2)*(n+2)*(n+2)*sizeof(PetscScalar));\n MatShellSetContext(A, (void**)&shell);\n MatShellSetOperation(A, MATOP_MULT, DEL2MAT_MULT);\n MatShellSetOperation(A, MATOP_MULT_TRANSPOSE, DEL2MAT_MULT);\n MatShellSetOperation(A, MATOP_GET_DIAGONAL, DEL2MAT_DIAG);\n MatSetUp(A);\n /* setup linear system vectors */\n MatCreateVecs(A, &x, &b);\n VecSet(x, 0);\n VecSet(b, 1);\n /* setup Krylov linear solver */\n KSPCreate(PETSC_COMM_SELF, &ksp);\n KSPGetPC(ksp, &pc);\n KSPSetType(ksp, KSPCG); /* use conjugate gradients */\n PCSetType(pc, PCNONE); /* with no preconditioning */\n KSPSetFromOptions(ksp);\n /* iteratively solve linear system of equations A*x=b */\n KSPSetOperators(ksp,A,A);\n KSPSolve(ksp, b, x);\n /* scale solution vector to account for grid spacing */\n VecScale(x, h*h);\n /* free memory and destroy objects */\n PetscFree(shell.F);\n VecDestroy(&x);\n VecDestroy(&b);\n MatDestroy(&A);\n KSPDestroy(&ksp);\n /* finalize PETSc */ \n PetscFinalize();\n return 0;\n}\n", "meta": {"hexsha": "a6315f7a01e5ba75d59872409a9527cf5bad0ea9", "size": 1797, "ext": "c", "lang": "C", "max_stars_repo_path": "demo/poisson3d/poisson3d.c", "max_stars_repo_name": "zonca/petsc4py", "max_stars_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-11T05:00:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-11T05:00:53.000Z", "max_issues_repo_path": "demo/poisson3d/poisson3d.c", "max_issues_repo_name": "zonca/petsc4py", "max_issues_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/poisson3d/poisson3d.c", "max_forks_repo_name": "zonca/petsc4py", "max_forks_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9838709677, "max_line_length": 63, "alphanum_fraction": 0.6649972176, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4082400147782493}} {"text": "/* spmatrix/util.c\n * \n * Copyright (C) 2012, 2013, 2014, 2015, 2016, 2017, 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\ngsl_spmatrix_cumsum()\n\nCompute the cumulative sum:\n\np[j] = Sum_{k=0...j-1} c[k]\n\n0 <= j < n + 1\n\nAlternatively,\np[0] = 0\np[j] = p[j - 1] + c[j - 1]\n\nInputs: n - length of input array\n c - (input/output) array of size n + 1\n on input, contains the n values c[k]\n on output, contains the n + 1 values p[j]\n\nReturn: success or error\n*/\n\nvoid\ngsl_spmatrix_cumsum(const size_t n, int * c)\n{\n int sum = 0;\n size_t k;\n\n for (k = 0; k < n; ++k)\n {\n int ck = c[k];\n c[k] = sum;\n sum += ck;\n }\n\n c[n] = sum;\n}\n", "meta": {"hexsha": "6e5d02e8c6d930a8494513756d3bf2fe7d77f79c", "size": 1523, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/spmatrix/util.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/spmatrix/util.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/spmatrix/util.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.1746031746, "max_line_length": 81, "alphanum_fraction": 0.6559422193, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.4081157586041334}} {"text": "\n#include \n#include \n#include \n#include \n#include \n\n\n// author: Andrew Liew \n// copyright: Copyright 2018, BLOCK Research Group - ETH Zurich\n// license: MIT License\n// email: liew@arch.ethz.ch\n\n\nvoid drx_solver_c(\n double tol, // Tolerance value.\n int steps, // Maximum number of steps.\n int summary, // Print summary at end (1:yes or 0:no).\n int m, // Number of elements.\n int n, // Number of nodes.\n int *u, // Element start node.\n int *v, // Element end node.\n double *X, // Nodal co-ordinates.\n double *f0, // Initial edge forces.\n double *l0, // Initial edge lengths.\n double *k0, // Initial edge axial stiffnesses.\n int *ind_c, // Indices of compression only edges.\n int *ind_t, // Indices of tension only edges.\n int ind_c_n, // Length of ind_c.\n int ind_t_n, // Length of ind_t.\n double *B, // Constraint conditions Bx, By, Bz.\n double *P, // Nodal loads Px, Py, Pz.\n double *S, // Shear forces Sx, Sy, Sz.\n int *rows, // Rows of Ct.\n int *cols, // Columns of Ct.\n double *vals, // Values of Ct.\n int nv, // Length of rows/cols/vals.\n double *M, // Mass matrix.\n double factor, // Convergence factor.\n double *V, // Nodal velocities Vx, Vy, Vz.\n int *inds, // Indices of beam element start nodes.\n int *indi, // Indices of beam element intermediate nodes.\n int *indf, // Indices of beam element finish nodes beams.\n double *EIx, // Nodal EIx flexural stiffnesses.\n double *EIy, // Nodal EIy flexural stiffnesses.\n int beams, // Includes beams:1 or not:0.\n int nb) // Length of inds/indi/indf.\n\n {\n\n int a;\n int b;\n int c;\n int i;\n int j;\n int k;\n int nans[nb];\n int ts;\n\n double alpha;\n double f[m];\n double fx[m];\n double fy[m];\n double fz[m];\n double frx[n];\n double fry[n];\n double frz[n];\n double kappa;\n double l;\n double La;\n double Lb;\n double Lc;\n double LQn;\n double Lmu;\n double Lc1;\n double Lc2;\n double Mi;\n double Ms;\n double q;\n double res;\n double Rx;\n double Ry;\n double Rz;\n double Rn;\n double Uo;\n double Un;\n double xd;\n double yd;\n double zd;\n\n gsl_vector *Xs = gsl_vector_alloc(3);\n gsl_vector *Xi = gsl_vector_alloc(3);\n gsl_vector *Xf = gsl_vector_alloc(3);\n gsl_vector *Qa = gsl_vector_alloc(3);\n gsl_vector *Qb = gsl_vector_alloc(3);\n gsl_vector *Qc = gsl_vector_alloc(3);\n gsl_vector *Qn = gsl_vector_alloc(3);\n gsl_vector *mu = gsl_vector_alloc(3);\n gsl_vector *ex = gsl_vector_alloc(3);\n gsl_vector *ey = gsl_vector_alloc(3);\n gsl_vector *ez = gsl_vector_alloc(3);\n gsl_vector *K = gsl_vector_alloc(3);\n gsl_vector *Kx = gsl_vector_alloc(3);\n gsl_vector *Ky = gsl_vector_alloc(3);\n gsl_vector *Mc = gsl_vector_alloc(3);\n gsl_vector *ua = gsl_vector_alloc(3);\n gsl_vector *ub = gsl_vector_alloc(3);\n gsl_vector *c1 = gsl_vector_alloc(3);\n gsl_vector *c2 = gsl_vector_alloc(3);\n gsl_matrix *Sa = gsl_matrix_alloc(nb, 3);\n gsl_matrix *Sb = gsl_matrix_alloc(nb, 3);\n\n ts = 0;\n Uo = 0.;\n res = 1000. * tol;\n\n while (ts <= steps && res > tol)\n {\n #pragma omp parallel for private(i,j,k,xd,yd,zd,l,q)\n for (i = 0; i < m; i++)\n {\n j = 3 * v[i];\n k = 3 * u[i];\n xd = X[j + 0] - X[k + 0];\n yd = X[j + 1] - X[k + 1];\n zd = X[j + 2] - X[k + 2];\n l = gsl_hypot3(xd, yd, zd);\n f[i] = f0[i] + k0[i] * (l - l0[i]);\n q = f[i] / l;\n fx[i] = xd * q;\n fy[i] = yd * q;\n fz[i] = zd * q;\n }\n\n if (ind_t_n > 0)\n {\n #pragma omp parallel for private(i)\n for (i = 0; i < ind_t_n; i++)\n {\n if (f[i] < 0)\n {\n fx[i] = 0;\n fy[i] = 0;\n fz[i] = 0;\n }\n }\n }\n\n if (ind_c_n > 0)\n {\n #pragma omp parallel for private(i)\n for (i = 0; i < ind_c_n; i++)\n {\n if (f[i] > 0)\n {\n fx[i] = 0;\n fy[i] = 0;\n fz[i] = 0;\n }\n }\n }\n\n if (beams)\n {\n #pragma omp parallel for private(i,j)\n for (i = 0; i < n; i++)\n {\n j = i * 3;\n S[j + 0] = 0.;\n S[j + 1] = 0.;\n S[j + 2] = 0.;\n }\n\n for (i = 0; i < nb; i++)\n {\n a = inds[i] * 3;\n b = indi[i] * 3;\n c = indf[i] * 3;\n\n vector_from_pointer(&X[a], Xs);\n vector_from_pointer(&X[b], Xi);\n vector_from_pointer(&X[c], Xf);\n subtract_vectors(Xi, Xs, Qa);\n subtract_vectors(Xf, Xi, Qb);\n subtract_vectors(Xf, Xs, Qc);\n cross_vectors(Qa, Qb, Qn);\n subtract_vectors(Xf, Xs, mu);\n scale_vector(mu, 0.5);\n\n La = length_vector(Qa);\n Lb = length_vector(Qb);\n Lc = length_vector(Qc);\n LQn = length_vector(Qn);\n Lmu = length_vector(mu);\n alpha = acos((gsl_pow_2(La) + gsl_pow_2(Lb) - gsl_pow_2(Lc)) / (2. * La * Lb));\n kappa = 2. * sin(alpha) / Lc;\n\n gsl_vector_memcpy(ex, Qn);\n gsl_vector_memcpy(ez, mu);\n scale_vector(ex, 1./LQn);\n scale_vector(ez, 1./Lmu);\n cross_vectors(ez, ex, ey);\n gsl_vector_memcpy(K, Qn);\n scale_vector(K, kappa/LQn);\n gsl_vector_memcpy(Kx, ex);\n gsl_vector_memcpy(Ky, ey);\n scale_vector(Kx, dot_vectors(K, ex));\n scale_vector(Ky, dot_vectors(K, ey));\n scale_vector(Kx, EIx[i]);\n scale_vector(Ky, EIy[i]);\n add_vectors(Kx, Ky, Mc);\n cross_vectors(Mc, Qa, ua);\n cross_vectors(Mc, Qb, ub);\n normalize_vector(ua);\n normalize_vector(ub);\n cross_vectors(Qa, ua, c1);\n cross_vectors(Qb, ub, c2);\n\n Lc1 = length_vector(c1);\n Lc2 = length_vector(c2);\n Ms = length_vector_squared(Mc);\n scale_vector(ua, Ms * Lc1 / (La * dot_vectors(Mc, c1)));\n scale_vector(ub, Ms * Lc2 / (Lb * dot_vectors(Mc, c2)));\n\n for (j = 0; j < 3; j++)\n {\n gsl_matrix_set(Sa, i, j, gsl_vector_get(ua, j));\n gsl_matrix_set(Sb, i, j, gsl_vector_get(ub, j));\n }\n }\n\n #pragma omp parallel for private(i,j)\n for (i = 0; i < nb; i++)\n {\n nans[i] = 0;\n for (j = 0; j < 3; j++)\n {\n if (gsl_isnan(gsl_matrix_get(Sa, i, j)) || gsl_isnan(gsl_matrix_get(Sb, i, j)))\n {\n nans[i] = 1;\n break;\n }\n }\n }\n\n for (i = 0; i < nb; i++)\n {\n a = inds[i] * 3;\n b = indi[i] * 3;\n c = indf[i] * 3;\n\n if (nans[i] == 0)\n {\n for (j = 0; j < 3; j++)\n {\n S[a + j] += gsl_matrix_get(Sa, i, j);\n S[b + j] -= (gsl_matrix_get(Sa, i, j) + gsl_matrix_get(Sb, i, j));\n S[c + j] += gsl_matrix_get(Sb, i, j);\n }\n }\n }\n }\n\n #pragma omp parallel for private(i)\n for (i = 0; i < n; i++)\n {\n frx[i] = 0;\n fry[i] = 0;\n frz[i] = 0;\n }\n\n for (i = 0; i < nv; i++)\n {\n frx[rows[i]] += vals[i] * fx[cols[i]];\n fry[rows[i]] += vals[i] * fy[cols[i]];\n frz[rows[i]] += vals[i] * fz[cols[i]];\n }\n\n Un = 0.;\n Rn = 0.;\n\n #pragma omp parallel for private(i,j,Rx,Ry,Rz,Mi) reduction(+:Un,Rn)\n for (i = 0; i < n; i++)\n {\n j = 3 * i;\n Rx = (P[j + 0] - S[j + 0] - frx[i]) * B[j + 0];\n Ry = (P[j + 1] - S[j + 1] - fry[i]) * B[j + 1];\n Rz = (P[j + 2] - S[j + 2] - frz[i]) * B[j + 2];\n Rn += gsl_hypot3(Rx, Ry, Rz);\n Mi = M[i] * factor;\n V[j + 0] += Rx / Mi;\n V[j + 1] += Ry / Mi;\n V[j + 2] += Rz / Mi;\n Un += Mi * (gsl_pow_2(V[j + 0]) + gsl_pow_2(V[j + 1]) + gsl_pow_2(V[j + 2]));\n }\n\n if (Un < Uo)\n {\n #pragma omp parallel for private(i,j)\n for (i = 0; i < n; i++)\n {\n j = 3 * i;\n V[j + 0] = 0.;\n V[j + 1] = 0.;\n V[j + 2] = 0.;\n }\n }\n\n Uo = Un;\n\n #pragma omp parallel for private(i,j)\n for (i = 0; i < n; i++)\n {\n j = 3 * i;\n X[j + 0] += V[j + 0];\n X[j + 1] += V[j + 1];\n X[j + 2] += V[j + 2];\n }\n\n res = Rn / n;\n ts++;\n\n }\n\n if (summary == 1)\n {\n printf(\"Step: %i, Residual: %f\\n\", ts - 1, res);\n }\n\n}\n", "meta": {"hexsha": "5517b2b5d322a3f563d269614012cae2ff3c44fe", "size": 9712, "ext": "c", "lang": "C", "max_stars_repo_path": "src/compas_hpc/algorithms/drx_c.c", "max_stars_repo_name": "philianeles/compas", "max_stars_repo_head_hexsha": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/compas_hpc/algorithms/drx_c.c", "max_issues_repo_name": "philianeles/compas", "max_issues_repo_head_hexsha": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/compas_hpc/algorithms/drx_c.c", "max_forks_repo_name": "philianeles/compas", "max_forks_repo_head_hexsha": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3413897281, "max_line_length": 99, "alphanum_fraction": 0.4191721582, "num_tokens": 2851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.4074304275726247}} {"text": "#include \n#include \n#include \"getNextIterate.h\"\n\nvoid getNextIterate(const grid *grd, const bool eos_func, \n\t\t const wksp *w\n#if AA_M > 0 \n\t\t , const unsigned long itCount, const long nHist,\n\t\t double *residMax\n#endif\n\t\t ) {\n\n long i;\n#if AA_M > 0\n long j, mk, colptr;\n gsl_matrix *resid;\n gsl_vector *tau, *llsresid, *aa_wgts, *constraint;\n gsl_vector_view constraint_view;\n#endif\n\n#if AA_M == 0\n/* No Anderson acceleration, so just move temporaries into next\n guess */\n for (i=0; inr; i++) {\n w->colNew[i] = w->colTmp[i];\n w->presNew_g[i+1] = gsl_vector_get(w->presTmp_g, i+1);\n if (eos_func==1)\n w->eIntNew[i] = w->eIntTmp[i];\n }\n#else\n\n /* Anderson acceleration code */\n\n /* Set up pointers */\n mk = itCount < AA_M+1 ? itCount : AA_M+1;\n colptr = (itCount - 1) % (AA_M+1);\n\n /* Store the current guesses in the history array */\n for (i=0; inr; i++) {\n w->colHist[i + colptr*grd->nr] = w->colTmp[i];\n w->presHist[i + colptr*grd->nr] = gsl_vector_get(w->presTmp_g, i+1);\n if (eos_func)\n w->eIntHist[i + colptr*grd->nr] = w->eIntTmp[i];\n }\n\n /* Compute residuals and store them in the residual matrix */\n for (i=0; inr; i++) {\n w->colResid[i + colptr*grd->nr] = \n (w->colHist[i+colptr*grd->nr]-w->colNew[i]) / \n w->colHist[i+colptr*grd->nr];\n if (fabs(w->colResid[i + colptr*grd->nr]) > *residMax) {\n *residMax = fabs(w->colResid[i + colptr*grd->nr]);\n }\n w->presResid[i + colptr*grd->nr] = \n (w->presHist[i+colptr*grd->nr]-w->presNew_g[i+1]) / \n w->presHist[i+colptr*grd->nr];\n if (fabs(w->presResid[i + colptr*grd->nr]) > *residMax) {\n *residMax = fabs(w->presResid[i + colptr*grd->nr]);\n }\n if (eos_func) {\n w->eIntResid[i + colptr*grd->nr] = \n\t(w->eIntHist[i+colptr*grd->nr]-w->eIntNew[i]) / \n\tw->eIntHist[i+colptr*grd->nr];\n if (fabs(w->eIntResid[i + colptr*grd->nr]) > *residMax)\n\t*residMax = fabs(w->eIntResid[i + colptr*grd->nr]);\n }\n }\n\n /* If we're in the first iteration, set move temporaries to next\n guess */\n if (itCount == 1) {\n for (i=0; inr; i++) {\n w->colNew[i] = w->colHist[i+colptr*grd->nr];\n w->presNew_g[i+1] = w->presHist[i+colptr*grd->nr];\n if (eos_func)\n\tw->eIntNew[i] = w->eIntHist[i+colptr*grd->nr];\n }\n } else {\n /* On subsequent iterations, solve the linear least squares\n optimization problem to get a weighted sum of previous\n guesses for the new guess */\n\n /* Allocate workspace for this iteration */\n resid = gsl_matrix_alloc(nHist+1, mk);\n llsresid = gsl_vector_alloc(nHist+1);\n aa_wgts = gsl_vector_alloc(mk);\n if (nHist+1 < mk) {\n tau = gsl_vector_alloc(nHist+1);\n } else {\n tau = gsl_vector_alloc(mk);\n }\n\n /* Build matrix of residuals */\n for (i=0; inr; i++) {\n for (j=0; jcolResid[i+j*grd->nr]);\n\tgsl_matrix_set(resid, i+grd->nr, j, w->presResid[i+j*grd->nr]);\n\tif (eos_func)\n\t gsl_matrix_set(resid, i+2*grd->nr, j, w->eIntResid[i+j*grd->nr]);\n }\n }\n\n /* Set up constraints on coefficients */\n for (j=0; jconstraint, 0, nHist+1);\n constraint = &(constraint_view.vector);\n gsl_vector_set(constraint, nHist, 1e3*(*residMax));\n\n /* Solve linear least squares system by QR decomposition */\n gsl_linalg_QR_decomp(resid, tau);\n gsl_linalg_QR_lssolve(resid, tau, constraint, aa_wgts, llsresid);\n\n /* Build the new guess from the computed weights */\n for (i=0; inr; i++) {\n w->colNew[i] = \n\tgsl_vector_get(aa_wgts, 0)*w->colHist[i];\n w->presNew_g[i+1] = \n\tgsl_vector_get(aa_wgts, 0)*w->presHist[i];\n if (eos_func)\n\tw->eIntNew[i] = \n\t gsl_vector_get(aa_wgts, 0)*w->eIntHist[i];\n }\n for (j=1; jnr; i++) {\n\tw->colNew[i] += gsl_vector_get(aa_wgts, j) *\n\t w->colHist[i+j*grd->nr];\n\tw->presNew_g[i+1] += gsl_vector_get(aa_wgts, j) *\n\t w->presHist[i+j*grd->nr];\n\tif (eos_func)\n\t w->eIntNew[i] += gsl_vector_get(aa_wgts, j) *\n\t w->eIntHist[i+j*grd->nr];\n }\n }\n\n /* Free memory for this iteration */\n gsl_vector_free(llsresid);\n gsl_vector_free(tau);\n gsl_vector_free(aa_wgts);\n gsl_matrix_free(resid);\n }\n\n#endif\n /* End Anderson acceleration code */\n}\n", "meta": {"hexsha": "552c81278645c48c94814020d4a952e0610d3187", "size": 4423, "ext": "c", "lang": "C", "max_stars_repo_path": "src/amuse/community/vader/src/getNextIterate.c", "max_stars_repo_name": "franciscaconcha/amuse-vader", "max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/amuse/community/vader/src/getNextIterate.c", "max_issues_repo_name": "franciscaconcha/amuse-vader", "max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/amuse/community/vader/src/getNextIterate.c", "max_forks_repo_name": "franciscaconcha/amuse-vader", "max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z", "avg_line_length": 30.5034482759, "max_line_length": 76, "alphanum_fraction": 0.6036626724, "num_tokens": 1594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4070623659639855}} {"text": "/* filter/gaussian.c\n *\n * Gaussian smoothing filters\n * \n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n/* maximum derivative order allowed for Gaussian filter */\n#define GSL_FILTER_GAUSSIAN_MAX_ORDER 10\n\ntypedef double gaussian_type_t;\ntypedef double ringbuf_type_t;\n#include \"ringbuf.c\"\n\ntypedef struct\n{\n size_t n; /* window size */\n double * window; /* linear array with current window */\n ringbuf * rbuf; /* ring buffer storing current window */\n} gaussian_state_t;\n\nstatic size_t gaussian_size(const size_t n);\nstatic int gaussian_init(const size_t n, void * vstate);\nstatic int gaussian_insert(const gaussian_type_t x, void * vstate);\nstatic int gaussian_delete(void * vstate);\nstatic int gaussian_get(void * params, gaussian_type_t * result, const void * vstate);\n\nstatic const gsl_movstat_accum gaussian_accum_type;\n\n/*\ngsl_filter_gaussian_alloc()\n Allocate a workspace for Gaussian filtering.\n\nInputs: K - number of samples in window; if even, it is rounded up to\n the next odd, to have a symmetric window\n\nReturn: pointer to workspace\n*/\n\ngsl_filter_gaussian_workspace *\ngsl_filter_gaussian_alloc(const size_t K)\n{\n const size_t H = K / 2;\n gsl_filter_gaussian_workspace *w;\n size_t state_size;\n\n w = calloc(1, sizeof(gsl_filter_gaussian_workspace));\n if (w == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workspace\", GSL_ENOMEM);\n }\n\n w->K = 2 * H + 1;\n\n w->kernel = malloc(w->K * sizeof(double));\n if (w->kernel == 0)\n {\n gsl_filter_gaussian_free(w);\n GSL_ERROR_NULL (\"failed to allocate space for kernel\", GSL_ENOMEM);\n return NULL;\n }\n\n state_size = gaussian_size(w->K);\n\n w->movstat_workspace_p = gsl_movstat_alloc_with_size(state_size, H, H);\n if (!w->movstat_workspace_p)\n {\n gsl_filter_gaussian_free(w);\n GSL_ERROR_NULL (\"failed to allocate space for movstat workspace\", GSL_ENOMEM);\n }\n\n return w;\n}\n\nvoid\ngsl_filter_gaussian_free(gsl_filter_gaussian_workspace * w)\n{\n if (w->kernel)\n free(w->kernel);\n\n if (w->movstat_workspace_p)\n gsl_movstat_free(w->movstat_workspace_p);\n\n free(w);\n}\n\n/*\ngsl_filter_gaussian()\n Apply a Gaussian filter to an input vector:\n\nG_{sigma}(x) = exp [ -x^2 / (2 sigma^2) ]\n\nInputs: alpha - number of standard deviations to include in Gaussian kernel\n order - derivative order of Gaussian\n x - input vector, size n\n y - (output) filtered vector, size n\n w - workspace\n\nNotes:\n1) If alpha = 3, then the Gaussian kernel will be a Gaussian of +/- 3 standard deviations\n*/\n\nint\ngsl_filter_gaussian(const gsl_filter_end_t endtype, const double alpha, const size_t order, const gsl_vector * x,\n gsl_vector * y, gsl_filter_gaussian_workspace * w)\n{\n if (x->size != y->size)\n {\n GSL_ERROR(\"input and output vectors must have same length\", GSL_EBADLEN);\n }\n else if (alpha <= 0.0)\n {\n GSL_ERROR(\"alpha must be positive\", GSL_EDOM);\n }\n else\n {\n int status;\n gsl_vector_view kernel = gsl_vector_view_array(w->kernel, w->K);\n\n /* construct Gaussian kernel of length K */\n gsl_filter_gaussian_kernel(alpha, order, 1, &kernel.vector);\n\n status = gsl_movstat_apply_accum(endtype, x, &gaussian_accum_type, (void *) w->kernel, y,\n NULL, w->movstat_workspace_p);\n\n return status;\n }\n}\n\n/*\ngsl_filter_gaussian_kernel()\n Construct Gaussian kernel with given sigma and order\n\nInputs: alpha - number of standard deviations to include in window\n order - kernel order (0 = gaussian, 1 = first derivative, ...)\n normalize - normalize so sum(G) = 1\n kernel - (output) Gaussian kernel\n\nReturn: success/error\n\nNotes:\n1) If alpha = 3, then the output kernel will contain a Gaussian with +/- 3 standard deviations\n*/\n\nint\ngsl_filter_gaussian_kernel(const double alpha, const size_t order, const int normalize, gsl_vector * kernel)\n{\n const size_t N = kernel->size;\n\n if (alpha <= 0.0)\n {\n GSL_ERROR(\"alpha must be positive\", GSL_EDOM);\n }\n else if (order > GSL_FILTER_GAUSSIAN_MAX_ORDER)\n {\n GSL_ERROR(\"derivative order is too large\", GSL_EDOM);\n }\n else\n {\n const double half = 0.5 * (N - 1.0); /* (N - 1) / 2 */\n double sum = 0.0;\n size_t i;\n\n /* check for quick return */\n if (N == 1)\n {\n if (order == 0)\n gsl_vector_set(kernel, 0, 1.0);\n else\n gsl_vector_set(kernel, 0, 0.0);\n\n return GSL_SUCCESS;\n }\n\n for (i = 0; i < N; ++i)\n {\n double xi = ((double)i - half) / half;\n double yi = alpha * xi;\n double gi = exp(-0.5 * yi * yi);\n\n gsl_vector_set(kernel, i, gi);\n sum += gi;\n }\n\n /* normalize so sum(kernel) = 1 */\n if (normalize)\n gsl_vector_scale(kernel, 1.0 / sum);\n\n if (order > 0)\n {\n const double beta = -0.5 * alpha * alpha;\n double q[GSL_FILTER_GAUSSIAN_MAX_ORDER + 1];\n size_t k;\n\n /*\n * Need to calculate derivatives of the Gaussian window; define\n *\n * w(n) = C * exp [ p(n) ]\n *\n * p(n) = beta * n^2\n * beta = -1/2 * ( alpha / ((N-1)/2) )^2\n *\n * Then:\n *\n * d^k/dn^k w(n) = q_k(n) * w(n)\n *\n * where q_k(n) is a degree-k polynomial in n, which satisfies:\n *\n * q_k(n) = d/dn q_{k-1}(n) + q_{k-1}(n) * dp(n)/dn\n * q_0(n) = 1 / half^{order}\n */\n\n /* initialize q_0(n) = 1 / half^{order} */\n q[0] = 1.0 / gsl_pow_uint(half, order);\n for (i = 1; i <= GSL_FILTER_GAUSSIAN_MAX_ORDER; ++i)\n q[i] = 0.0;\n\n /* loop through derivative orders and calculate q_k(n) for k = 1,...,order */\n for (k = 1; k <= order; ++k)\n {\n double qm1 = q[0];\n\n q[0] = q[1];\n for (i = 1; i <= k; ++i)\n {\n double tmp = q[i];\n q[i] = (i + 1.0) * q[i + 1] + /* d/dn q_{k-1} */\n 2.0 * beta * qm1; /* q_{k-1}(n) p'(n) */\n qm1 = tmp;\n }\n }\n\n /* now set w(n) := q(n) * w(n) */\n for (i = 0; i < N; ++i)\n {\n double xi = ((double)i - half) / half;\n double qn = gsl_poly_eval(q, order + 1, xi);\n double *wn = gsl_vector_ptr(kernel, i);\n\n *wn *= qn;\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\nstatic size_t\ngaussian_size(const size_t n)\n{\n size_t size = 0;\n\n size += sizeof(gaussian_state_t);\n size += n * sizeof(gaussian_type_t);\n size += ringbuf_size(n);\n\n return size;\n}\n\nstatic int\ngaussian_init(const size_t n, void * vstate)\n{\n gaussian_state_t * state = (gaussian_state_t *) vstate;\n\n state->n = n;\n\n state->window = (gaussian_type_t *) ((unsigned char *) vstate + sizeof(gaussian_state_t));\n state->rbuf = (ringbuf *) ((unsigned char *) state->window + n * sizeof(gaussian_type_t));\n\n ringbuf_init(n, state->rbuf);\n\n return GSL_SUCCESS;\n}\n\nstatic int\ngaussian_insert(const gaussian_type_t x, void * vstate)\n{\n gaussian_state_t * state = (gaussian_state_t *) vstate;\n\n /* add new element to ring buffer */\n ringbuf_insert(x, state->rbuf);\n\n return GSL_SUCCESS;\n}\n\nstatic int\ngaussian_delete(void * vstate)\n{\n gaussian_state_t * state = (gaussian_state_t *) vstate;\n\n if (!ringbuf_is_empty(state->rbuf))\n ringbuf_pop_back(state->rbuf);\n\n return GSL_SUCCESS;\n}\n\nstatic int\ngaussian_get(void * params, gaussian_type_t * result, const void * vstate)\n{\n const gaussian_state_t * state = (const gaussian_state_t *) vstate;\n const double * kernel = (const double *) params;\n size_t n = ringbuf_copy(state->window, state->rbuf);\n double sum = 0.0;\n size_t i;\n\n for (i = 0; i < n; ++i)\n sum += state->window[i] * kernel[n - i - 1];\n\n *result = sum;\n\n return GSL_SUCCESS;\n}\n\nstatic const gsl_movstat_accum gaussian_accum_type =\n{\n gaussian_size,\n gaussian_init,\n gaussian_insert,\n gaussian_delete,\n gaussian_get\n};\n", "meta": {"hexsha": "d83c90e2c0bd2e284335e9c50251f21b80608f1f", "size": 9056, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/filter/gaussian.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/filter/gaussian.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/filter/gaussian.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.2492753623, "max_line_length": 113, "alphanum_fraction": 0.6073321555, "num_tokens": 2446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.40704759541687346}} {"text": "/*\n * Copyright (c) 2018, Aleksi Kurkela, Aleksas Mazeliauskas, Jean-Francois\n * Paquet, Soeren Schlichting and Derek Teaney\n * All rights reserved.\n *\n * KoMPoST is distributed under MIT license;\n * see the LICENSE file that should be present in the root\n * of the source distribution, or alternately available at:\n * https://github.com/KMPST/KoMPoST/\n */\n\n#include \n#include \n#ifndef M_HBARC\n#define M_HBARC 0.197326979\n#endif\n\nnamespace GreensFunctions {\n\nclass LowKArguments;\n\n//////////////////////////////////////////////////\n\nnamespace EnergyPerturbations {\n\nnamespace FreeStreaming {\nnamespace CoordinateSpace {\ndouble Gs(double dX, double dT);\ndouble Gv(double dX, double dT);\ndouble Gd(double dX, double dT);\ndouble Gr(double dX, double dT);\n}\n} // FreeStreaming\n\nnamespace KineticTheory {\nnamespace CoordinateSpace {\ndouble Gs(double dX, double dT, double ScalingVarOut);\ndouble Gv(double dX, double dT, double ScalingVarOut);\ndouble Gd(double dX, double dT, double ScalingVarOut);\ndouble Gr(double dX, double dT, double ScalingVarOut);\n}\n} // KineticTheory\n\nnamespace LowKLimit {\nnamespace CoordinateSpace {\ndouble Gs(double dX, double dT, const LowKArguments &in);\ndouble Gv(double dX, double dT, const LowKArguments &in);\ndouble Gd(double dX, double dT, const LowKArguments &in);\ndouble Gr(double dX, double dT, const LowKArguments &in);\n}\n} // LowKLimit\n\n} // EnergyPerturbations\n\n//////////////////////////////////////////////////\n\nnamespace MomentumPerturbations {\n\nnamespace FreeStreaming {\nnamespace CoordinateSpace {\ndouble Hv(double dX, double dT);\ndouble Hd(double dX, double dT);\ndouble Hr(double dX, double dT);\ndouble Htd(double dX, double dT);\ndouble Htm(double dX, double dT);\ndouble Htr(double dX, double dT);\n}\n} // FreeStreaming\n\nnamespace KineticTheory {\nnamespace CoordinateSpace {\ndouble Hv(double dX, double dT, double ScalingVarOut);\ndouble Hd(double dX, double dT, double ScalingVarOut);\ndouble Hr(double dX, double dT, double ScalingVarOut);\ndouble Htd(double dX, double dT, double ScalingVarOut);\ndouble Htm(double dX, double dT, double ScalingVarOut);\ndouble Htr(double dX, double dT, double ScalingVarOut);\n}\n} // Kinetic Theory\n\n} // MomentumPerturbations\n\n//////////////////////////////////////////////////\n\nvoid Setup(double Sigma, int NumberOfPoints, int ENERGY_PERTURBATIONS,\n int MOMENTUM_PERTURBATIONS);\n\nvoid Output(int ENERGY_PERTURBATIONS, int MOMENTUM_PERTURBATIONS);\n\nclass LowKArguments {\n\n // private:\npublic:\n // Number of DOF\n const int NuG = 16;\n\n double tauF; // Final time in fm\n double tauIn; // Initial time in fm\n\n double E0;\n double EF;\n\n double TXX0;\n double TXXF;\n\n double EtaByS;\n double SigmaBG; // Sigma in fm\n\npublic:\n LowKArguments(double tf, double tin, double e0, double ef, double txx0,\n double txxf, double etabys, double sigmabg)\n : tauF(tf), tauIn(tin), E0(e0), EF(ef), TXX0(txx0), TXXF(txxf),\n EtaByS(etabys), SigmaBG(sigmabg) {}\n\n double S(double dX, double dT) const {\n const double &s = SigmaBG;\n double rs = dX / s;\n return 1. / (M_PI * s * s) * exp(-rs * rs);\n }\n\n double DS(double dX, double dT) const {\n const double &s = SigmaBG;\n double rs = dX / s;\n return dT / (M_PI * s * s * s) * exp(-rs * rs) * (-2. * rs);\n }\n\n double DSOverR(double dX, double dT) const {\n const double &s = SigmaBG;\n double rs = dX / s;\n return dT * dT / (M_PI * s * s * s * s) * exp(-rs * rs) * (-2.);\n }\n\n double DDS(double dX, double dT) const {\n const double &s = SigmaBG;\n double rs = dX / s;\n return dT * dT / (M_PI * s * s * s * s) * exp(-rs * rs) *\n (4 * rs * rs - 2.);\n }\n\n double Ass() const {\n double dT = tauF - tauIn;\n double s2 = SigmaBG * SigmaBG / (dT * dT);\n return (-0.5 + s2 / 2.) * E0 / EF * (EF + TXXF) / (E0 + TXX0);\n }\n\n double Asv() const { return 0.5 * E0 / EF * (EF + TXXF) / (E0 + TXX0); }\n\n double ScalingVariableInverse() const {\n return 3. / 4. * EtaByS * Entropy(EF) * M_HBARC / (EF * tauF);\n }\n\n double Entropy(double e) const {\n double T = pow(30. / (M_PI * M_PI * NuG) * e, 0.25);\n return 4. / 3. * e / T;\n }\n};\n\n} // GreensFunctions\n", "meta": {"hexsha": "c1207d210c7314d56bb2ec8bca27618fac21736a", "size": 4183, "ext": "h", "lang": "C", "max_stars_repo_path": "src/GreensFunctions.h", "max_stars_repo_name": "j-f-paquet/kompost", "max_stars_repo_head_hexsha": "13113cb05bc673f8e54d52f49adf15ff8d2cd3bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-02T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-02T09:49:03.000Z", "max_issues_repo_path": "src/GreensFunctions.h", "max_issues_repo_name": "j-f-paquet/kompost", "max_issues_repo_head_hexsha": "13113cb05bc673f8e54d52f49adf15ff8d2cd3bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-08-10T19:10:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T13:24:54.000Z", "max_forks_repo_path": "src/GreensFunctions.h", "max_forks_repo_name": "j-f-paquet/kompost", "max_forks_repo_head_hexsha": "13113cb05bc673f8e54d52f49adf15ff8d2cd3bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-02T09:49:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T09:49:07.000Z", "avg_line_length": 26.3081761006, "max_line_length": 74, "alphanum_fraction": 0.6473822615, "num_tokens": 1277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.4067504139168496}} {"text": "/**\n * @file localization.h\n * @brief source localization\n * @author Ulrich Klee\n */\n\n#ifndef LOCALIZATION_H\n#define LOCALIZATION_H\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/jexception.h\"\n\ngsl_vector* getSrpPhat(double delta_f, gsl_matrix_complex *mFramePerChannel, gsl_vector *searchRangeX, gsl_vector *searchRangeY, gsl_matrix *arrgeom, int zPos);\n\nvoid calcDelays(int x, int y, int z, const gsl_matrix* mpos, gsl_vector* delays);\n\nvoid calcDelaysOfLinearMicrophoneArray(float azimuth, const gsl_matrix* mpos, gsl_vector* delays);\n\nvoid calcDelaysOfCircularMicrophoneArray(float azimuth, float elevation, const gsl_matrix* mpos, gsl_vector* delays);\n\ngsl_vector* getDelays(double delta_f, gsl_matrix_complex* mFramePerChannel, gsl_vector* searchRange);\n\ndouble getAzimuth(double delta_f, gsl_matrix_complex *mFramePerChannel, gsl_matrix *arrgeom, gsl_vector *delays);\n\ndouble getPlaneWaveSrp(double delta_f, gsl_matrix_complex *mFramePerChannel, gsl_vector *searchRangeY, gsl_matrix *arrgeom);\n\n//void halfComplexPack(double* tgt, const gsl_vector_complex* src);\n\nvoid getGCCRaw(const gsl_matrix_complex* spectralSample, double sampleRate, gsl_vector* gcc);\n\nconst gsl_vector* getGCC(gsl_matrix_complex *spectralSample, double sampleRate);\nconst gsl_vector* getWindowedGCC(gsl_matrix_complex *spectralSample, double sampleRate, double minDelay, double maxDelay);\n\nconst gsl_vector* getWindowedGCCratio(gsl_matrix_complex *spectralSample, double sampleRate, double minDelay, double maxDelay);\n\nconst gsl_vector* getWindowedGCCdirect(gsl_matrix_complex *spectralSample, double sampleRate, double minDelay, double maxDelay);\n\nconst gsl_vector* getWindowedGCCabs(gsl_matrix_complex *spectralSample, double sampleRate, double minDelay, double maxDelay);\n\nconst gsl_vector* getDynWindowedGCC(gsl_matrix_complex *spectralSample, double sampleRate, double minDelay, double maxDelay, double wMinDelay, double wMaxDelay, double threshold);\n\ndouble getInterpolation(gsl_matrix *crossResult, int delayPos);\n\ngsl_vector* get3DPosition(gsl_vector *yCoord, gsl_vector *azimuth1, gsl_vector *azimuth2, double xPos, double zPos);\n\ngsl_vector* get3DPosition_T_shape(gsl_matrix *arrgeom1, int arrayNr1, gsl_matrix *arrgeom2, int arrayNr2, gsl_matrix *arrgeom3, double azimuth1, double azimuth2, double azimuth3);\n\ngsl_vector* getGCC_old(gsl_matrix_complex *spectralSample, double delta_f, gsl_vector *delays);\n\ngsl_matrix* getLowerTriangMatrix(gsl_matrix* fullMatrix);\n\ngsl_vector* getXi(gsl_matrix* D1_2);\n\nclass PhaseTransform {\npublic:\n PhaseTransform(unsigned sz);\n ~PhaseTransform();\nprivate:\n gsl_vector_complex*\t\t\t\t\t_crossSpectrum;\n double*\t\t\t\t\t\t_crossCorrelation;\n};\n\nclass NoisePowerSpectrum\n{\n public:\n NoisePowerSpectrum(double alpha = 0.95);\n ~NoisePowerSpectrum() {\n if (powerSpectrum != NULL)\n gsl_vector_free(powerSpectrum);\n }\n void setAlpha(double alpha) {\n this->alpha = alpha;\n alpha1 = 1 - alpha;\n }\n double getAlpha() { return alpha; }\n void add(const gsl_vector_complex *noiseSpectrum, double timestamp);\n const gsl_vector *get() {\n return powerSpectrum;\n }\n private:\n gsl_vector *powerSpectrum;\n double alpha, alpha1;\n double timestamp;\n};\n\nclass NoiseCrossSpectrum\n{\n public:\n NoiseCrossSpectrum(double alpha = 0.95);\n ~NoiseCrossSpectrum() {\n if (crossSpectrum != NULL)\n gsl_vector_complex_free(crossSpectrum);\n }\n void setAlpha(double alpha) {\n this->alpha = alpha;\n alpha1 = 1 - alpha;\n }\n double getAlpha() { return alpha; }\n const gsl_vector_complex *get() {\n return crossSpectrum;\n }\n void add(const gsl_vector_complex *noiseSpectrum1, const gsl_vector_complex *noiseSpectrum2);\n private:\n gsl_vector_complex *crossSpectrum;\n double alpha, alpha1;\n};\n\nclass GCC\n{\n public:\n GCC(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true);\n ~GCC();\n void calculate(const gsl_vector_complex *spectralSample1, unsigned chan1, const gsl_vector_complex *spectralSample2, unsigned chan2, unsigned pair, double timestamp, bool sad = false, bool smooth = true);\n const gsl_vector* findMaximum(double minDelay = -HUGE_VAL, double maxDelay = HUGE_VAL);\n double getPeakDelay() { return delay; }\n double getPeakCorr() { return maxCorr; }\n double getRatio() { return ratio; }\n const gsl_vector* getNoisePowerSpectrum(unsigned chan) { return noisePowerSpectrum[chan].get(); }\n const gsl_vector_complex* getNoiseCrossSpectrum(unsigned pair) { return noiseCrossSpectrum[pair].get(); }\n const gsl_vector_complex* getCrossSpectrum() { return crossSpectrum; }\n const gsl_vector* getCrossCorrelation() { return crossCorrelation; }\n void setAlpha(double alpha) {\n for(unsigned i=0; i < pairs; i++)\n noiseCrossSpectrum[i].setAlpha(alpha);\n for(unsigned i=0; i < nChan; i++)\n noisePowerSpectrum[i].setAlpha(alpha);\n }\n double getAlpha() { return noiseCrossSpectrum[0].getAlpha(); }\n protected:\n virtual gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i) { throw jdimension_error(\"Not implemented!!!\\n\"); };\n\n //auxiliary variables \n gsl_complex x1, x2, Gx1x2, Gs1s2, G;\n double W1, W2, X1, X12, X2, X22;\n\n double sampleRate;\n unsigned fftLen;\n unsigned fftLen2;\n unsigned len;\n unsigned nChan;\n unsigned pairs;\n unsigned delayPos;\n double q, q1, q2, beta, beta1;\n double ratio;\n double delay;\n double maxCorr;\n double maxCorr2;\n gsl_vector *crossCorrelation;\n gsl_matrix *interpolValues;\n gsl_vector* retValues;\n gsl_vector *powerSpectrum1, *powerSpectrum2;\n gsl_vector_complex *cSpectrum;\n gsl_vector_complex *crossSpectrum;\n NoisePowerSpectrum* noisePowerSpectrum;\n NoiseCrossSpectrum* noiseCrossSpectrum;\n bool noisereduction;\n bool sad;\n bool interpolate;\n};\n\nclass GCCRaw : public GCC\n{\n public:\n GCCRaw(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {};\n protected:\n gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i);\n};\n\nclass GCCGnnSub : public GCC\n{\n public:\n GCCGnnSub(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {};\n protected:\n gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i);\n};\n\nclass GCCPhat : public GCC\n{\n public:\n GCCPhat(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {};\n protected:\n gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i);\n};\n\nclass GCCGnnSubPhat : public GCC\n{\n public:\n GCCGnnSubPhat(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {};\n protected:\n gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i);\n};\n\nclass GCCMLRRaw : public GCC\n{\n public:\n GCCMLRRaw(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {};\n protected:\n gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i);\n};\n\nclass GCCMLRGnnSub : public GCC\n{\n public:\n GCCMLRGnnSub(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {};\n protected:\n gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i);\n};\n\n#endif\n\n", "meta": {"hexsha": "4ec24a2a529181ab177981bce300fc9ac6ff1d4c", "size": 9243, "ext": "h", "lang": "C", "max_stars_repo_path": "btk20_src/localization/localization.h", "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_issues_repo_path": "btk20_src/localization/localization.h", "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_forks_repo_path": "btk20_src/localization/localization.h", "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "avg_line_length": 42.0136363636, "max_line_length": 308, "alphanum_fraction": 0.7594936709, "num_tokens": 2604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519376, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.40660090071293997}} {"text": "/**\n * File: nicback_utils.c\n * Subroutine for the NICMOS background subtraction\n *\n */\n#include \n#include \n#include \n#include \n#include \"aXe_grism.h\"\n#include \"aXe_utils.h\"\n#include \"spc_FITScards.h\"\n#include \"spce_sect.h\"\n#include \"spce_fitting.h\"\n#include \"spce_is_in.h\"\n#include \"spc_back.h\"\n#include \"spce_pathlength.h\"\n#include \"trfit_utils.h\"\n#include \"nicback_utils.h\"\n\n/**\n * Function: make_nicmos_back\n * The subroutine computes and stores the background image for a specific\n * NICMOS grism image. The non-masked pixels in the grism image are\n * correlated with their corresponding values in the master background image.\n * A linear relation is fitted to the value pairs. Deviating points are\n * excluded using kappa-sigma clipping.\n * Using the slope of the final fit, the background image is computed\n * and stored as a fits image.\n *\n * Parameters:\n * @param obs - the observation for the grism image\n * @param msk_name - the full name of the mask file\n * @param master_bck - the full name of the master sky background\n * @param bck_name - the full name of the background image\n *\n * Returns:\n * @return -\n */\nvoid\nmake_nicmos_back(const observation * const obs, const char *msk_name,\n\t\t const char *master_bck, char bck_name[], char plist_name[],\n\t\t const char corr_bck[])\n{\n px_point npixels;\n\n double skypix_frac;\n\n gsl_matrix *msk_img;\n gsl_matrix *mbck_img;\n gsl_matrix *corr_img=NULL;\n gsl_matrix *grism_bck;\n\n gsl_vector *lfit;\n\n fitbck_data *fbck_data;\n //int f_status=0;\n\n FITScards *cards;\n\n char ID[MAXCHAR];\n\n // fix the extension name\n sprintf (ID, \"BCK\");\n\n // load the master background image\n fprintf(stdout,\"Loading DATA from: %s...\", master_bck);\n mbck_img = FITSimage_to_gsl(master_bck, 1, 1);\n fprintf(stdout,\". Done.\\n\");\n\n if (strlen(corr_bck) > 0)\n {\n // load the correction background image\n fprintf(stdout,\"Loading DATA from: %s...\", corr_bck);\n corr_img = FITSimage_to_gsl(corr_bck, 1, 1);\n fprintf(stdout,\". Done.\\n\");\n }\n\n // load the mask image\n fprintf(stdout,\"Loading DATA from: %s...\", msk_name);\n msk_img = FITSimage_to_gsl(msk_name, 2, 1);\n fprintf(stdout,\". Done.\\n\");\n\n // get the dimension of\n // the grism image\n npixels = get_npixel(obs);\n\n // allocate memory for the fit data\n fbck_data = alloc_fitbck_data(npixels.x * npixels.y);\n\n // fill the fit data into the structure\n fill_fbck_data(obs, msk_img, mbck_img, fbck_data, plist_name, corr_img);\n\n // make the fit, including\n // kappa-sigma iterations\n lfit = make_ksig_linfit(fbck_data);\n\n // report the result of the fit onto the screen\n fprintf(stdout, \"\\nFitting result: c0 = %f +- %f , c1 = %f +- %f , chi^2 = %f\\n\\n\",\n\t gsl_vector_get(lfit, 1), gsl_vector_get(lfit, 3),\n\t gsl_vector_get(lfit, 2), gsl_vector_get(lfit, 4), gsl_vector_get(lfit, 6));\n\n // compute the background for the grism frame\n grism_bck = compute_nicmos_back(mbck_img, gsl_vector_get(lfit, 2),\n\t\t\t\t gsl_vector_get(lfit, 1), corr_img);\n\n // write the background image to a file\n fprintf(stdout,\"Writing data to: %s...\", bck_name);\n gsl_to_FITSimage (grism_bck, bck_name, 1, ID);\n fprintf(stdout,\". Done.\\n\");\n\n // determine the fraction of pixels\n // used in the background determination\n skypix_frac = get_skypix_frac(fbck_data);\n\n // create the fits keywords\n cards = nicbck_info_to_FITScards(skypix_frac, gsl_vector_get(lfit, 2),\n\t\t\t\t gsl_vector_get(lfit, 1));\n\n // transfer the fits keywords\n // to the background image\n put_FITS_cards (bck_name, 2, cards);\n\n // release memory\n free_fitbck_data(fbck_data);\n gsl_matrix_free(mbck_img);\n if (corr_img != NULL)\n gsl_matrix_free(corr_img);\n gsl_matrix_free(msk_img);\n gsl_matrix_free(grism_bck);\n gsl_vector_free(lfit);\n free_FITScards(cards);\n}\n\n\n/**\n * Function: alloc_fitbck_data\n */\nfitbck_data *\nalloc_fitbck_data(const int n_data)\n{\n fitbck_data *fbck_data;\n\n fbck_data = (fitbck_data *)malloc(sizeof(fitbck_data));\n\n fbck_data->x_values = (double *)malloc(n_data * sizeof(double));\n fbck_data->y_values = (double *)malloc(n_data * sizeof(double));\n fbck_data->e_values = (double *)malloc(n_data * sizeof(double));\n fbck_data->x_pos = (int *)malloc(n_data * sizeof(int));\n fbck_data->y_pos = (int *)malloc(n_data * sizeof(int));\n\n fbck_data->n_data = n_data;\n\n return fbck_data;\n}\n\n/**\n * Function: get_skypix_frac\n * The subroutine computes the fraction of image pixels which were used for\n * determining the scaling factor of the master background and the computation\n * of the bacground image. Pixels not used were masked out, since they are part\n * of an object beam or rejected in the kappa-sigma clipping.\n *\n * Parameters:\n * @param fbck_data - the data used for the fit\n *\n * Returns:\n * @return skypix_frac - fraction of pixels used for background determination\n */\ndouble\nget_skypix_frac(const fitbck_data *fbck_data)\n{\n int index;\n int nvalues=0;\n\n double skypix_frac=0.0;\n\n // go over all data values\n for (index=0; index < fbck_data->n_data; index++)\n {\n // check whether the weight is not NULL\n if (fbck_data->e_values[index])\n\t// enhance the number of used pixels\n\tnvalues++;\n }\n\n // compute the fration of used pixels\n skypix_frac = (double)nvalues / (double)fbck_data->n_data;\n\n // return the fraction\n return skypix_frac;\n}\n\n/**\n * Function: compute_nicmos_back\n * The subroutine applies a scaling factor to a master background\n * in order to get the background image for a specific grism image.\n *\n * Parameters:\n * @param mbck_img - the master background pixel\n * @param factor - the scaling factor\n *\n * Returns:\n * @return grism_bck - the background image as gsl-matrix\n */\ngsl_matrix *\ncompute_nicmos_back(const gsl_matrix *mbck_img, const double factor,\n\t\t const double offset, const gsl_matrix *corr_img)\n{\n gsl_matrix *grism_bck;\n\n int ii, jj;\n\n // allocate the space for the background image\n grism_bck = gsl_matrix_alloc(mbck_img->size1, mbck_img->size2);\n\n // go over each row\n for (ii=0; ii < (int)mbck_img->size1; ii++)\n {\n // go over each column\n for (jj=0; jj < (int)mbck_img->size2; jj++)\n\t{\n\t // compute and set the value in the background image\n\t if (corr_img != NULL)\n\t // using the pedestal image\n\t gsl_matrix_set(grism_bck, ii, jj,\n\t (gsl_matrix_get(mbck_img, ii, jj) + gsl_matrix_get(corr_img, ii, jj)) * factor);\n\t else\n\t // using the fit values only\n\t gsl_matrix_set(grism_bck, ii, jj, gsl_matrix_get(mbck_img, ii, jj) * factor + offset);\n\t}\n }\n\n // return the background image\n return grism_bck;\n}\n\n/**\n * Function: compute_nicmos_back\n * The subroutine iteratively fits a linear relation to the pairs of\n * grism image - master background pixel values. After each fit,\n * pairs with large deviations are determined and excluded.\n * The result of the final fit is returned.\n *\n * Parameters:\n * @param fbck_data - the data used for the fits\n *\n * Returns:\n * @return lfit - the results of the final fit\n */\ngsl_vector *\nmake_ksig_linfit(fitbck_data *fbck_data)\n{\n gsl_vector *lfit=NULL;\n\n int index=0;\n\n int clipped=1;\n\n // check whether iterations still\n // must be done and whether\n // the data was changed from clipping\n while (index < N_KSIGBCK_ITER && clipped)\n {\n if (check_fbck_data(fbck_data))\n\t{\n\t // make a non-weighted linear fit\n\t lfit = det_vector_linear(fbck_data->x_values, fbck_data->y_values, fbck_data->e_values,\n\t\t\t\t fbck_data->n_data, 0);\n\n\t // make a clipping iteration\n\t clipped = clipp_fbck_data(fbck_data, lfit, N_KSIGBCK_KAPPA);\n\n\t // inhance the clipping counter\n\t index++;\n\t}\n else\n\t{\n\t // release the space\n\t // for the old vector\n\t if (lfit)\n\t gsl_vector_free(lfit);\n\n\t // get a new dummy vector\n\t lfit = get_fbck_defaults();\n\n\t break;\n\t}\n }\n\n // check whether the scale is within the boundaries\n if (gsl_vector_get(lfit, 2) < BCK_SCALE_MIN || gsl_vector_get(lfit, 2) > BCK_SCALE_MAX)\n {\n\n fprintf(stdout, \"aXe_NICBACK: Background scale is out of bounds. It is re-adjusted.\\n\");\n // release the space\n // for the old vector\n gsl_vector_free(lfit);\n\n // get a new dummy vector\n lfit = get_fbck_defaults();\n }\n\n // return the fit result\n return lfit;\n}\n\nint\ncheck_fbck_data(fitbck_data *fbck_data)\n{\n int check=1;\n int ix_min=60000;\n int ix_max=0;\n int iy_min=60000;\n int iy_max=0;\n int index;\n double frac;\n double x_ext, y_ext;\n\n // get the fraction of background pixel\n frac = get_skypix_frac(fbck_data);\n\n if (frac < FRAC_BPIX_MIN)\n {\n check = 0;\n fprintf(stdout, \"aXe_NICBACK: Not enough background pixels. Fraction: %e\\n\", frac);\n }\n else\n {\n // go over all data values\n for (index=0; index < fbck_data->n_data; index++)\n\t{\n\t // check whether the weight is not NULL\n\t if (fbck_data->e_values[index])\n\t {\n\t if (fbck_data->x_pos[index] > ix_max)\n\t\tix_max = fbck_data->x_pos[index];\n\t if (fbck_data->x_pos[index] < ix_min)\n\t\tix_min = fbck_data->x_pos[index];\n\t if (fbck_data->y_pos[index] > iy_max)\n\t\tiy_max = fbck_data->y_pos[index];\n\t if (fbck_data->y_pos[index] < iy_min)\n\t\tiy_min = fbck_data->y_pos[index];\n\t }\n\t}\n x_ext = (float)(ix_max-ix_min) / NPIX_DIM1;\n y_ext = (float)(iy_max-iy_min) / NPIX_DIM2;\n\n if (x_ext < AREA_EXTEND_MIN || y_ext < AREA_EXTEND_MIN)\n\t{\n\t check = 0;\n\t fprintf(stdout, \"aXe_NICBACK: Not enough coverage. xcover,ycover: %e,%e\\n\", x_ext, y_ext);\n\t}\n }\n\n return check;\n}\n\ngsl_vector*\nget_fbck_defaults()\n{\n gsl_vector *ret;\n\n ret = gsl_vector_alloc(10);\n\n /*\n gsl_vector_set(ret, 0, xean);\n gsl_vector_set(ret, 1, c0);\n gsl_vector_set(ret, 2, c1);\n gsl_vector_set(ret, 3, cov00);\n gsl_vector_set(ret, 4, cov01);\n gsl_vector_set(ret, 5, cov11);\n gsl_vector_set(ret, 6, chisq);\n */\n\n gsl_vector_set(ret, 0, 0.0);\n gsl_vector_set(ret, 1, 0.0);\n gsl_vector_set(ret, 2, 1.0);\n gsl_vector_set(ret, 3, 1.0);\n gsl_vector_set(ret, 4, 0.0);\n gsl_vector_set(ret, 5, 1.0);\n gsl_vector_set(ret, 6, 0.0);\n\n return ret;\n}\n\n/**\n * Function: clipp_fbck_data\n * The subroutine applies kappa-sigma clipping to a set of data points.\n * The difference between the measured values and the expected values\n * according to linear regression are determined.\n * Data which is outside of the accepted interval is excluded by\n * setting the weight to '0.0'. If at least one value was clipped,\n * '1' is returned, otherwise '0' (if all values are within the\n * accepted interval.\n *\n * Parameters:\n * @param fbck_data - the data used for the fits\n * @param lfit - the result of the fit\n * @param kappa - the kappa value\n *\n * Returns:\n * @return clipped - boolean to indicate clipped values\n */\nint\nclipp_fbck_data(fitbck_data *fbck_data, const gsl_vector *lfit, const float kappa)\n{\n int clipped=0;\n int nclipps=0;\n\n int ndata=0;\n int index;\n\n double dy_mean=0.0;\n double stdev=0.0;\n double absdev;\n double dy_act;\n\n double *y_diff;\n\n // allocate memory for the tmp-vector\n y_diff = (double *) malloc(fbck_data->n_data * sizeof(double));\n\n // go over all data values\n for (index=0; index < fbck_data->n_data; index++)\n {\n // check whether the weight is not NULL\n if (fbck_data->e_values[index])\n\t{\n\t // compute the difference from the data point\n\t // to the prediction from the fit\n\t dy_act = (fbck_data->x_values[index] - gsl_vector_get(lfit, 0)) * gsl_vector_get(lfit, 2)\n\t + gsl_vector_get(lfit, 1)-fbck_data->y_values[index];\n\n\t // fill the tmp vector\n\t y_diff[ndata] = dy_act;\n\n\t // pre-comute the mean\n\t dy_mean += dy_act;\n\n\t // enhance the counter\n\t // of non-NULL values\n\t ndata++;\n\t}\n }\n\n // compute the mean offset\n dy_mean = dy_mean / (double)ndata;\n\n // compute the standard deviation\n stdev = comp_stdev_from_array(y_diff, ndata, dy_mean);\n\n // get the maximum allowed\n // deviation\n absdev = kappa*stdev;\n\n // go over the data\n for (index=0; index < fbck_data->n_data; index++)\n {\n // check whether the data has weigth\n if (fbck_data->e_values[index])\n\t{\n\t // compute the absolute difference from the data point\n\t // to the prediction from the fit\n\t dy_act = fabs((fbck_data->x_values[index] - gsl_vector_get(lfit, 0)) * gsl_vector_get(lfit, 2)\n\t\t\t+ gsl_vector_get(lfit, 1)-fbck_data->y_values[index]);\n\n\t // check whether the difference\n\t // is larger than allowed\n\t if (dy_act > absdev)\n\t {\n\t // make the weight NULL\n\t fbck_data->e_values[index] = 0.0;\n\n\t // set the clipped flagg\n\t clipped=1;\n\t nclipps++;\n\t }\n\t}\n }\n\n fprintf(stdout, \"Number of clipped pixels: %i\\n\", nclipps);\n\n // release memory\n free(y_diff);\n\n // return the integer\n // indicating clipped values\n return clipped;\n}\n\n/**\n * Function: comp_stdev_from_array\n * The subroutine computes the standard deviation\n * of a data vector, using the known mean value.\n *\n * Parameters:\n * @param data - the data vector\n * @param ndata - number of data points to use\n * @param mean - mean value of the data points\n *\n * Returns:\n * @return clipped - boolean to indicate clipped values\n */\ndouble\ncomp_stdev_from_array(const double *data, const int ndata, const double mean)\n{\n int index=0;\n\n double stdev=0.0;\n\n // go over the data array\n for (index=0; index < ndata; index++)\n {\n // compute and add the square difference to the mean\n stdev += (data[index] - mean) * (data[index] - mean);\n }\n\n // compute the average square difference\n if (ndata > 1)\n stdev /= ((double)ndata-1);\n\n // compute the final\n // standard deviation\n stdev = sqrt(stdev);\n\n // return the stdev\n return stdev;\n}\n\n\n/**\n * Function: make_nicmos_back\n * The subroutine creates and fills a structure with pairs of correpsonding\n * from a grism image and a master sky background. Dq-masked pixels values\n * and pixels which are part of an object beam are used, but marked with\n * a zero weight.\n *\n * Parameters:\n * @param obs - the observation for the grism image\n * @param msk_image - the maks image values\n * @param mbck_img - the master background values\n * @param fbck_data - structure with the data pairs\n *\n * Returns:\n * @return -\n */\nvoid\nfill_fbck_data(const observation * const obs, const gsl_matrix *msk_img,\n\t const gsl_matrix *mbck_img, fitbck_data *fbck_data, char plist_name[],\n\t const gsl_matrix *corr_img)\n{\n int ix=0;\n int iy=0;\n int index=0;\n char Buffer[10240];\n FILE *fout;\n\n int px_min=20;\n int px_max=180;\n int py_min=50;\n int py_max=245;\n //int px_min=0;\n //int px_max=255;\n //int py_min=0;\n //int py_max=255;\n //10:240,15:245[10:180,20:245][20:180,50:245]\n\n // intitialize the index for\n // the fit_data structure\n index = 0;\n\n double diffval;\n\n fout = fopen(plist_name, \"w\");\n\n // go over all pixels\n // in the grism image\n for (ix=0; ix < (int)obs->grism->size1; ix++)\n {\n for (iy=0; iy < (int)obs->grism->size2; iy++)\n\t{\n\t // set the master background pixel as independent variable\n\t fbck_data->x_values[index] = gsl_matrix_get(mbck_img, ix, iy);\n\n\t if (corr_img != NULL)\n\t // subtract the correction value from the background value\n\t diffval = gsl_matrix_get(obs->grism, ix, iy) - gsl_matrix_get(corr_img, ix, iy);\n\t else\n\t // use the naked background value\n\t diffval = gsl_matrix_get(obs->grism, ix, iy);\n\n\t // set the grism image pixel as dependent variable\n\t //fbck_data->y_values[index] = gsl_matrix_get(obs->grism, ix, iy);\n\t // set the difference as dependent variable\n\t fbck_data->y_values[index] = diffval;\n\n\t // set the x- and y-positions\n\t fbck_data->x_pos[index] = ix;\n\t fbck_data->y_pos[index] = iy;\n\n\t // check whether the pixel was masked out\n\t // or is part of an object\n\t if (isnan(gsl_matrix_get(obs->grism, ix, iy))\n\t\t || gsl_matrix_get(msk_img, ix, iy) < -9.0e+05)\n\t // mask the pixel in the array\n\t fbck_data->e_values[index] = 0.0;\n\t else\n\t {\n\t // give the pixel full weight\n\t //x,y,value_back,value_grism_imag\n\t fbck_data->e_values[index] = 1.0;\n\t sprintf (Buffer, \"%i %i %e %e\\n\",ix, iy, gsl_matrix_get(obs->grism, ix, iy), gsl_matrix_get(mbck_img, ix, iy));\n\t fputs (Buffer, fout);\n\t }\n\n\t // check whether the pixel is in the\n\t // allowed are\n\t if (ix < px_min || ix > px_max\n\t || iy < py_min || iy > py_max)\n\t // mask the pixel in the array\n\t fbck_data->e_values[index] = 0.0;\n\t // enhance the counter\n\t index++;\n\t}\n }\n\n fclose (fout);\n}\n\n/*\n * Function: free_fitbck_data\n * The function releases the memory allocated in\n * a fit-data structure\n *\n * Parameters:\n * @param fbck_data - the allocated structure\n *\n * Returns:\n * @return -\n */\nvoid\nfree_fitbck_data(fitbck_data *fbck_data)\n{\n free(fbck_data->x_values);\n free(fbck_data->y_values);\n free(fbck_data->e_values);\n free(fbck_data->x_pos);\n free(fbck_data->y_pos);\n\n free(fbck_data);\n\n fbck_data = NULL;\n}\n", "meta": {"hexsha": "3eac35d2a95ec274c9f7fb815ce8044bcdf99dfd", "size": 16929, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/nicback_utils.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/nicback_utils.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/nicback_utils.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8458015267, "max_line_length": 118, "alphanum_fraction": 0.6754090614, "num_tokens": 4969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800691997339971, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.40660089588265047}} {"text": "/** @file */\n#ifndef __CCL_CORE_H_INCLUDED__\n#define __CCL_CORE_H_INCLUDED__\n\n#include \n#include \n#include \n#include \n#include \n\nCCL_BEGIN_DECLS\n\n/**\n * Struct containing the parameters defining a cosmology\n */\ntypedef struct ccl_parameters {\n\n // Densities: CDM, baryons, total matter, neutrinos, curvature\n double Omega_c; /**< Density of CDM relative to the critical density*/\n double Omega_b; /**< Density of baryons relative to the critical density*/\n double Omega_m; /**< Density of all matter relative to the critical density*/\n double Omega_k; /**< Density of curvature relative to the critical density*/\n double sqrtk; /**< Square root of the magnitude of curvature, k */ //TODO check\n int k_sign; /**\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"common.h\"\n#include \"filters.h\"\n#include \"hdf5rawWaveformIo.h\"\ntypedef SCOPE_DATA_TYPE IN_WFM_BASE_TYPE;\ntypedef SCOPE_DATA_TYPE OUT_WFM_BASE_TYPE;\n\n/** Parameters settable from commandline */\ntypedef struct param\n{\n size_t diffSep; //!< rise-time in samples for pulse finding\n double riseFrac; //!< fraction of max pulse height for pulse edge location\n double fltM; //!< exp decay constant for Trapezoidal filter\n size_t sPre; //!< samples before rising edge\n size_t sLen; //!< total number of samples of a pulse\n size_t sHscale; //!< histogram sample scaling factor\n} param_t;\n\nparam_t param_default = {\n .diffSep = 150,\n .riseFrac = 0.5,\n .fltM = -1.0,\n .sPre = 1000,\n .sLen = 4000,\n .sHscale = 4\n};\n\nvoid print_usage(const param_t *pm)\n{\n printf(\"Usage:\\n\");\n printf(\" -r rise time in samples[%zd]\\n\", pm->diffSep);\n printf(\" -f riseFrac[%g]\\n\", pm->riseFrac);\n printf(\" -m fltM[%g]\\n\", pm->fltM);\n printf(\" -p sPre[%zd]\\n\", pm->sPre);\n printf(\" -l sLen[%zd]\\n\", pm->sLen);\n printf(\" -s iStart[0] -e iStop[-1] starting and stopping(+1) eventid\\n\");\n printf(\" inFileName(.h5) outFileName\\n\");\n}\n\n/** Find pulses by their rising edges.\n *\n * @param[out] npulse number of pulses found\n * @param[in] fltH input waveform should be loaded into it already\n * @param[in] diffSep basically the rise time in samples\n * @param[in] riseFrac fraction of max pulse height to set pulse edge location\n * @param[in] M exp decay constant for Trapezoidal filter\n * @return the list of rising edge positions (times)\n */\nsize_t *find_pulses(size_t *npulse, filters_t *fltH, size_t diffSep, double riseFrac, double M)\n{\n\n size_t n, nc = 1024;\n size_t *pulseRiseT = NULL, *pulseRiseT1;\n\n size_t flt_k = 2*diffSep, flt_l = 2*flt_k;\n double flt_M = M, max, dV;\n ssize_t i, j, sep, prev;\n\n if((pulseRiseT = calloc(nc, sizeof(size_t))) == NULL) {\n error_printf(\"calloc failed for pulseRiseT in %s()\\n\", __FUNCTION__);\n return NULL;\n }\n \n filters_trapezoidal(fltH, flt_k, flt_l, flt_M);\n\n max = 0.0;\n for(i=0; iwavLen; i++)\n if(fltH->outWav[i] > max) max = fltH->outWav[i];\n\n sep = flt_k + flt_l;\n prev = 0;\n n = 0;\n for(i=0; iwavLen; i++) {\n j = ((i+diffSep)>=fltH->wavLen)?(fltH->wavLen-1):(i+diffSep);\n dV = fltH->inWav[j] - fltH->inWav[i];\n if(dV > max * riseFrac) {\n if(i-prev > sep) {\n pulseRiseT[n] = j; n++;\n if(n >= nc) {\n nc *= 2;\n if((pulseRiseT1 = realloc(pulseRiseT, nc * sizeof(size_t))) == NULL) {\n error_printf(\"realloc failed for pulseRiseT in %s()\\n\", __FUNCTION__);\n *npulse = n;\n return pulseRiseT;\n }\n pulseRiseT = pulseRiseT1;\n }\n prev = i;\n }\n }\n }\n *npulse = n;\n return pulseRiseT;\n}\n\nint main(int argc, char **argv)\n{\n int optC = 0;\n param_t pm;\n\n char *inFileName, *outFileName;\n struct hdf5rawWaveformIo_waveform_file *inWfmFile;\n struct waveform_attribute inWfmAttr;\n struct hdf5rawWaveformIo_waveform_event inWfmEvent;\n IN_WFM_BASE_TYPE *inWfmBuf;\n // OUT_WFM_BASE_TYPE *outWfmBuf;\n filters_t *fltHdl;\n\n ssize_t iStart=0, iStop=-1, i, j, k, iCh;\n size_t nEventsInFile, chGrpLen, npulse, *pulseRiseT, nSep;\n unsigned int v, c;\n size_t chGrpIdx[SCOPE_NCH] = {0};\n double frameSize, val, sep, sepMu, sepSigma;\n\n gsl_histogram2d *wav2H, *flt2H;\n \n memcpy(&pm, ¶m_default, sizeof(pm));\n // parse switches\n while((optC = getopt(argc, argv, \"e:f:l:m:p:r:s:\")) != -1) {\n switch(optC) {\n case 'e':\n iStop = atoll(optarg);\n break;\n case 'f':\n pm.riseFrac = atof(optarg);\n break;\n case 'l':\n pm.sLen = atoll(optarg);\n break;\n case 'm':\n pm.fltM = atof(optarg);\n break;\n case 'p':\n pm.sPre = atoll(optarg);\n break;\n case 'r':\n pm.diffSep = atoll(optarg);\n break;\n case 's':\n iStart = atoll(optarg);\n break;\n default:\n print_usage(&pm);\n return EXIT_FAILURE;\n break;\n }\n }\n\n argc -= optind;\n argv += optind;\n if(argc<2 || argc>=3) {\n print_usage(&pm);\n return EXIT_FAILURE;\n }\n\n inFileName = argv[0];\n outFileName = argv[1];\n\n inWfmFile = hdf5rawWaveformIo_open_file_for_read(inFileName);\n hdf5rawWaveformIo_read_waveform_attribute_in_file_header(inWfmFile, &inWfmAttr);\n\n fprintf(stderr, \"waveform_attribute:\\n\"\n \" chMask = 0x%04x\\n\"\n \" nPt = %zd\\n\"\n \" nFrames = %zd\\n\"\n \" dt = %g\\n\"\n \" t0 = %g\\n\"\n \" ymult = %g %g %g %g\\n\"\n \" yoff = %g %g %g %g\\n\"\n \" yzero = %g %g %g %g\\n\",\n inWfmAttr.chMask, inWfmAttr.nPt, inWfmAttr.nFrames, inWfmAttr.dt,\n inWfmAttr.t0, inWfmAttr.ymult[0], inWfmAttr.ymult[1], inWfmAttr.ymult[2],\n inWfmAttr.ymult[3], inWfmAttr.yoff[0], inWfmAttr.yoff[1],\n inWfmAttr.yoff[2], inWfmAttr.yoff[3], inWfmAttr.yzero[0],\n inWfmAttr.yzero[1], inWfmAttr.yzero[2], inWfmAttr.yzero[3]);\n\n nEventsInFile = hdf5rawWaveformIo_get_number_of_events(inWfmFile);\n fprintf(stderr, \"Number of events in file: %zd\\n\", nEventsInFile);\n if(iStart < 0) iStart = 0;\n if(iStart >= nEventsInFile) iStart = nEventsInFile - 1;\n if(iStop < 0) iStop = nEventsInFile;\n if(iStop <= iStart) iStop = iStart + 1;\n \n if(inWfmAttr.nFrames > 0) {\n frameSize = inWfmAttr.nPt / (double)inWfmAttr.nFrames;\n } else {\n frameSize = (double)inWfmAttr.nPt;\n }\n\n v = inWfmAttr.chMask;\n for(c=0; v; c++) v &= v - 1;\n /* Brian Kernighan's way of counting bits */\n chGrpLen = inWfmFile->nCh / c;\n i=0;\n for(v=0; v> v) & 0x01) {\n chGrpIdx[i] = v;\n i++;\n }\n inWfmBuf = (IN_WFM_BASE_TYPE*)malloc(inWfmFile->nPt * inWfmFile->nCh * sizeof(IN_WFM_BASE_TYPE));\n inWfmEvent.wavBuf = inWfmBuf;\n\n fltHdl = filters_init(NULL, inWfmFile->nPt);\n wav2H = gsl_histogram2d_alloc(pm.sLen/pm.sHscale, 128);\n gsl_histogram2d_set_ranges_uniform(wav2H, -0.5 * inWfmAttr.dt, (pm.sLen+0.5) * inWfmAttr.dt,\n inWfmAttr.yzero[chGrpIdx[0]] + (-128.5 - inWfmAttr.yoff[chGrpIdx[0]]) * inWfmAttr.ymult[chGrpIdx[0]],\n inWfmAttr.yzero[chGrpIdx[0]] + ( 127.5 - inWfmAttr.yoff[chGrpIdx[0]]) * inWfmAttr.ymult[chGrpIdx[0]]);\n \n flt2H = gsl_histogram2d_alloc(pm.sLen/pm.sHscale, 256);\n gsl_histogram2d_set_ranges_uniform(flt2H, -0.5 * inWfmAttr.dt, (pm.sLen+0.5) * inWfmAttr.dt, -0.01, -0.01 + 256 * inWfmAttr.ymult[chGrpIdx[0]]);\n\n nSep = 0; sepMu = 0.0; sepSigma = 0.0;\n for(inWfmEvent.eventId = iStart; inWfmEvent.eventId < iStop; inWfmEvent.eventId++) {\n hdf5rawWaveformIo_read_event(inWfmFile, &inWfmEvent);\n for(iCh=0; iCh < 1 /* inWfmFile->nCh */; iCh++) {\n for(i=0; inPt; i++) {\n val = (inWfmBuf[(size_t)(iCh * inWfmFile->nPt + i)]\n - inWfmAttr.yoff[chGrpIdx[iCh]])\n * inWfmAttr.ymult[chGrpIdx[iCh]]\n + inWfmAttr.yzero[chGrpIdx[iCh]];\n\n fltHdl->inWav[i] = val;\n }\n }\n pulseRiseT = find_pulses(&npulse, fltHdl,\n pm.diffSep, pm.riseFrac, pm.fltM);\n fprintf(stderr, \"eventId = %zd, npulse = %zd, first at %zd\\n\",\n inWfmEvent.eventId, npulse, pulseRiseT[0]);\n for(i=0; iinWav[k]);\n gsl_histogram2d_increment(flt2H, j*inWfmAttr.dt, fltHdl->outWav[k]);\n }\n }\n free(pulseRiseT);\n }\n sepMu /= (double)nSep; \n sepSigma = sqrt(1.0/(double)(nSep-1) * (sepSigma - nSep * sepMu * sepMu));\n\n printf(\"nSep = %zd, sepMu = %g, sepSigma = %g\\n\", nSep, sepMu, sepSigma);\n\n FILE *ofp;\n if((ofp = fopen(outFileName, \"w\"))==NULL) {\n perror(outFileName);\n goto Exit;\n }\n gsl_histogram2d_fprintf(ofp, wav2H, \"%24.16e\", \"%g\");\n fprintf(ofp, \"\\n\\n\");\n gsl_histogram2d_fprintf(ofp, flt2H, \"%24.16e\", \"%g\");\n fprintf(ofp, \"\\n\\n\");\n\n fprintf(ofp, \"# baseline distribution\");\n double yl, yu;\n for(i=0; i\n\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n * \n */\n\n/*\n * =====================================================================================\n *\n * Filename: Reg_s0.c\n *\n * Description: \n *\n * Version: 1.0\n * Created: 15/03/2014 21:10:30\n * Revision: none\n * Compiler: gcc\n *\n * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it\n * Organization: \n *\n * =====================================================================================\n */\n\n#include \n\n#include \"funcs.h\"\n\n/* \n We split the interval of integration (0,+inf) into three parts:\n 1) (0, O/2)\n \t\tand we use the diffeomorphism k -> 1/k to cope with the singularity\n\t\tin k = 0 ;\n 2) (O/2, 3*O/2)\n \t\tand we calculate the Cauchy principal value around k = O ;\n 3) (3*O/2, +inf)\n */\n\n\n/* \n * === FUNCTION ======================================================================\n * Name: fu_inv\n * Description: To integrate on the 1) interval we make the change of variable \n *\t\t k -> 1/k \n * =====================================================================================\n */\ndouble fu_inv ( double k, void* params )\n{\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1, alpha ;\n\tassign_p ( pars, &o_c, &b, &O, &o_1 ) ;\n\talpha = pars->alpha ;\n\n\tdouble temp = alpha*O*exp(-1/(k*o_c))/(1-(O*O*k*k)) ;\n\tdouble val = temp/(k*tanh(b/(k*2))) ;\n\n\treturn val ;\n}\n\n\n/* \n * === FUNCTION ======================================================================\n * Name: fu_coth\n * Description: The function to be integrated around the singularity O, by calculating\n *\t\t the Cauchy principal value. We use qawc and therefore we multiply by\n *\t\t (k-O).\n * =====================================================================================\n */\ndouble fu_cau ( double k, void* params )\n{\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1, alpha ;\n\tassign_p ( pars, &o_c, &b, &O, &o_1 ) ;\n\talpha = pars->alpha ;\n\n\tdouble temp = alpha*O*k*exp(-k/o_c)/(k+O) ;\n\tdouble val = temp/tanh(b*k/2) ;\n\n\treturn val ;\n}\n\n/* \n * === FUNCTION ======================================================================\n * Name: fu_coth\n * Description: Function to be integrated on the tail (3*O/2 , +inf)\n * =====================================================================================\n */\ndouble fu_coth ( double k, void* params )\n{\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1, alpha ;\n\tassign_p ( pars, &o_c, &b, &O, &o_1 ) ;\n\talpha = pars->alpha ;\n\n\tdouble temp = alpha*O*k*exp(-k/o_c)/(k*k-O*O) ;\n\tdouble val = temp/tanh(b*k/2) ;\n\n\treturn val ;\n}\n\n\n/* \n * === FUNCTION ======================================================================\n * Name: re_gs0\n * Description: Re g_s0\n * =====================================================================================\n */\nint re_gs0 ( void* params, double* val, double* error )\n{\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble O ;\n\tO = pars->Omega ;\n\n\tdouble r, err ;\n\tdouble r1, r2, r3, err1, err2, err3 ;\n\n\tgsl_function f, F, G ;\n\tf.function = &fu_coth ; F.function = &fu_cau ; G.function = &fu_inv ;\n\tf.params = pars ; F.params = pars ; G.params = pars ;\n\n\tgsl_integration_workspace *fu_fin_ws =\n\t\tgsl_integration_workspace_alloc (WS_SZ) ;\n\n\tgsl_integration_workspace *fu_inv_ws =\n\t\tgsl_integration_workspace_alloc (WS_SZ) ;\n\n\tgsl_integration_workspace *fu_inf_ws =\n\t\tgsl_integration_workspace_alloc (WS_SZ) ;\n\n\tint status1 ;\n\tstatus1 = gsl_integration_qagiu ( &G, 2/O, 1e-9, .001, WS_SZ,\n\t\t \tfu_inv_ws, &r1,\t&err1 ) ;\n\tint status2 ;\n\tstatus2 = gsl_integration_qawc ( &F, O/2, 3*O/2, O, 1e-9, .001, WS_SZ,\n\t\t\tfu_fin_ws, &r2, &err2 ) ;\n\n\tint status3 ;\n\tstatus3 = gsl_integration_qagiu ( &f, 3*O/2, 1e-9, .001, WS_SZ,\n\t\t \tfu_inf_ws, &r3,\t&err3 ) ;\n\n\tr = r1 + r2 + r3 ; err = err1 + err2 + err3 ;\n\t*val = r ; *error = err ;\n\n\tgsl_integration_workspace_free(fu_fin_ws) ;\n\tgsl_integration_workspace_free(fu_inv_ws) ;\n\tgsl_integration_workspace_free(fu_inf_ws) ;\n\n\tint status = status1 + status2 + status3 ;\n\treturn status ;\n}\n\n\n", "meta": {"hexsha": "874dea6a2f160d2da06e77683bf7d51a17f7a33e", "size": 5548, "ext": "c", "lang": "C", "max_stars_repo_path": "Reg_s0.c", "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Reg_s0.c", "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Reg_s0.c", "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7028571429, "max_line_length": 88, "alphanum_fraction": 0.5639870224, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.40586740557261897}} {"text": "/* multilarge_nlinear/cgst.c\n * \n * Copyright (C) 2016 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * This module contains an implementation of the Steihaug-Toint\n * conjugate gradient algorithm for nonlinear optimization problems.\n * This implementation closely follows the following works:\n *\n * [1] T. Steihaug, The conjugate gradient method and trust regions\n * in large scale optimization, SIAM J. Num. Anal., 20(3) 1983.\n *\n * In the below algorithm, the Jacobian and gradient are scaled\n * according to:\n *\n * J~ = J D^{-1}\n * g~ = D^{-1}\n *\n * prior to any calculations which results in better numerical\n * stability when solving for the Gauss-Newton step. The resulting\n * step vector is then backtransformed as:\n *\n * dx = D^{-1} dx~\n */\n\ntypedef struct\n{\n size_t n; /* number of observations */\n size_t p; /* number of parameters */\n gsl_vector *z; /* Gauss-Newton step, size p */\n gsl_vector *r; /* steepest descent step, size p */\n gsl_vector *d; /* steepest descent step, size p */\n gsl_vector *workp; /* workspace, length p */\n gsl_vector *workn; /* workspace, length n */\n double norm_g; /* || g~ || */\n\n double cgtol; /* tolerance for CG solution */\n size_t cgmaxit; /* maximum CG iterations */\n} cgst_state_t;\n\n#include \"common.c\"\n\nstatic void * cgst_alloc (const void * params, const size_t n, const size_t p);\nstatic void cgst_free(void *vstate);\nstatic int cgst_init(const void *vtrust_state, void *vstate);\nstatic int cgst_preloop(const void * vtrust_state, void * vstate);\nstatic int cgst_step(const void * vtrust_state, const double delta,\n gsl_vector * dx, void * vstate);\nstatic int cgst_preduction(const void * vtrust_state, const gsl_vector * dx,\n double * pred, void * vstate);\nstatic double cgst_calc_tau(const gsl_vector * p, const gsl_vector * d,\n const double delta);\n\nstatic void *\ncgst_alloc (const void * params, const size_t n, const size_t p)\n{\n const gsl_multilarge_nlinear_parameters *par = (const gsl_multilarge_nlinear_parameters *) params;\n cgst_state_t *state;\n \n state = calloc(1, sizeof(cgst_state_t));\n if (state == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate st state\", GSL_ENOMEM);\n }\n\n state->z = gsl_vector_alloc(p);\n if (state->z == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for z\", GSL_ENOMEM);\n }\n\n state->r = gsl_vector_alloc(p);\n if (state->r == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for r\", GSL_ENOMEM);\n }\n\n state->d = gsl_vector_alloc(p);\n if (state->d == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for d\", GSL_ENOMEM);\n }\n\n state->workp = gsl_vector_alloc(p);\n if (state->workp == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workp\", GSL_ENOMEM);\n }\n\n state->workn = gsl_vector_alloc(n);\n if (state->workn == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workn\", GSL_ENOMEM);\n }\n\n state->n = n;\n state->p = p;\n\n state->cgmaxit = par->max_iter;\n if (state->cgmaxit == 0)\n state->cgmaxit = n;\n\n state->cgtol = par->tol;\n\n return state;\n}\n\nstatic void\ncgst_free(void *vstate)\n{\n cgst_state_t *state = (cgst_state_t *) vstate;\n\n if (state->z)\n gsl_vector_free(state->z);\n\n if (state->r)\n gsl_vector_free(state->r);\n\n if (state->d)\n gsl_vector_free(state->d);\n\n if (state->workp)\n gsl_vector_free(state->workp);\n\n if (state->workn)\n gsl_vector_free(state->workn);\n\n free(state);\n}\n\n/*\ncgst_init()\n Initialize cgst solver\n\nInputs: vtrust_state - trust state\n vstate - workspace\n\nReturn: success/error\n*/\n\nstatic int\ncgst_init(const void *vtrust_state, void *vstate)\n{\n /* nothing to do */\n\n (void)vtrust_state;\n (void)vstate;\n\n return GSL_SUCCESS;\n}\n\nstatic int\ncgst_preloop(const void * vtrust_state, void * vstate)\n{\n /* nothing to do */\n\n (void)vtrust_state;\n (void)vstate;\n\n return GSL_SUCCESS;\n}\n\n/*\ncgst_step()\n Calculate a new step vector\n\nReturn:\nGSL_SUCCESS if CG solution found\nGSL_EMAXITER if no solution found\n*/\n\nstatic int\ncgst_step(const void * vtrust_state, const double delta,\n gsl_vector * dx, void * vstate)\n{\n int status;\n const gsl_multilarge_nlinear_trust_state *trust_state =\n (const gsl_multilarge_nlinear_trust_state *) vtrust_state;\n cgst_state_t *state = (cgst_state_t *) vstate;\n const gsl_vector * x = trust_state->x;\n const gsl_vector * f = trust_state->f;\n const gsl_vector * swts = trust_state->sqrt_wts;\n const gsl_vector * diag = trust_state->diag;\n const gsl_multilarge_nlinear_parameters * params = trust_state->params;\n gsl_multilarge_nlinear_fdf * fdf = trust_state->fdf;\n double alpha, beta, u;\n double norm_Jd; /* || J D^{-1} d_i || */\n double norm_r; /* || r_i || */\n double norm_rp1; /* || r_{i+1} || */\n size_t i;\n\n /* Step 1 of [1], section 2; scale gradient as\n *\n * g~ = D^{-1} g\n *\n * for better numerical stability\n */\n\n for (i = 0; i < state->p; ++i)\n {\n double gi = gsl_vector_get(trust_state->g, i);\n double di = gsl_vector_get(trust_state->diag, i);\n\n gsl_vector_set(state->z, i, 0.0);\n gsl_vector_set(state->r, i, -gi / di);\n gsl_vector_set(state->d, i, -gi / di);\n gsl_vector_set(state->workp, i, gi / di);\n }\n\n /* compute || g~ || */\n state->norm_g = gsl_blas_dnrm2(state->workp);\n\n for (i = 0; i < state->cgmaxit; ++i)\n {\n /* workp := D^{-1} d_i */\n gsl_vector_memcpy(state->workp, state->d);\n gsl_vector_div(state->workp, trust_state->diag);\n\n /* workn := J D^{-1} d_i */\n status = gsl_multilarge_nlinear_eval_df(CblasNoTrans, x, f, state->workp,\n swts, params->h_df, params->fdtype,\n fdf, state->workn, NULL, NULL);\n if (status)\n return status;\n\n /* compute || J D^{-1} d_i || */\n norm_Jd = gsl_blas_dnrm2(state->workn);\n\n /* Step 2 of [1], section 2 */\n if (norm_Jd == 0.0)\n {\n double tau = cgst_calc_tau(state->z, state->d, delta);\n\n /* dx = z_i + tau*d_i */\n scaled_addition(1.0, state->z, tau, state->d, dx);\n gsl_vector_div(dx, diag);\n\n return GSL_SUCCESS;\n }\n\n /* Step 3 of [1], section 2 */\n\n norm_r = gsl_blas_dnrm2(state->r);\n u = norm_r / norm_Jd;\n alpha = u * u;\n\n /* workp <= z_{i+1} = z_i + alpha_i*d_i */\n scaled_addition(1.0, state->z, alpha, state->d, state->workp);\n\n u = gsl_blas_dnrm2(state->workp);\n if (u >= delta)\n {\n double tau = cgst_calc_tau(state->z, state->d, delta);\n\n /* dx = z_i + tau*d_i */\n scaled_addition(1.0, state->z, tau, state->d, dx);\n gsl_vector_div(dx, diag);\n\n return GSL_SUCCESS;\n }\n\n /* store z_{i+1} */\n gsl_vector_memcpy(state->z, state->workp);\n\n /* Step 4 of [1], section 2 */\n\n /* compute: workp := alpha B d_i = alpha D^{-1} J^T J D^{-1} d_i,\n * where J D^{-1} d_i is already stored in workn */\n status = gsl_multilarge_nlinear_eval_df(CblasTrans, x, f, state->workn,\n swts, params->h_df, params->fdtype,\n fdf, state->workp, NULL, NULL);\n if (status)\n return status;\n\n gsl_vector_div(state->workp, trust_state->diag);\n gsl_vector_scale(state->workp, alpha);\n\n /* r_{i+1} = r_i - alpha*B*d_i */\n gsl_vector_sub(state->r, state->workp);\n norm_rp1 = gsl_blas_dnrm2(state->r);\n\n u = norm_rp1 / state->norm_g;\n if (u < state->cgtol)\n {\n gsl_vector_memcpy(dx, state->z);\n gsl_vector_div(dx, diag);\n return GSL_SUCCESS;\n }\n\n /* Step 5 of [1], section 2 */\n\n /* compute u = ||r_{i+1}|| / || r_i|| */\n u = norm_rp1 / norm_r;\n beta = u * u;\n\n /* compute: d_{i+1} = rt_{i+1} + beta*d_i */\n scaled_addition(1.0, state->r, beta, state->d, state->d);\n }\n\n /* failed to converge, return current estimate */\n gsl_vector_memcpy(dx, state->z);\n gsl_vector_div(dx, diag);\n\n return GSL_EMAXITER;\n}\n\nstatic int\ncgst_preduction(const void * vtrust_state, const gsl_vector * dx,\n double * pred, void * vstate)\n{\n const gsl_multilarge_nlinear_trust_state *trust_state =\n (const gsl_multilarge_nlinear_trust_state *) vtrust_state;\n cgst_state_t *state = (cgst_state_t *) vstate;\n\n *pred = quadratic_preduction(trust_state, dx, state->workn);\n\n return GSL_SUCCESS;\n}\n\n/*\ncgst_calc_tau()\n Compute tau > 0 such that:\n\n|| p + tau*d || = delta\n*/\n\nstatic double\ncgst_calc_tau(const gsl_vector * p, const gsl_vector * d,\n const double delta)\n{\n double norm_p, norm_d, u;\n double t1, t2, tau;\n\n norm_p = gsl_blas_dnrm2(p);\n norm_d = gsl_blas_dnrm2(d);\n\n /* compute (p, d) */\n gsl_blas_ddot(p, d, &u);\n\n t1 = u / (norm_d * norm_d);\n t2 = t1*u + (delta + norm_p) * (delta - norm_p);\n tau = -t1 + sqrt(t2) / norm_d;\n\n return tau;\n}\n\nstatic const gsl_multilarge_nlinear_trs cgst_type =\n{\n \"steihaug-toint\",\n cgst_alloc,\n cgst_init,\n cgst_preloop,\n cgst_step,\n cgst_preduction,\n cgst_free\n};\n\nconst gsl_multilarge_nlinear_trs *gsl_multilarge_nlinear_trs_cgst = &cgst_type;\n", "meta": {"hexsha": "9e86cdc27301e0430dc4a86c3ef2df78d4d87ae9", "size": 10314, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multilarge_nlinear/cgst.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multilarge_nlinear/cgst.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multilarge_nlinear/cgst.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.9295039164, "max_line_length": 100, "alphanum_fraction": 0.6194492922, "num_tokens": 2942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4057470702544803}} {"text": "/* integration/cquad.c\n * \n * Copyright (C) 2010 Pedro Gonnet\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cquad_const.c\"\n\n\n/* Allocates a workspace for the given maximum number of intervals.\n Note that if the workspace gets filled, the intervals with the\n lowest error estimates are dropped. The maximum number of\n intervals is therefore not the maximum number of intervals\n that will be computed, but merely the size of the buffer.\n */\n\ngsl_integration_cquad_workspace *\ngsl_integration_cquad_workspace_alloc (const size_t n)\n{\n\n gsl_integration_cquad_workspace *w;\n\n /* Check inputs */\n if (n < 3)\n GSL_ERROR_VAL (\"workspace size n must be at least 3\", GSL_EDOM, 0);\n\n /* Allocate first the workspace struct */\n if ((w =\n (gsl_integration_cquad_workspace *)\n malloc (sizeof (gsl_integration_cquad_workspace))) == NULL)\n GSL_ERROR_VAL (\"failed to allocate space for workspace struct\",\n\t\t GSL_ENOMEM, 0);\n\n /* Allocate the intervals */\n if ((w->ivals =\n (gsl_integration_cquad_ival *)\n malloc (sizeof (gsl_integration_cquad_ival) * n)) == NULL)\n {\n free (w);\n GSL_ERROR_VAL (\"failed to allocate space for the intervals\", GSL_ENOMEM,\n\t\t 0);\n }\n\n /* Allocate the max-heap indices */\n if ((w->heap = (size_t *) malloc (sizeof (size_t) * n)) == NULL)\n {\n free (w->ivals);\n free (w);\n GSL_ERROR_VAL (\"failed to allocate space for the heap\", GSL_ENOMEM, 0);\n }\n\n /* Remember the size of the workspace */\n w->size = n;\n\n /* Return the result */\n return w;\n\n}\n\n\n/* Liberates the workspace memory.\n */\n\nvoid\ngsl_integration_cquad_workspace_free (gsl_integration_cquad_workspace * w)\n{\n\n /* Nothing to be done? */\n if (w == NULL)\n return;\n\n /* Free the intervals first */\n if (w->ivals != NULL)\n free (w->ivals);\n\n /* Free the heap */\n if (w->heap != NULL)\n free (w->heap);\n\n /* Free the structure */\n free (w);\n\n}\n\n\n/* Compute the product of the fx with one of the inverse\n Vandermonde-like matrices. */\n\nstatic void\nVinvfx (const double *fx, double *c, const int d)\n{\n\n int i, j;\n\n switch (d)\n {\n case 0:\n for (i = 0; i <= 4; i++)\n\t{\n\t c[i] = 0.0;\n\t for (j = 0; j <= 4; j++)\n\t c[i] += V1inv[i * 5 + j] * fx[j * 8];\n\t}\n break;\n case 1:\n for (i = 0; i <= 8; i++)\n\t{\n\t c[i] = 0.0;\n\t for (j = 0; j <= 8; j++)\n\t c[i] += V2inv[i * 9 + j] * fx[j * 4];\n\t}\n break;\n case 2:\n for (i = 0; i <= 16; i++)\n\t{\n\t c[i] = 0.0;\n\t for (j = 0; j <= 16; j++)\n\t c[i] += V3inv[i * 17 + j] * fx[j * 2];\n\t}\n break;\n case 3:\n for (i = 0; i <= 32; i++)\n\t{\n\t c[i] = 0.0;\n\t for (j = 0; j <= 32; j++)\n\t c[i] += V4inv[i * 33 + j] * fx[j];\n\t}\n break;\n }\n\n}\n\n\n/* Downdate the interpolation given by the n coefficients c\n by removing the nodes with indices in nans. */\n\nstatic void\ndowndate (double *c, int n, int d, int *nans, int nnans)\n{\n\n static const int bidx[4] = { 0, 6, 16, 34 };\n double b_new[34], alpha;\n int i, j;\n\n for (i = 0; i <= n + 1; i++)\n b_new[i] = bee[bidx[d] + i];\n for (i = 0; i < nnans; i++)\n {\n b_new[n + 1] = b_new[n + 1] / Lalpha[n];\n b_new[n] = (b_new[n] + xi[nans[i]] * b_new[n + 1]) / Lalpha[n - 1];\n for (j = n - 1; j > 0; j--)\n\tb_new[j] =\n\t (b_new[j] + xi[nans[i]] * b_new[j + 1] -\n\t Lgamma[j + 1] * b_new[j + 2]) / Lalpha[j - 1];\n for (j = 0; j <= n; j++)\n\tb_new[j] = b_new[j + 1];\n alpha = c[n] / b_new[n];\n for (j = 0; j < n; j++)\n\tc[j] -= alpha * b_new[j];\n c[n] = 0;\n n--;\n }\n\n}\n\n\n/* The actual integration routine.\n */\n\nint\ngsl_integration_cquad (const gsl_function * f, double a, double b,\n\t\t double epsabs, double epsrel,\n\t\t gsl_integration_cquad_workspace * ws,\n\t\t double *result, double *abserr, size_t * nevals)\n{\n\n /* Some constants that we will need. */\n static const int n[4] = { 4, 8, 16, 32 };\n static const int skip[4] = { 8, 4, 2, 1 };\n static const int idx[4] = { 0, 5, 14, 31 };\n static const double w = M_SQRT2 / 2;\n static const int ndiv_max = 20;\n\n /* Actual variables (as opposed to constants above). */\n double m, h, temp;\n double igral, err, igral_final, err_final, err_excess;\n int nivals, neval = 0;\n int i, j, d, split, t;\n int nnans, nans[32];\n gsl_integration_cquad_ival *iv, *ivl, *ivr;\n double nc, ncdiff;\n\n /* Check the input arguments. */\n if (f == NULL)\n GSL_ERROR (\"function pointer shouldn't be NULL\", GSL_EINVAL);\n if (result == NULL)\n GSL_ERROR (\"result pointer shouldn't be NULL\", GSL_EINVAL);\n if (ws == NULL)\n GSL_ERROR (\"workspace pointer shouldn't be NULL\", GSL_EINVAL);\n\n\n /* Check for unreasonable accuracy demands */\n if (epsabs < 0.0 || epsrel < 0.0)\n GSL_ERROR (\"tolerances may not be negative\", GSL_EBADTOL);\n if (epsabs <= 0 && epsrel < GSL_DBL_EPSILON)\n GSL_ERROR (\"unreasonable accuracy requirement\", GSL_EBADTOL);\n\n\n /* Create the first interval. */\n iv = &(ws->ivals[0]);\n m = (a + b) / 2;\n h = (b - a) / 2;\n nnans = 0;\n for (i = 0; i <= n[3]; i++)\n {\n iv->fx[i] = GSL_FN_EVAL (f, m + xi[i] * h);\n neval++;\n if (!finite (iv->fx[i]))\n\t{\n\t nans[nnans++] = i;\n\t iv->fx[i] = 0.0;\n\t}\n }\n Vinvfx (iv->fx, &(iv->c[idx[0]]), 0);\n Vinvfx (iv->fx, &(iv->c[idx[3]]), 3);\n Vinvfx (iv->fx, &(iv->c[idx[2]]), 2);\n for (i = 0; i < nnans; i++)\n iv->fx[nans[i]] = GSL_NAN;\n iv->a = a;\n iv->b = b;\n iv->depth = 3;\n iv->rdepth = 1;\n iv->ndiv = 0;\n iv->igral = 2 * h * iv->c[idx[3]] * w;\n nc = 0.0;\n for (i = n[2] + 1; i <= n[3]; i++)\n {\n temp = iv->c[idx[3] + i];\n nc += temp * temp;\n }\n ncdiff = nc;\n for (i = 0; i <= n[2]; i++)\n {\n temp = iv->c[idx[2] + i] - iv->c[idx[3] + i];\n ncdiff += temp * temp;\n nc += iv->c[idx[3] + i] * iv->c[idx[3] + i];\n }\n ncdiff = sqrt (ncdiff);\n nc = sqrt (nc);\n iv->err = ncdiff * 2 * h;\n if (ncdiff / nc > 0.1 && iv->err < 2 * h * nc)\n iv->err = 2 * h * nc;\n\n\n /* Initialize the heaps. */\n for (i = 0; i < ws->size; i++)\n ws->heap[i] = i;\n\n\n /* Initialize some global values. */\n igral = iv->igral;\n err = iv->err;\n nivals = 1;\n igral_final = 0.0;\n err_final = 0.0;\n err_excess = 0.0;\n\n\n /* Main loop. */\n while (nivals > 0 && err > 0.0 &&\n\t !(err <= fabs (igral) * epsrel || err <= epsabs)\n\t && !(err_final > fabs (igral) * epsrel\n\t && err - err_final < fabs (igral) * epsrel)\n\t && !(err_final > epsabs && err - err_final < epsabs))\n {\n\n /* Put our finger on the interval with the largest error. */\n iv = &(ws->ivals[ws->heap[0]]);\n m = (iv->a + iv->b) / 2;\n h = (iv->b - iv->a) / 2;\n\n/* printf\n (\"cquad: processing ival %i (of %i) with [%e,%e] int=%e, err=%e, depth=%i\\n\",\n ws->heap[0], nivals, iv->a, iv->b, iv->igral, iv->err, iv->depth);\n*/\n /* Should we try to increase the degree? */\n if (iv->depth < 3)\n\t{\n\n\t /* Keep tabs on some variables. */\n\t d = ++iv->depth;\n\n\t /* Get the new (missing) function values */\n\t for (i = skip[d]; i <= 32; i += 2 * skip[d])\n\t {\n\t iv->fx[i] = GSL_FN_EVAL (f, m + xi[i] * h);\n\t neval++;\n\t }\n\t nnans = 0;\n\t for (i = 0; i <= 32; i += skip[d])\n\t {\n\t if (!finite (iv->fx[i]))\n\t\t{\n\t\t nans[nnans++] = i;\n\t\t iv->fx[i] = 0.0;\n\t\t}\n\t }\n\n\t /* Compute the new coefficients. */\n\t Vinvfx (iv->fx, &(iv->c[idx[d]]), d);\n\n\t /* Downdate any NaNs. */\n\t if (nnans > 0)\n\t {\n\t downdate (&(iv->c[idx[d]]), n[d], d, nans, nnans);\n\t for (i = 0; i < nnans; i++)\n\t\tiv->fx[nans[i]] = GSL_NAN;\n\t }\n\n\t /* Compute the error estimate. */\n\t nc = 0.0;\n\t for (i = n[d - 1] + 1; i <= n[d]; i++)\n\t {\n\t temp = iv->c[idx[d] + i];\n\t nc += temp * temp;\n\t }\n\t ncdiff = nc;\n\t for (i = 0; i <= n[d - 1]; i++)\n\t {\n\t temp = iv->c[idx[d - 1] + i] - iv->c[idx[d] + i];\n\t ncdiff += temp * temp;\n\t nc += iv->c[idx[d] + i] * iv->c[idx[d] + i];\n\t }\n\t ncdiff = sqrt (ncdiff);\n\t nc = sqrt (nc);\n\t iv->err = ncdiff * 2 * h;\n\n\t /* Compute the local integral. */\n\t iv->igral = 2 * h * w * iv->c[idx[d]];\n\n\t /* Split the interval prematurely? */\n\t split = (nc > 0 && ncdiff / nc > 0.1);\n\n\t}\n\n /* Maximum degree reached, just split. */\n else\n\t{\n\t split = 1;\n\t}\n\n\n /* Should we drop this interval? */\n if ((m + h * xi[0]) >= (m + h * xi[1])\n\t || (m + h * xi[31]) >= (m + h * xi[32])\n\t || iv->err < fabs (iv->igral) * GSL_DBL_EPSILON * 10)\n\t{\n\n/* printf\n (\"cquad: dumping ival %i (of %i) with [%e,%e] int=%e, err=%e, depth=%i\\n\",\n ws->heap[0], nivals, iv->a, iv->b, iv->igral, iv->err,\n iv->depth);\n*/\n\t /* Keep this interval's contribution */\n\t err_final += iv->err;\n\t igral_final += iv->igral;\n\n\t /* Swap with the last element on the heap */\n\t t = ws->heap[nivals - 1];\n\t ws->heap[nivals - 1] = ws->heap[0];\n\t ws->heap[0] = t;\n\t nivals--;\n\n\t /* Fix up the heap */\n\t i = 0;\n\t while (2 * i + 1 < nivals)\n\t {\n\n\t /* Get the kids */\n\t j = 2 * i + 1;\n\n\t /* If the j+1st entry exists and is larger than the jth,\n\t use it instead. */\n\t if (j + 1 < nivals\n\t\t && ws->ivals[ws->heap[j + 1]].err >=\n\t\t ws->ivals[ws->heap[j]].err)\n\t\tj++;\n\n\t /* Do we need to move the ith entry up? */\n\t if (ws->ivals[ws->heap[j]].err <= ws->ivals[ws->heap[i]].err)\n\t\tbreak;\n\t else\n\t\t{\n\t\t t = ws->heap[j];\n\t\t ws->heap[j] = ws->heap[i];\n\t\t ws->heap[i] = t;\n\t\t i = j;\n\t\t}\n\t }\n\n\t}\n\n /* Do we need to split this interval? */\n else if (split)\n\t{\n\n\t /* Some values we will need often... */\n\t d = iv->depth;\n\n\t /* Generate the interval on the left */\n\t ivl = &(ws->ivals[ws->heap[nivals++]]);\n\t ivl->a = iv->a;\n\t ivl->b = m;\n\t ivl->depth = 0;\n\t ivl->rdepth = iv->rdepth + 1;\n\t ivl->fx[0] = iv->fx[0];\n\t ivl->fx[32] = iv->fx[16];\n\t for (i = skip[0]; i < 32; i += skip[0])\n\t {\n\t ivl->fx[i] =\n\t\tGSL_FN_EVAL (f, (ivl->a + ivl->b) / 2 + xi[i] * h / 2);\n\t neval++;\n\t }\n\t nnans = 0;\n\t for (i = 0; i <= 32; i += skip[0])\n\t {\n\t if (!finite (ivl->fx[i]))\n\t\t{\n\t\t nans[nnans++] = i;\n\t\t ivl->fx[i] = 0.0;\n\t\t}\n\t }\n\t Vinvfx (ivl->fx, ivl->c, 0);\n\t if (nnans > 0)\n\t {\n\t downdate (ivl->c, n[0], 0, nans, nnans);\n\t for (i = 0; i < nnans; i++)\n\t\tivl->fx[nans[i]] = GSL_NAN;\n\t }\n\t for (i = 0; i <= n[d]; i++)\n\t {\n\t ivl->c[idx[d] + i] = 0.0;\n\t for (j = i; j <= n[d]; j++)\n\t\tivl->c[idx[d] + i] += Tleft[i * 33 + j] * iv->c[idx[d] + j];\n\t }\n\t ncdiff = 0.0;\n\t for (i = 0; i <= n[0]; i++)\n\t {\n\t temp = ivl->c[i] - ivl->c[idx[d] + i];\n\t ncdiff += temp * temp;\n\t }\n\t for (i = n[0] + 1; i <= n[d]; i++)\n\t {\n\t temp = ivl->c[idx[d] + i];\n\t ncdiff += temp * temp;\n\t }\n\t ncdiff = sqrt (ncdiff);\n\t ivl->err = ncdiff * h;\n\n\t /* Check for divergence. */\n\t ivl->ndiv = iv->ndiv + (fabs (iv->c[0]) > 0\n\t\t\t\t && ivl->c[0] / iv->c[0] > 2);\n\t if (ivl->ndiv > ndiv_max && 2 * ivl->ndiv > ivl->rdepth)\n\t {\n /* need copysign(INFINITY, igral) */\n\t *result = (igral >= 0) ? GSL_POSINF : GSL_NEGINF; \n\t if (nevals != NULL)\n\t\t*nevals = neval;\n\t return GSL_EDIVERGE;\n\t }\n\n\t /* Compute the local integral. */\n\t ivl->igral = h * w * ivl->c[0];\n\n\n\t /* Generate the interval on the right */\n\t ivr = &(ws->ivals[ws->heap[nivals++]]);\n\t ivr->a = m;\n\t ivr->b = iv->b;\n\t ivr->depth = 0;\n\t ivr->rdepth = iv->rdepth + 1;\n\t ivr->fx[0] = iv->fx[16];\n\t ivr->fx[32] = iv->fx[32];\n\t for (i = skip[0]; i < 32; i += skip[0])\n\t {\n\t ivr->fx[i] =\n\t\tGSL_FN_EVAL (f, (ivr->a + ivr->b) / 2 + xi[i] * h / 2);\n\t neval++;\n\t }\n\t nnans = 0;\n\t for (i = 0; i <= 32; i += skip[0])\n\t {\n\t if (!finite (ivr->fx[i]))\n\t\t{\n\t\t nans[nnans++] = i;\n\t\t ivr->fx[i] = 0.0;\n\t\t}\n\t }\n\t Vinvfx (ivr->fx, ivr->c, 0);\n\t if (nnans > 0)\n\t {\n\t downdate (ivr->c, n[0], 0, nans, nnans);\n\t for (i = 0; i < nnans; i++)\n\t\tivr->fx[nans[i]] = GSL_NAN;\n\t }\n\t for (i = 0; i <= n[d]; i++)\n\t {\n\t ivr->c[idx[d] + i] = 0.0;\n\t for (j = i; j <= n[d]; j++)\n\t\tivr->c[idx[d] + i] += Tright[i * 33 + j] * iv->c[idx[d] + j];\n\t }\n\t ncdiff = 0.0;\n\t for (i = 0; i <= n[0]; i++)\n\t {\n\t temp = ivr->c[i] - ivr->c[idx[d] + i];\n\t ncdiff += temp * temp;\n\t }\n\t for (i = n[0] + 1; i <= n[d]; i++)\n\t {\n\t temp = ivr->c[idx[d] + i];\n\t ncdiff += temp * temp;\n\t }\n\t ncdiff = sqrt (ncdiff);\n\t ivr->err = ncdiff * h;\n\n\t /* Check for divergence. */\n\t ivr->ndiv = iv->ndiv + (fabs (iv->c[0]) > 0\n\t\t\t\t && ivr->c[0] / iv->c[0] > 2);\n\t if (ivr->ndiv > ndiv_max && 2 * ivr->ndiv > ivr->rdepth)\n\t {\n /* need copysign(INFINITY, igral) */\n\t *result = (igral >= 0) ? GSL_POSINF : GSL_NEGINF; \n\t if (nevals != NULL)\n\t\t*nevals = neval;\n\t return GSL_EDIVERGE;\n\t }\n\n\t /* Compute the local integral. */\n\t ivr->igral = h * w * ivr->c[0];\n\n\n\t /* Fix-up the heap: we now have one interval on top\n\t that we don't need any more and two new, unsorted\n\t ones at the bottom. */\n\n\t /* Flip the last interval to the top of the heap and\n\t sift down. */\n\t t = ws->heap[nivals - 1];\n\t ws->heap[nivals - 1] = ws->heap[0];\n\t ws->heap[0] = t;\n\t nivals--;\n\n\t /* Sift this interval back down the heap. */\n\t i = 0;\n\t while (2 * i + 1 < nivals - 1)\n\t {\n\t j = 2 * i + 1;\n\t if (j + 1 < nivals - 1\n\t\t && ws->ivals[ws->heap[j + 1]].err >=\n\t\t ws->ivals[ws->heap[j]].err)\n\t\tj++;\n\t if (ws->ivals[ws->heap[j]].err <= ws->ivals[ws->heap[i]].err)\n\t\tbreak;\n\t else\n\t\t{\n\t\t t = ws->heap[j];\n\t\t ws->heap[j] = ws->heap[i];\n\t\t ws->heap[i] = t;\n\t\t i = j;\n\t\t}\n\t }\n\n\t /* Now grab the last interval and sift it up the heap. */\n\t i = nivals - 1;\n\t while (i > 0)\n\t {\n\t j = (i - 1) / 2;\n\t if (ws->ivals[ws->heap[j]].err < ws->ivals[ws->heap[i]].err)\n\t\t{\n\t\t t = ws->heap[j];\n\t\t ws->heap[j] = ws->heap[i];\n\t\t ws->heap[i] = t;\n\t\t i = j;\n\t\t}\n\t else\n\t\tbreak;\n\t }\n\n\n\t}\n\n /* Otherwise, just fix-up the heap. */\n else\n\t{\n\t i = 0;\n\t while (2 * i + 1 < nivals)\n\t {\n\t j = 2 * i + 1;\n\t if (j + 1 < nivals\n\t\t && ws->ivals[ws->heap[j + 1]].err >=\n\t\t ws->ivals[ws->heap[j]].err)\n\t\tj++;\n\t if (ws->ivals[ws->heap[j]].err <= ws->ivals[ws->heap[i]].err)\n\t\tbreak;\n\t else\n\t\t{\n\t\t t = ws->heap[j];\n\t\t ws->heap[j] = ws->heap[i];\n\t\t ws->heap[i] = t;\n\t\t i = j;\n\t\t}\n\t }\n\n\t}\n\n /* If the heap is about to overflow, remove the last two\n intervals. */\n while (nivals > ws->size - 2)\n\t{\n\t iv = &(ws->ivals[ws->heap[nivals - 1]]);\n\n/* printf\n (\"cquad: dumping ival %i (of %i) with [%e,%e] int=%e, err=%e, depth=%i\\n\",\n ws->heap[0], nivals, iv->a, iv->b, iv->igral, iv->err,\n iv->depth);\n*/\n\t err_final += iv->err;\n\t igral_final += iv->igral;\n\t nivals--;\n\t}\n\n /* Collect the value of the integral and error. */\n igral = igral_final;\n err = err_final;\n for (i = 0; i < nivals; i++)\n\t{\n\t igral += ws->ivals[ws->heap[i]].igral;\n\t err += ws->ivals[ws->heap[i]].err;\n\t}\n\n }\n\n /* Dump the contents of the heap. */\n/* for (i = 0; i < nivals; i++)\n {\n iv = &(ws->ivals[ws->heap[i]]);\n printf\n (\"cquad: ival %i (%i) with [%e,%e], int=%e, err=%e, depth=%i, rdepth=%i\\n\",\n i, ws->heap[i], iv->a, iv->b, iv->igral, iv->err, iv->depth,\n iv->rdepth);\n }\n*/\n /* Clean up and present the results. */\n *result = igral;\n if (abserr != NULL)\n *abserr = err;\n if (nevals != NULL)\n *nevals = neval;\n\n /* All is well that ends well. */\n return GSL_SUCCESS;\n\n}\n", "meta": {"hexsha": "da96b93879b42eb655f67520d93d89e1639d0bb1", "size": 16355, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/integration/cquad.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/integration/cquad.c", "max_issues_repo_name": "ruslankuzmin/julia", "max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/integration/cquad.c", "max_forks_repo_name": "ruslankuzmin/julia", "max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "avg_line_length": 23.9108187135, "max_line_length": 86, "alphanum_fraction": 0.4995414246, "num_tokens": 5931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190477, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4055860471317493}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n//#include \r\n#ifndef _HEART_H\r\n#define _HEART_H\r\n\r\n\r\nclass heart\r\n{\r\nprivate:\r\n\tint L; //sytem size length for now square\r\n\r\n\tstd::vector> state; //value indicates whether in excited state refactory or resting\r\n\tstd::vector> new_state; //using new_state and state to distinguish newly excited cells from previously excited\r\n\tstd::vector> functional; //1 if functional 0 if disfunctional\r\n\tstd::vector> bond; //1 if bond to site above current cell, 0 if no bond above site\r\n\tstd::vector> last_excited;\r\n\tstd::vector> last_excited_counter; // have a dummy counter so as to not interfere with APD dynamics\r\n\tstd::vector> refractory;\r\n\tstd::vector> total_rest; //have counter for total time cells spend in rest or refractory \r\n\r\n\r\n\r\n\tint heart_time; //internal clock\r\n\t//model parameters \r\n\tint tau; //refactory period\r\n\tint T; // pacemaker rate\r\n\tdouble nu, epsilom, delta; //probability vertical connection exists, probability of misfire given faulty and probability cell faulty \r\n\r\n\t//random number generator \r\n\tconst gsl_rng_type*Type;\r\n\tgsl_rng*r;\r\n\r\n\tint total_bonds;\r\n\tint total_functional;\r\n\tint total_excited;\r\n\tdouble refractory_period;\r\n\r\npublic:\r\n\r\n\theart()\r\n\t{\r\n\r\n\t}\r\n\theart(int _L, int _T, int _tau, double _nu, double _epsilom, double _delta)\r\n\t{\r\n\r\n\t\trefractory_period =0;\r\n\t\tL = _L;\r\n\t\tnu = _nu;\r\n\t\ttau = _tau;\r\n\t\tT = _T;\r\n\t\tepsilom = _epsilom;\r\n\t\tdelta = _delta;\r\n\r\n\t\theart_time = T;\r\n\r\n\t\tstate.resize(L);\r\n\t\tnew_state.resize(L);\r\n\t\tfunctional.resize(L);\r\n\t\tbond.resize(L);\r\n\t\tlast_excited.resize(L);\r\n\t\tlast_excited_counter.resize(L);\r\n\t\trefractory.resize(L);\r\n\t\ttotal_rest.resize(L);\r\n\t\t//pacemaker action\r\n\t\tfor (unsigned i = 0; idelta);// inequality reversed\r\n\t\t\t\t//double x = gsl_rng_uniform(r);\r\n\t\t\t\t//\tstd::cout <0) + (L - 1)*(i<1)][j] += (new_state[(i - 1)*(i>0) + (L - 1)*(i<1)][j]<1)*(state[(i - 1)*(i>0) + (L - 1)*(i<1)][j]<1)*bond[(i - 1)*(i>0) + (L - 1)*(i<1)][j] * (1 - (1 - functional[(i - 1)*(i>0) + (L - 1)*(i<1)][j])*(gsl_rng_uniform(r)0)] += (new_state[i][(j - 1)*(j>0)]<1)*(j>0)*(state[i][(j - 1)*(j>0)]<1)*(1 - (1 - functional[i][(j - 1)*(j>0)])*(gsl_rng_uniform(r)> next_excited_cells;\r\n\r\n\t\t//evolving cells that were not excited previously or now (some subtlty to those possibly excited now)\r\n\t\tfor (int i = 0; i0);\r\n\t\t\t\t//if state was excited or refactory before +1 states that were resting may have been newly excited or not but this ignores them\r\n\t\t\t\tnew_state[i][j] *= (state[i][j]1);//counts if not excited\r\n\t\t\t\tlast_excited[i][j] *= (state[i][j] < 1) + (state[i][j]>1); //cycles back to 0 if excited; old states so don't put lastexcited to 0 before calculating new refractory\r\n\t\t\t\tlast_excited_counter[i][j] += (state[i][j] < 1) + (state[i][j]>1);//dummy counter\r\n\t\t\t\tlast_excited_counter[i][j] *= (state[i][j] < 1) + (state[i][j]>1); //dummy counter\r\n\t\t\t\trefractory_period += refractory[i][j];\r\n\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//SAN \r\n\t\tfor (int i = 0; iT - 1)*(1 - (1 - functional[i][0])*(gsl_rng_uniform(r)T - 1);\r\n\r\n\t\t}\r\n\r\n\t\theart_time++;\r\n\t\theart_time *= (heart_time1);\r\n\t\t//return state[i][j]/(1.0*T);\r\n\r\n\t}\r\n\tint restitution(int i, int j)\r\n\t{\r\n\t\t//some function of tau T and last_excited[i][j]\r\n\t\tif (last_excited[i][j] < T)\r\n\t\t{\r\n\t\t\t//return floor((1 - exp(-4.0*last_excited[i][j] / (1.0*T)))*tau);\r\n\t\t\treturn tau;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn tau;\r\n\t\t}\r\n\t\t//if T since excited should be approx tau \r\n\t\t//if less shoud be less than tau\r\n\r\n\r\n\t}\r\n\tdouble get_avg_refractory()\r\n\t{\r\n\r\n\t\treturn refractory_period/(L*L);\r\n\t}\r\n};\r\n#endif", "meta": {"hexsha": "a6887fe400314672933bcec1baed2d7ae05abddd", "size": 7721, "ext": "h", "lang": "C", "max_stars_repo_path": "standard model + apd 100% working/heart_james.h", "max_stars_repo_name": "pm2111/Heart-Defibrillation-Project", "max_stars_repo_head_hexsha": "48ea3570c360aac7c3ff46354891998f4f364fab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "standard model + apd 100% working/heart_james.h", "max_issues_repo_name": "pm2111/Heart-Defibrillation-Project", "max_issues_repo_head_hexsha": "48ea3570c360aac7c3ff46354891998f4f364fab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "standard model + apd 100% working/heart_james.h", "max_forks_repo_name": "pm2111/Heart-Defibrillation-Project", "max_forks_repo_head_hexsha": "48ea3570c360aac7c3ff46354891998f4f364fab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3860294118, "max_line_length": 272, "alphanum_fraction": 0.606398135, "num_tokens": 2511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.40556973161871274}} {"text": "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n#include \n#include \n\n#include \n\n#ifdef __INTEL_COMPILER\n#include \n#else\n#include \n#define kmp_set_blocktime(k) \n#endif\n\nstatic inline float minf (float a, float b) { return a < b ? a : b; }\nstatic inline float maxf (float a, float b) { return a < b ? b : a; }\n\n\nPyObject * compute_overlap (float bbx1, float bby1, float bbx2, float bby2,\n int fdimy, int fdimx, int dimy, int dimx,\n float scale, int pady, int padx, int h, int w) {\n int im_area = h*w;\n int bbox_area = (bbx2-bbx1)*(bby2-bby1);\n int im_clip = ((double)bbox_area / (double)im_area) < 0.7;\n npy_intp dims[2] = { dimy, dimx };\n int x, y;\n\n PyArrayObject * pyoverlap = (PyArrayObject*)PyArray_SimpleNew ((npy_intp)2, dims, NPY_FLOAT);\n\n for (x = 0; x < dimx; ++x) {\n for (y = 0; y < dimy; ++y) {\n float x1 = (x - padx) * scale;\n float y1 = (y - pady) * scale;\n float x2 = x1 + fdimx*scale - 1;\n float y2 = y1 + fdimy*scale - 1;\n\n if (im_clip) {\n x1 = minf(maxf(x1, 0.0f), w-1);\n y1 = minf(maxf(y1, 0.0f), h-1);\n x2 = minf(maxf(x2, 0.0f), w-1);\n y2 = minf(maxf(y2, 0.0f), h-1);\n }\n\n float xx1 = maxf(x1, bbx1);\n float yy1 = maxf(y1, bby1);\n float xx2 = minf(x2, bbx2);\n float yy2 = minf(y2, bby2);\n\n float intw = xx2 - xx1 + 1;\n float inth = yy2 - yy1 + 1;\n\n if (intw > 0 && inth > 0) {\n float filterw = x2 - x1 + 1;\n float filterh = y2 - y1 + 1;\n float filter_area = filterw*filterh;\n float int_area = intw*inth;\n float union_area = filter_area + bbox_area - int_area;\n\n *(float*)PyArray_GETPTR2(pyoverlap, y, x) = int_area / union_area;\n } else {\n *(float*)PyArray_GETPTR2(pyoverlap, y, x) = 0;\n }\n }\n }\n\n return Py_BuildValue(\"N\", pyoverlap);\n}\n\n#if 0\nPyObject * objective_function (PyObject * pyexamples) {\n int i;\n int j;\n int k;\n\n for (i = 0; i < PyList_Size(pyexamples); ++i) {\n PyObject * pyexample = PyList_GetItem (pyexamples, i);\n if (!PyList_Check(pyexample)) {\n PyErr_SetString(PyExc_TypeError, \"example list elements must be list.\");\n return NULL;\n }\n\n for (j = 0; j < PyList_Size(pyexample); ++j) {\n\n PyObject * pyentry = PyList_GetItem(pyexample, j);\n if (!PyTuple_Check(pyentry)) {\n PyErr_SetString(PyExc_TypeError, \"entries must be tuples.\");\n return NULL;\n }\n\n if (PyTuple_Size(pyentry) != 2) {\n PyErr_SetString(PyExc_TypeError, \"entry tuples must be of size 2\");\n return NULL;\n }\n\n PyObject * pyfeatures = PyTuple_GetItem(pyentry, 0);\n if (!PyDict_Check(pyfeatures)) {\n PyErr_SetString(PyExc_TypeError, \"features must be a dict\");\n return NULL;\n }\n\n PyObject * pyfeatureslist = PyDict_Items(pyfeatures);\n\n float score = 0;\n for (k = 0; k < PyDict_Size(pyfeatureslist); ++k) {\n PyObject * pyfeature = PyList_GetItem(pyfeatureslist, k);\n PyObject * pyblock = PyTuple_GetItem(pyfeature, 0);\n\n PyObject * pyw = PyTuple_GetItem(pyfeature, 1);\n if (!PyArray_Check(pyw)) {\n PyErr_SetString(PyExc_TypeError, \"w must be a numpy array\");\n return NULL;\n }\n\n PyArrayObject * pywarray = (PyArrayObject*)pyw;\n\n \n }\n\n PyObject * pydetection = PyTuple_GetItem(pyentry, 1);\n }\n }\n return Py_BuildValue(\"i\", 0);\n}\n\nPyObject * gradient (PyObject * examples, PyObject * gradients) {\n Py_RETURN_NONE;\n}\n#endif\n\nstatic PyObject * ComputeOverlap(PyObject * self, PyObject * args)\n{\n float x1, x2, y1, y2;\n int fdimy, fdimx, dimy, dimx;\n float scale;\n int pady, padx;\n int w, h;\n if (!PyArg_ParseTuple(args, \"ffffiiiifiiii\", &x1, &y1, &x2, &y2, &fdimy, &fdimx, &dimy, &dimx, &scale, &pady, &padx, &h, &w)) \n return NULL;\n return compute_overlap(x1, y1, x2, y2, fdimy, fdimx, dimy, dimx, scale, pady, padx, h, w);\n}\n\n#if 0\nstatic PyObject * ObjectiveFunction (PyObject * self, PyObject * args) {\n PyObject * pyexamples;\n if (!PyArg_ParseTuple (args, \"O!\", &PyList_Type, &pyexamples)) {\n return NULL;\n }\n\n return objective_function (pyexamples);\n}\n\nstatic PyObject * Gradient (PyObject * self, PyObject * args) {\n PyObject * pyexamples;\n PyObject * pygradients;\n if (!PyArg_ParseTuple (args, \"O!O!\", &PyList_Type, &pyexamples, &PyDict_Type, &pygradients)) {\n return NULL;\n }\n\n return gradient (pyexamples, pygradients);\n}\n#endif\n\n#if PY_MAJOR_VERSION >= 3\nstatic struct PyModuleDef moduledef = {\n PyModuleDef_HEAD_INIT,\n \"_train\",\n \"Routines for training the DPM.\",\n -1,\n NULL,\n NULL,\n NULL,\n NULL,\n NULL\n};\n#endif\n\n#if PY_MAJOR_VERSION < 3\nstatic PyMethodDef _train_methods[] = {\n {\"compute_overlap\", ComputeOverlap, METH_VARARGS, \"Compute detection overlaps with bbox.\"},\n#if 0\n {\"ObjectiveFunction\", ObjectiveFunction, METH_VARARGS, \"WL-SSVM objective function.\"},\n {\"Gradient\", Gradient, METH_VARARGS, \"WL-SSVM gradient.\"},\n#endif\n {NULL}\n};\n#endif\n\n#if PY_MAJOR_VERSION >= 3\nPyMODINIT_FUNC\nPyInit__train(void)\n#else\nPyMODINIT_FUNC\ninit_train(void)\n#endif\n{\n import_array();\n\n#if PY_MAJOR_VERSION >= 3\n PyObject *m = PyModule_Create(&moduledef);\n#else\n Py_InitModule3(\"_train\", _train_methods, \"Compute detection overlaps with bbox.\");\n#endif\n\n#if PY_MAJOR_VERSION >= 3\n return m;\n#endif\n}\n", "meta": {"hexsha": "dd2656065d494b60a13a0697e645be124e8406b0", "size": 5958, "ext": "c", "lang": "C", "max_stars_repo_path": "src/pydro/_train.c", "max_stars_repo_name": "caomw/pydro", "max_stars_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T23:41:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-24T01:25:25.000Z", "max_issues_repo_path": "src/pydro/_train.c", "max_issues_repo_name": "caomw/pydro", "max_issues_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-06T07:54:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-06T07:54:15.000Z", "max_forks_repo_path": "src/pydro/_train.c", "max_forks_repo_name": "kmatzen/pydro", "max_forks_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-08-20T14:21:54.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-30T07:30:11.000Z", "avg_line_length": 28.7826086957, "max_line_length": 130, "alphanum_fraction": 0.5689828802, "num_tokens": 1692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.40556973161871274}} {"text": "/* blas/gsl_blas.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/*\n * Author: G. Jungman\n */\n#ifndef __GSL_BLAS_H__\n#define __GSL_BLAS_H__\n\n#include \n#include \n\n#include \n\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n\n/* ========================================================================\n * Level 1\n * ========================================================================\n */\n\nint gsl_blas_sdsdot (float alpha,\n const gsl_vector_float * X,\n const gsl_vector_float * Y,\n float * result\n );\n\nint gsl_blas_dsdot (const gsl_vector_float * X,\n const gsl_vector_float * Y,\n double * result\n );\n\nint gsl_blas_sdot (const gsl_vector_float * X,\n const gsl_vector_float * Y,\n float * result\n );\n\nint gsl_blas_ddot (const gsl_vector * X,\n const gsl_vector * Y,\n double * result\n );\n\n\nint gsl_blas_cdotu (const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_complex_float * dotu);\n\nint gsl_blas_cdotc (const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_complex_float * dotc);\n\nint gsl_blas_zdotu (const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_complex * dotu);\n\nint gsl_blas_zdotc (const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_complex * dotc);\n\n\nfloat gsl_blas_snrm2 (const gsl_vector_float * X);\nfloat gsl_blas_sasum (const gsl_vector_float * X);\ndouble gsl_blas_dnrm2 (const gsl_vector * X);\ndouble gsl_blas_dasum (const gsl_vector * X);\nfloat gsl_blas_scnrm2 (const gsl_vector_complex_float * X);\nfloat gsl_blas_scasum (const gsl_vector_complex_float * X);\ndouble gsl_blas_dznrm2 (const gsl_vector_complex * X);\ndouble gsl_blas_dzasum (const gsl_vector_complex * X);\n\n\nCBLAS_INDEX_t gsl_blas_isamax (const gsl_vector_float * X);\nCBLAS_INDEX_t gsl_blas_idamax (const gsl_vector * X);\nCBLAS_INDEX_t gsl_blas_icamax (const gsl_vector_complex_float * X);\nCBLAS_INDEX_t gsl_blas_izamax (const gsl_vector_complex * X);\n\n\nint gsl_blas_sswap (gsl_vector_float * X,\n gsl_vector_float * Y);\n\nint gsl_blas_scopy (const gsl_vector_float * X,\n gsl_vector_float * Y);\n\nint gsl_blas_saxpy (float alpha,\n const gsl_vector_float * X,\n gsl_vector_float * Y);\n\nint gsl_blas_dswap (gsl_vector * X,\n gsl_vector * Y);\n\nint gsl_blas_dcopy (const gsl_vector * X,\n gsl_vector * Y);\n\nint gsl_blas_daxpy (double alpha,\n const gsl_vector * X,\n gsl_vector * Y);\n\nint gsl_blas_cswap (gsl_vector_complex_float * X,\n gsl_vector_complex_float * Y);\n\nint gsl_blas_ccopy (const gsl_vector_complex_float * X,\n gsl_vector_complex_float * Y);\n\nint gsl_blas_caxpy (const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n gsl_vector_complex_float * Y);\n\nint gsl_blas_zswap (gsl_vector_complex * X,\n gsl_vector_complex * Y);\n\nint gsl_blas_zcopy (const gsl_vector_complex * X,\n gsl_vector_complex * Y);\n\nint gsl_blas_zaxpy (const gsl_complex alpha,\n const gsl_vector_complex * X,\n gsl_vector_complex * Y);\n\n\nint gsl_blas_srotg (float a[], float b[], float c[], float s[]);\n\nint gsl_blas_srotmg (float d1[], float d2[], float b1[], float b2, float P[]);\n\nint gsl_blas_srot (gsl_vector_float * X,\n gsl_vector_float * Y,\n float c, float s);\n\nint gsl_blas_srotm (gsl_vector_float * X,\n gsl_vector_float * Y,\n const float P[]);\n\nint gsl_blas_drotg (double a[], double b[], double c[], double s[]);\n\nint gsl_blas_drotmg (double d1[], double d2[], double b1[],\n double b2, double P[]);\n\nint gsl_blas_drot (gsl_vector * X,\n gsl_vector * Y,\n const double c, const double s);\n\nint gsl_blas_drotm (gsl_vector * X,\n gsl_vector * Y,\n const double P[]);\n\n\nvoid gsl_blas_sscal (float alpha, gsl_vector_float * X);\nvoid gsl_blas_dscal (double alpha, gsl_vector * X);\nvoid gsl_blas_cscal (const gsl_complex_float alpha, gsl_vector_complex_float * X);\nvoid gsl_blas_zscal (const gsl_complex alpha, gsl_vector_complex * X);\nvoid gsl_blas_csscal (float alpha, gsl_vector_complex_float * X);\nvoid gsl_blas_zdscal (double alpha, gsl_vector_complex * X);\n\n\n/* ===========================================================================\n * Level 2\n * ===========================================================================\n */\n\n/*\n * Routines with standard 4 prefixes (S, D, C, Z)\n */\nint gsl_blas_sgemv (CBLAS_TRANSPOSE_t TransA,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_vector_float * X,\n float beta,\n gsl_vector_float * Y);\n\nint gsl_blas_strmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_float * A,\n gsl_vector_float * X);\n\nint gsl_blas_strsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_float * A,\n gsl_vector_float * X);\n\nint gsl_blas_dgemv (CBLAS_TRANSPOSE_t TransA,\n double alpha,\n const gsl_matrix * A,\n const gsl_vector * X,\n double beta,\n gsl_vector * Y);\n\nint gsl_blas_dtrmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix * A,\n gsl_vector * X);\n\nint gsl_blas_dtrsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix * A,\n gsl_vector * X);\n\nint gsl_blas_cgemv (CBLAS_TRANSPOSE_t TransA,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_vector_complex_float * X,\n const gsl_complex_float beta,\n gsl_vector_complex_float * Y);\n\nint gsl_blas_ctrmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex_float * A,\n gsl_vector_complex_float * X);\n\nint gsl_blas_ctrsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex_float * A,\n gsl_vector_complex_float * X);\n\nint gsl_blas_zgemv (CBLAS_TRANSPOSE_t TransA,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_vector_complex * X,\n const gsl_complex beta,\n gsl_vector_complex * Y);\n\nint gsl_blas_ztrmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex * A,\n gsl_vector_complex * X);\n\nint gsl_blas_ztrsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex * A,\n gsl_vector_complex *X);\n\n/*\n * Routines with S and D prefixes only\n */\nint gsl_blas_ssymv (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_vector_float * X,\n float beta,\n gsl_vector_float * Y);\n\nint gsl_blas_sger (float alpha,\n const gsl_vector_float * X,\n const gsl_vector_float * Y,\n gsl_matrix_float * A);\n\nint gsl_blas_ssyr (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_vector_float * X,\n gsl_matrix_float * A);\n\nint gsl_blas_ssyr2 (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_vector_float * X,\n const gsl_vector_float * Y,\n gsl_matrix_float * A);\n\nint gsl_blas_dsymv (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_matrix * A,\n const gsl_vector * X,\n double beta,\n gsl_vector * Y);\nint gsl_blas_dger (double alpha,\n const gsl_vector * X,\n const gsl_vector * Y,\n gsl_matrix * A);\n\nint gsl_blas_dsyr (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_vector * X,\n gsl_matrix * A);\n\nint gsl_blas_dsyr2 (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_vector * X,\n const gsl_vector * Y,\n gsl_matrix * A);\n\n/*\n * Routines with C and Z prefixes only\n */\n\nint gsl_blas_chemv (CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_vector_complex_float * X,\n const gsl_complex_float beta,\n gsl_vector_complex_float * Y);\n\nint gsl_blas_cgeru (const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_matrix_complex_float * A);\n\nint gsl_blas_cgerc (const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_matrix_complex_float * A);\n\nint gsl_blas_cher (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_vector_complex_float * X,\n gsl_matrix_complex_float * A);\n\nint gsl_blas_cher2 (CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_matrix_complex_float * A);\n\nint gsl_blas_zhemv (CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_vector_complex * X,\n const gsl_complex beta,\n gsl_vector_complex * Y);\n\nint gsl_blas_zgeru (const gsl_complex alpha,\n const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_matrix_complex * A);\n\nint gsl_blas_zgerc (const gsl_complex alpha,\n const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_matrix_complex * A);\n\nint gsl_blas_zher (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_vector_complex * X,\n gsl_matrix_complex * A);\n\nint gsl_blas_zher2 (CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_matrix_complex * A);\n\n/*\n * ===========================================================================\n * Prototypes for level 3 BLAS\n * ===========================================================================\n */\n\n/*\n * Routines with standard 4 prefixes (S, D, C, Z)\n */\nint gsl_blas_sgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_matrix_float * B,\n float beta,\n gsl_matrix_float * C);\n\nint gsl_blas_ssymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_matrix_float * B,\n float beta,\n gsl_matrix_float * C);\n\nint gsl_blas_ssyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans,\n float alpha,\n const gsl_matrix_float * A,\n float beta,\n gsl_matrix_float * C);\n\nint gsl_blas_ssyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_matrix_float * B,\n float beta,\n gsl_matrix_float * C);\n\nint gsl_blas_strmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n float alpha,\n const gsl_matrix_float * A,\n gsl_matrix_float * B);\n\nint gsl_blas_strsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n float alpha,\n const gsl_matrix_float * A,\n gsl_matrix_float * B);\n\nint gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n double alpha,\n const gsl_matrix * A,\n const gsl_matrix * B,\n double beta,\n gsl_matrix * C);\n\nint gsl_blas_dsymm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_matrix * A,\n const gsl_matrix * B,\n double beta,\n gsl_matrix * C);\n\nint gsl_blas_dsyrk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n double alpha,\n const gsl_matrix * A,\n double beta,\n gsl_matrix * C);\n\nint gsl_blas_dsyr2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n double alpha,\n const gsl_matrix * A,\n const gsl_matrix * B,\n double beta,\n gsl_matrix * C);\n\nint gsl_blas_dtrmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n double alpha,\n const gsl_matrix * A,\n gsl_matrix * B);\n\nint gsl_blas_dtrsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n double alpha,\n const gsl_matrix * A,\n gsl_matrix * B);\n\nint gsl_blas_cgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nint gsl_blas_csymm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nint gsl_blas_csyrk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nint gsl_blas_csyr2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nint gsl_blas_ctrmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n gsl_matrix_complex_float * B);\n\nint gsl_blas_ctrsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n gsl_matrix_complex_float * B);\n\nint gsl_blas_zgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nint gsl_blas_zsymm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nint gsl_blas_zsyrk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nint gsl_blas_zsyr2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex *C);\n\nint gsl_blas_ztrmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n gsl_matrix_complex * B);\n\nint gsl_blas_ztrsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n gsl_matrix_complex * B);\n\n/*\n * Routines with prefixes C and Z only\n */\nint gsl_blas_chemm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nint gsl_blas_cherk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n float alpha,\n const gsl_matrix_complex_float * A,\n float beta,\n gsl_matrix_complex_float * C);\n\nint gsl_blas_cher2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n float beta,\n gsl_matrix_complex_float * C);\n\nint gsl_blas_zhemm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nint gsl_blas_zherk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n double alpha,\n const gsl_matrix_complex * A,\n double beta,\n gsl_matrix_complex * C);\n\nint gsl_blas_zher2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n double beta,\n gsl_matrix_complex * C);\n\n\n__END_DECLS\n\n#endif /* __GSL_BLAS_H__ */\n", "meta": {"hexsha": "82ecd674edf26adf4fa7abe7374e155d5dc224a3", "size": 21913, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl_subset/blas/gsl_blas.h", "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_issues_repo_path": "gsl_subset/blas/gsl_blas.h", "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_forks_repo_path": "gsl_subset/blas/gsl_blas.h", "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "avg_line_length": 36.3399668325, "max_line_length": 83, "alphanum_fraction": 0.5298681148, "num_tokens": 4679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.40544191343510666}} {"text": "/* monte/test.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#define CONSTANT\n#define PRODUCT\n#define GAUSSIAN\n#define DBLGAUSSIAN\n#define TSUDA\n\n#define PLAIN\n#define MISER\n#define VEGAS\n\ndouble xl[11] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\ndouble xu[11] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };\ndouble xu2[11] = { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };\ndouble xu3[2] = { GSL_DBL_MAX, GSL_DBL_MAX };\n\ndouble fconst (double x[], size_t d, void *params);\ndouble f0 (double x[], size_t d, void *params);\ndouble f1 (double x[], size_t d, void *params);\ndouble f2 (double x[], size_t d, void *params);\ndouble f3 (double x[], size_t d, void *params);\n\nvoid my_error_handler (const char *reason, const char *file,\n\t\t int line, int err);\n\nstruct problem {\n gsl_monte_function * f;\n double * xl;\n double * xu;\n size_t dim;\n size_t calls;\n double expected_result;\n double expected_error;\n char * description;\n} ;\n\ngsl_monte_function \nmake_function (double (*f)(double *, size_t, void *), size_t d, void * p);\n\ngsl_monte_function \nmake_function (double (*f)(double *, size_t, void *), size_t d, void * p)\n{\n gsl_monte_function f_new;\n\n f_new.f = f;\n f_new.dim = d;\n f_new.params = p;\n\n return f_new;\n}\n\n\nvoid \nadd (struct problem * problems, int * n, \n gsl_monte_function * f, double xl[], double xu[], size_t dim, size_t calls,\n double result, double err, char * description);\n\nvoid \nadd (struct problem * problems, int * n, \n gsl_monte_function * f, double xl[], double xu[], size_t dim, size_t calls,\n double result, double err, char * description)\n{\n int i = *n;\n problems[i].f = f;\n problems[i].xl = xl;\n problems[i].xu = xu;\n problems[i].dim = dim;\n problems[i].calls = calls;\n problems[i].expected_result = result;\n problems[i].expected_error = err;\n problems[i].description = description;\n (*n)++;\n}\n\n#define TRIALS 10\n\nint\nmain (void)\n{\n double result[TRIALS], error[TRIALS];\n double a = 0.1;\n double c = (1.0 + sqrt (10.0)) / 9.0;\n\n gsl_monte_function Fc = make_function(&fconst, 0, 0);\n gsl_monte_function F0 = make_function(&f0, 0, &a);\n gsl_monte_function F1 = make_function(&f1, 0, &a);\n gsl_monte_function F2 = make_function(&f2, 0, &a);\n gsl_monte_function F3 = make_function(&f3, 0, &c);\n\n /* The relationship between the variance of the function itself, the\n error on the integral and the number of calls is,\n\n sigma = sqrt(variance/N)\n\n where the variance is the <(f - )^2> where <.> denotes the\n volume average (integral over the integration region divided by\n the volume) */\n\n int n = 0;\n struct problem * I;\n struct problem problems[256];\n\n#ifdef CONSTANT\n /* variance(Fc) = 0 */\n\n add(problems,&n, &Fc, xl, xu, 1, 1000, 1.0, 0.0, \"constant, 1d\");\n add(problems,&n, &Fc, xl, xu, 2, 1000, 1.0, 0.0, \"constant, 2d\");\n add(problems,&n, &Fc, xl, xu, 3, 1000, 1.0, 0.0, \"constant, 3d\");\n add(problems,&n, &Fc, xl, xu, 4, 1000, 1.0, 0.0, \"constant, 4d\");\n add(problems,&n, &Fc, xl, xu, 5, 1000, 1.0, 0.0, \"constant, 5d\");\n add(problems,&n, &Fc, xl, xu, 6, 1000, 1.0, 0.0, \"constant, 6d\");\n add(problems,&n, &Fc, xl, xu, 7, 1000, 1.0, 0.0, \"constant, 7d\");\n add(problems,&n, &Fc, xl, xu, 8, 1000, 1.0, 0.0, \"constant, 8d\");\n add(problems,&n, &Fc, xl, xu, 9, 1000, 1.0, 0.0, \"constant, 9d\");\n add(problems,&n, &Fc, xl, xu, 10, 1000, 1.0, 0.0, \"constant, 10d\");\n#endif\n\n#ifdef PRODUCT\n /* variance(F0) = (4/3)^d - 1 */\n\n add(problems,&n, &F0, xl, xu, 1, 3333, 1.0, 0.01, \"product, 1d\" );\n add(problems,&n, &F0, xl, xu, 2, 7777, 1.0, 0.01, \"product, 2d\" );\n add(problems,&n, &F0, xl, xu, 3, 13703, 1.0, 0.01, \"product, 3d\" );\n add(problems,&n, &F0, xl, xu, 4, 21604, 1.0, 0.01, \"product, 4d\" );\n add(problems,&n, &F0, xl, xu, 5, 32139, 1.0, 0.01, \"product, 5d\" );\n add(problems,&n, &F0, xl, xu, 6, 46186, 1.0, 0.01, \"product, 6d\" );\n add(problems,&n, &F0, xl, xu, 7, 64915, 1.0, 0.01, \"product, 7d\" );\n add(problems,&n, &F0, xl, xu, 8, 89887, 1.0, 0.01, \"product, 8d\" );\n add(problems,&n, &F0, xl, xu, 9, 123182, 1.0, 0.01, \"product, 9d\" );\n add(problems,&n, &F0, xl, xu, 10, 167577, 1.0, 0.01, \"product, 10d\" );\n#endif\n\n#ifdef GAUSSIAN\n /* variance(F1) = (1/(a sqrt(2 pi)))^d - 1 */\n\n add(problems,&n, &F1, xl, xu, 1, 298, 1.0, 0.1, \"gaussian, 1d\" );\n add(problems,&n, &F1, xl, xu, 2, 1492, 1.0, 0.1, \"gaussian, 2d\" );\n add(problems,&n, &F1, xl, xu, 3, 6249, 1.0, 0.1, \"gaussian, 3d\" );\n add(problems,&n, &F1, xl, xu, 4, 25230, 1.0, 0.1, \"gaussian, 4d\" );\n add(problems,&n, &F1, xl, xu, 5, 100953, 1.0, 0.1, \"gaussian, 5d\" );\n add(problems,&n, &F1, xl, xu, 6, 44782, 1.0, 0.3, \"gaussian, 6d\" );\n add(problems,&n, &F1, xl, xu, 7, 178690, 1.0, 0.3, \"gaussian, 7d\" );\n add(problems,&n, &F1, xl, xu, 8, 712904, 1.0, 0.3, \"gaussian, 8d\" );\n add(problems,&n, &F1, xl, xu, 9, 2844109, 1.0, 0.3, \"gaussian, 9d\" );\n add(problems,&n, &F1, xl, xu, 10, 11346390, 1.0, 0.3, \"gaussian, 10d\" );\n#endif\n\n#ifdef DBLGAUSSIAN\n /* variance(F2) = 0.5 * (1/(a sqrt(2 pi)))^d - 1 */\n\n add(problems,&n, &F2, xl, xu, 1, 9947, 1.0, 0.01, \"double gaussian, 1d\" );\n add(problems,&n, &F2, xl, xu, 2, 695, 1.0, 0.1, \"double gaussian, 2d\" );\n add(problems,&n, &F2, xl, xu, 3, 3074, 1.0, 0.1, \"double gaussian, 3d\" );\n add(problems,&n, &F2, xl, xu, 4, 12565, 1.0, 0.1, \"double gaussian, 4d\" );\n add(problems,&n, &F2, xl, xu, 5, 50426, 1.0, 0.1, \"double gaussian, 5d\" );\n add(problems,&n, &F2, xl, xu, 6, 201472, 1.0, 0.1, \"double gaussian, 6d\" );\n add(problems,&n, &F2, xl, xu, 7, 804056, 1.0, 0.1, \"double gaussian, 7d\" );\n add(problems,&n, &F2, xl, xu, 8, 356446, 1.0, 0.3, \"double gaussian, 8d\" );\n add(problems,&n, &F2, xl, xu, 9, 1422049, 1.0, 0.3, \"double gaussian, 9d\" );\n add(problems,&n, &F2, xl, xu, 10, 5673189, 1.0, 0.3, \"double gaussian, 10d\" );\n#endif\n\n#ifdef TSUDA\n /* variance(F3) = ((c^2 + c + 1/3)/(c(c+1)))^d - 1 */\n\n add(problems,&n, &F3, xl, xu, 1, 4928, 1.0, 0.01, \"tsuda function, 1d\" );\n add(problems,&n, &F3, xl, xu, 2, 12285, 1.0, 0.01, \"tsuda function, 2d\" );\n add(problems,&n, &F3, xl, xu, 3, 23268, 1.0, 0.01, \"tsuda function, 3d\" );\n add(problems,&n, &F3, xl, xu, 4, 39664, 1.0, 0.01, \"tsuda function, 4d\" );\n add(problems,&n, &F3, xl, xu, 5, 64141, 1.0, 0.01, \"tsuda function, 5d\" );\n add(problems,&n, &F3, xl, xu, 6, 100680, 1.0, 0.01, \"tsuda function, 6d\" );\n add(problems,&n, &F3, xl, xu, 7, 155227, 1.0, 0.01, \"tsuda function, 7d\" );\n add(problems,&n, &F3, xl, xu, 8, 236657, 1.0, 0.01, \"tsuda function, 8d\" );\n add(problems,&n, &F3, xl, xu, 9, 358219, 1.0, 0.01, \"tsuda function, 9d\" );\n add(problems,&n, &F3, xl, xu, 10, 539690, 1.0, 0.01, \"tsuda function, 10d\" );\n#endif\n\n add(problems,&n, 0, 0, 0, 0, 0, 0, 0, 0 );\n\n\n /* gsl_set_error_handler (&my_error_handler); */\n gsl_ieee_env_setup ();\n gsl_rng_env_setup ();\n\n#ifdef A\n printf (\"testing allocation/input checks\\n\");\n\n status = gsl_monte_plain_validate (s, xl, xu3, 1, 1);\n gsl_test (status != 0, \"error if limits too large\");\n status = gsl_monte_plain_validate (s, xl, xu, 0, 10);\n gsl_test (status != 0, \"error if num_dim = 0\");\n status = gsl_monte_plain_validate (s, xl, xu, 1, 0);\n gsl_test (status != 0, \"error if calls = 0\");\n status = gsl_monte_plain_validate (s, xu, xl, 1, 10);\n gsl_test (status != 0, \"error if xu < xl\");\n#endif\n\n#ifdef PLAIN\n#define NAME \"plain\"\n#define MONTE_STATE gsl_monte_plain_state\n#define MONTE_ALLOC gsl_monte_plain_alloc\n#define MONTE_INTEGRATE gsl_monte_plain_integrate\n#define MONTE_FREE gsl_monte_plain_free\n#define MONTE_SPEEDUP 1\n#define MONTE_ERROR_TEST(err,expected) gsl_test_factor(err,expected, 5.0, NAME \", %s, abserr[%d]\", I->description, i)\n#include \"test_main.c\"\n#undef NAME\n#undef MONTE_STATE\n#undef MONTE_ALLOC\n#undef MONTE_INTEGRATE\n#undef MONTE_FREE\n#undef MONTE_ERROR_TEST\n#undef MONTE_SPEEDUP\n#endif\n\n#ifdef MISER\n#define NAME \"miser\"\n#define MONTE_STATE gsl_monte_miser_state\n#define MONTE_ALLOC gsl_monte_miser_alloc\n#define MONTE_INTEGRATE gsl_monte_miser_integrate\n#define MONTE_FREE gsl_monte_miser_free\n#define MONTE_SPEEDUP 2\n#define MONTE_ERROR_TEST(err,expected) gsl_test(err > 5.0 * expected, NAME \", %s, abserr[%d] (obs %g vs plain %g)\", I->description, i, err, expected)\n#include \"test_main.c\"\n#undef NAME\n#undef MONTE_STATE\n#undef MONTE_ALLOC\n#undef MONTE_INTEGRATE\n#undef MONTE_FREE\n#undef MONTE_ERROR_TEST\n#undef MONTE_SPEEDUP\n#endif\n\n#ifdef VEGAS\n#define NAME \"vegas\"\n#define MONTE_STATE gsl_monte_vegas_state\n#define MONTE_ALLOC gsl_monte_vegas_alloc\n#define MONTE_INTEGRATE(f,xl,xu,dim,calls,r,s,res,err) { gsl_monte_vegas_integrate(f,xl,xu,dim,calls,r,s,res,err) ; if (s->chisq < 0.5 || s->chisq > 2) gsl_monte_vegas_integrate(f,xl,xu,dim,calls,r,s,res,err); }\n#define MONTE_FREE gsl_monte_vegas_free\n#define MONTE_SPEEDUP 3\n#define MONTE_ERROR_TEST(err,expected) gsl_test(err > 3.0 * (expected == 0 ? 1.0/(I->calls/MONTE_SPEEDUP) : expected), NAME \", %s, abserr[%d] (obs %g vs exp %g)\", I->description, i, err, expected)\n#include \"test_main.c\"\n#undef NAME\n#undef MONTE_STATE\n#undef MONTE_ALLOC\n#undef MONTE_INTEGRATE\n#undef MONTE_FREE\n#undef MONTE_ERROR_TEST\n#undef MONTE_SPEEDUP\n#endif\n \n exit (gsl_test_summary ());\n}\n\n/* Simple constant function */\ndouble\nfconst (double x[], size_t num_dim, void *params)\n{\n return 1;\n}\n\n/* Simple product function */\ndouble\nf0 (double x[], size_t num_dim, void *params)\n{\n double prod = 1.0;\n unsigned int i;\n\n for (i = 0; i < num_dim; ++i)\n {\n prod *= 2.0 * x[i];\n }\n\n return prod;\n}\n\n/* Gaussian centered at 1/2. */\n\ndouble\nf1 (double x[], size_t num_dim, void *params)\n{\n double a = *(double *)params;\n double sum = 0.;\n\n unsigned int i;\n for (i = 0; i < num_dim; i++)\n {\n double dx = x[i] - 0.5;\n sum += dx * dx;\n }\n return (pow (M_2_SQRTPI / (2. * a), (double) num_dim) *\n\t exp (-sum / (a * a)));\n}\n\n/* double gaussian */\ndouble\nf2 (double x[], size_t num_dim, void *params)\n{\n double a = *(double *)params;\n double sum1 = 0.;\n double sum2 = 0.;\n\n unsigned int i;\n for (i = 0; i < num_dim; i++)\n {\n double dx1 = x[i] - 1. / 3.;\n double dx2 = x[i] - 2. / 3.;\n sum1 += dx1 * dx1;\n sum2 += dx2 * dx2;\n }\n return 0.5 * pow (M_2_SQRTPI / (2. * a), num_dim) \n * (exp (-sum1 / (a * a)) + exp (-sum2 / (a * a)));\n}\n\n/* Tsuda's example */\ndouble\nf3 (double x[], size_t num_dim, void *params)\n{\n double c = *(double *)params;\n\n double prod = 1.;\n\n unsigned int i;\n\n for (i = 0; i < num_dim; i++)\n {\n prod *= c / (c + 1) * pow((c + 1) / (c + x[i]), 2.0);\n }\n\n return prod;\n}\n\n\nvoid\nmy_error_handler (const char *reason, const char *file, int line, int err)\n{\n if (0)\n printf (\"(caught [%s:%d: %s (%d)])\\n\", file, line, reason, err);\n}\n", "meta": {"hexsha": "2c2da55dfc3986af84ef189de33db9e480bda6e5", "size": 11933, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/monte/test.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/monte/test.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/monte/test.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 31.9064171123, "max_line_length": 211, "alphanum_fraction": 0.6195424453, "num_tokens": 4732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.4054419085240929}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"core_allvars.h\"\n#include \"model_dust.h\"\n#include \"model_misc.h\"\n\ndouble integrate_arr(const double arr1[MAX_STRING_LEN], const double arr2[MAX_STRING_LEN], const int npts, const double lower_limit, const double upper_limit);\ndouble interpolate_arr(const double arr1[MAX_STRING_LEN], const double arr2[MAX_STRING_LEN], const int npts, const int xi);\ndouble compute_imf (const double m);\ndouble compute_taum (const double m);\n\nvoid produce_metals_dust(const double metallicity, const double dt, const int p, const int centralgal, const int step, struct GALAXY *galaxies)\n{\n double A = run_params.BinaryFraction;\n\n double yield;\n double yCr_snia, yFe_snia, yNi_snia;\n double yC_agb, yN_agb, yO_agb;\n double yC_sn, yO_sn, yMg_sn, ySi_sn, yS_sn, yCa_sn, yFe_sn;\n double Cr_snia, Fe_snia, Ni_snia;\n double C_agb, N_agb, O_agb;\n double C_sn, O_sn, Mg_sn, Si_sn, S_sn, Ca_sn, Fe_sn;\n double yCagb[run_params.countagb], yNagb[run_params.countagb], yOagb[run_params.countagb];\n double m_agb[run_params.countagb];\n double yCsn[run_params.countsn], yOsn[run_params.countsn], yMgsn[run_params.countsn], ySisn[run_params.countsn], ySsn[run_params.countsn], yCasn[run_params.countsn], yFesn[run_params.countsn];\n double m_sn[run_params.countsn];\n\n int i, j;\n double phi, taum, time, sfr;\n double gamma = 2.0; //to compute binary mass function for SN Ia \n double low_agb = 1; //lower limit for stars that ends up as AGB, Msun\n double low_binary = 3; //lower limit for binary star, Msun\n double up_agb = 6; //upper limit for stars that ends up as AGB, Msun\n double low_sn = run_params.msn[0]; //lower limit for stars that ends up as SN II, Msun\n double up_binary = 16; //upper limit for binary stars, Msun\n double up_sn = 40; //upper limit for stars that ends up as SN II, Msun\n double age[SNAPLEN], sfh[SNAPLEN];\n\n for (i=0; i Z_std[6]){\n\t\tsfrz = Z_std[6];}\n\n\tfor (i=0; i sfrz) {\n\t\t\tj = i;\n\t\t}\n\t}\n\n\t//double yCagb[run_params.countagb], yNagb[run_params.countagb], yOagb[run_params.countagb];\n\t//double m_agb[run_params.countagb];\n\tfor(i=0; i Z_std[6]){\n sfrz = Z_std[6];}\n\n for (i=0; i sfrz) {\n j = i;\n }\n }\n\n \tfor(i=0; i Z_std[3]){\n sfrz = Z_std[3];}\n\t\n for (i=0; i sfrz) {\n j = i;\n }\n }\n\n for(i=0; i 5.0e-2) {\n galaxies[p].MetalsColdGas += yield * dt;\n }\n else {\n galaxies[centralgal].MetalsHotGas += yield * dt;\n }\n XPRINT(galaxies[p].MetalsColdGas <= galaxies[p].ColdGas, \"metallicity = %.3f, cold gas mass = %.3e, galaxy ID = %i \\n\", galaxies[p].MetalsColdGas / galaxies[p].ColdGas, galaxies[p].ColdGas, galaxies[p].GalaxyNr);\n\n\n//mass of each element formed in each production channel, should satisfy same condition with overall metallicity\n if(galaxies[p].ColdGas > 1.0e-2) {\n Cr_snia = yCr_snia * dt;\n Fe_snia = yFe_snia * dt;\n Ni_snia = yNi_snia * dt;\n C_agb = yC_agb * dt;\n N_agb = yN_agb * dt;\n O_agb = yO_agb * dt;\n C_sn = yC_sn * dt;\n O_sn = yO_sn * dt;\n Mg_sn = yMg_sn * dt;\n Si_sn = ySi_sn * dt;\n S_sn = yS_sn * dt;\n Ca_sn = yCa_sn * dt;\n Fe_sn = yFe_sn * dt;\n\t\n\n double dustdot = 0;\n\n //produce dust\n //double dust_agb, dust_sn, dust_snia;\n double delta_agb = 0.2; //should be free parameter!! (value based on Popping et al. 2017)\n double delta_sn = 0.2; //should be free parameter!! (value based on Popping et al. 2017)\n double delta_snia = 0.15; //should be free parameter!! (value based on Popping et al. 2017)\n\n assert(dt > 0 && \"dt must be greater than 0\");\n\n /* eq 4 and eq 5 Popping et al. 2017 */\n //from AGB\n if (C_agb/O_agb > 1) {\n dustdot += delta_agb * (C_agb - 0.75*O_agb) / dt;\n }\n else {\n dustdot += delta_agb * (C_agb + N_agb + O_agb) / dt;\n }\n\n /* eq 6 Popping et al. 2017 */\n //from SN\n dustdot += delta_sn * C_sn / dt;\n dustdot += delta_sn * O_sn / dt;\n dustdot += 16 * delta_sn * (Mg_sn/24 + Si_sn/28 + S_sn/32 + Ca_sn/40 + Fe_sn/56) / dt;\n\n /* eq 6 Popping et al. 2017 */\n //from SNIa\n //printf(\"dustdot before = %f \\n\", dustdot);\n\t//dustdot += 16 * delta_snia * (Fe_snia/56) / dt;\n //dustdot += delta_snia * (Cr_snia + Ni_snia) / dt;\n\n\t//printf(\"dustdot after = %f \\n\", dustdot);\n \tgalaxies[p].ColdDust += dustdot * dt;\n\tgalaxies[p].MetalsColdGas -= dustdot * dt;\n galaxies[p].dustdotform[step] += dustdot;\n XPRINT(dustdot * dt >= 0, \"dust mass = %.3e, delta dust = %.3e, galaxy id = %i \\n\", galaxies[p].ColdDust, dustdot*dt, galaxies[p].GalaxyNr);\n\n }\n}\n\nvoid accrete_dust(const double metallicity, const double dt, const int p, const int step, struct GALAXY *galaxies) {\n//dust accretion in ISM : eq 20 Asano13\n double dustdot = 0;\n double tacc_zero = 20 * SEC_PER_MEGAYEAR / run_params.UnitTime_in_s; //should be free parameter! yr\n\n if (galaxies[p].MetalsColdGas > galaxies[p].ColdDust && metallicity > 0 ) {\n double tacc = tacc_zero * 0.02 / metallicity;\n dustdot += (1 - galaxies[p].ColdDust/galaxies[p].MetalsColdGas) * (galaxies[p].f_H2 * galaxies[p].ColdDust / tacc);\n \n galaxies[p].dustdotgrowth[step] += dustdot;\n galaxies[p].ColdDust += dustdot * dt;\n galaxies[p].MetalsColdGas -= dustdot * dt;\n XPRINT(galaxies[p].ColdDust >= 0, \"dust mass = %.3e, delta dust = %.3e, galaxy id = %i \\n\", galaxies[p].ColdDust, dustdot*dt, galaxies[p].GalaxyNr);\n }\n\n}\n\nvoid destruct_dust(const double metallicity, const double stars, const double dt, const int p, const int step, struct GALAXY *galaxies) {\n//dust destruction : Asano et al. 13\n int i;\n double sfr;\n double dustdot = 0;\n double age[SNAPLEN], sfh[SNAPLEN];\n double m_low = 8; //lower limit of stellar mass that end up as SN\n double up_binary = 16; //upper limit for binary stars, Msun\n double m_up = 40; //upper limit of stellar mass that end up as SN\n double t_low = compute_taum(m_up); //the shortest stellar lifetime that end up as SN\n double eta = 0.1; //should be free parameter, we used value adopted by Asano et al. 13\n double m_swept = 1535 * pow((metallicity/0.02 + 0.039), -0.289) * run_params.Hubble_h / 1.e10; //eq. 14 Asano et al. 13\n int count = 20;\n double mass[count], phi[count], mphi[count];\n double A = run_params.BinaryFraction;\n// double m_swept = 600 * run_params.Hubble_h / 1.e10;\n\n for (i=0; i t_low) {\n for(i=0; i 0 && \"mass of ISM swept by SN must be greater than 0\");\n\n// if (Rsn > 0 && galaxies[p].ColdGas > 0 && galaxies[p].f_HI >0) {\n if (Rsn > 0 && galaxies[p].ColdGas > 0) {\n Rsn *= run_params.UnitMass_in_g / run_params.UnitTime_in_s * SEC_PER_YEAR / SOLAR_MASS; //convert to Msun/yr \n// double tsn = galaxies[p].ColdGas * galaxies[p].f_HI/ (eta * m_swept * Rsn); //eq.12 Asano et al 13 [yr]\n double tsn = galaxies[p].ColdGas / (eta * m_swept * Rsn); //eq.12 Asano et al 13 [yr]\n tsn /= run_params.UnitTime_in_s / SEC_PER_YEAR; //back to internal unit\n// printf(\"coldgas = %.3e, dust = %.3e, m_swept = %.3e, Rsn = %.3e, tsn = %.3e, dt = %.3e Myr \\n\", galaxies[p].ColdGas, galaxies[p].ColdDust, m_swept, Rsn, tsn * run_params.UnitTime_in_s / SEC_PER_MEGAYEAR, dt * run_params.UnitTime_in_s / SEC_PER_MEGAYEAR);\n// assert(tsn > 0 && \"tsn must be greater than 0\");\n dustdot += galaxies[p].ColdDust / tsn;\n }\n\n if (galaxies[p].ColdDust - dustdot * dt > 0) {\n \t galaxies[p].dustdotdestruct[step] += dustdot;\n \t galaxies[p].ColdDust -= dustdot * dt;\n \t galaxies[p].MetalsColdGas += dustdot * dt;\n }\n else {\n\tgalaxies[p].dustdotdestruct[step] += dustdot;\n\tgalaxies[p].MetalsColdGas += galaxies[p].ColdDust;\n\tgalaxies[p].ColdDust = 0;\n }\n\n }\n}\n\n\nvoid dust_thermal_sputtering(const int gal, const double dt, struct GALAXY *galaxies) //section 3.5 Popping 2017\n{\n double adot;\n double a = 1e-5 / run_params.UnitLength_in_cm; //a = 0.1 micrometer\n double mdot = 0.0;\n\n// thermal sputtering in hot dust\n if(galaxies[gal].HotDust > 0.0 && galaxies[gal].Vvir > 0.0) {\n const double temp0 = 2e6; //in Kelvin\n const double temp = 35.9 * galaxies[gal].Vvir * galaxies[gal].Vvir; //in Kelvin \n const double gamma = 2.5;\n\n double x = -3.2e-18 / PROTONMASS / (pow(temp0/temp, gamma) + 1); //in cm^4 / g /s\n x /= run_params.UnitLength_in_cm / run_params.UnitDensity_in_cgs / run_params.UnitTime_in_s; //in internal unit\n double rho = galaxies[gal].HotGas / (4 / 3 * M_PI * galaxies[gal].Rvir * galaxies[gal].Rvir * galaxies[gal].Rvir);\n adot = rho / x;\n a -= adot * dt;\n\n assert(a > 0);\n a /= 1e-5 / run_params.UnitLength_in_cm; //in 0.1 micrometer unit\n rho *= run_params.UnitDensity_in_cgs;\n const double tau0 = 170 * SEC_PER_MEGAYEAR / run_params.UnitTime_in_s; // 0.17Gyr to internal unit\n const double tau = tau0 * (a/rho) * (pow(temp0/temp, gamma) + 1);\n mdot = galaxies[gal].HotDust / tau / 3;\n\n galaxies[gal].HotDust -= mdot * dt;\n galaxies[gal].MetalsHotGas += mdot * dt;\n }\n\n// thermal sputtering in ejected dust\n if(galaxies[gal].EjectedDust > 0.0 && galaxies[gal].Vvir > 0.0) {\n const double temp0 = 2e6; //in Kelvin\n const double temp = 35.9 * galaxies[gal].Vvir * galaxies[gal].Vvir; //in Kelvin \n const double gamma = 2.5;\n\n double x = -3.2e-18 / PROTONMASS / (pow(temp0/temp, gamma) + 1); //in cm^4 / g /s\n x /= run_params.UnitLength_in_cm / run_params.UnitDensity_in_cgs / run_params.UnitTime_in_s; //in internal unit\n double rho = galaxies[gal].EjectedMass / (4 / 3 * M_PI * galaxies[gal].Rvir * galaxies[gal].Rvir * galaxies[gal].Rvir);\n adot = rho / x;\n a -= adot * dt;\n\n assert(a > 0);\n a /= 1e-5 / run_params.UnitLength_in_cm; //in 0.1 micrometer unit\n rho *= run_params.UnitDensity_in_cgs;\n const double tau0 = 170 * SEC_PER_MEGAYEAR / run_params.UnitTime_in_s; // 0.17Gyr to internal unit\n const double tau = tau0 * (a/rho) * (pow(temp0/temp, gamma) + 1);\n mdot = galaxies[gal].EjectedDust / tau / 3;\n\n galaxies[gal].EjectedDust -= mdot * dt;\n galaxies[gal].MetalsEjectedMass += mdot * dt;\n }\n\n}\n\ndouble integrate_arr(const double arr1[MAX_STRING_LEN], const double arr2[MAX_STRING_LEN], const int npts, const double lower_limit, const double upper_limit)\n{\n double Q;\n gsl_interp_accel *acc;\n gsl_spline *spl;\n\n acc = gsl_interp_accel_alloc ();\n spl = gsl_spline_alloc (gsl_interp_linear, npts);\n\n gsl_spline_init (spl, arr1, arr2, npts);\n Q = gsl_spline_eval_integ (spl, lower_limit, upper_limit, acc);\n\n gsl_spline_free (spl);\n gsl_interp_accel_free (acc);\n\n return Q;\n}\n\ndouble interpolate_arr(const double arr1[MAX_STRING_LEN], const double arr2[MAX_STRING_LEN], const int npts, const int xi)\n{\n double Q;\n gsl_interp_accel *acc;\n gsl_spline *spl;\n\n acc = gsl_interp_accel_alloc ();\n spl = gsl_spline_alloc (gsl_interp_linear, npts);\n\n gsl_spline_init (spl, arr1, arr2, npts);\n Q = gsl_spline_eval (spl, xi, acc);\n\n gsl_spline_free (spl);\n gsl_interp_accel_free (acc);\n return Q;\n}\n\ndouble compute_imf (const double m)\n{ //eq 11 Arrigoni et al. 2010\n double mass = m;\n double A = 0.9098, B = 0.2539, x = 1.3, sigma=0.69;\n double mc = 0.079; //Msun\n double phi;\n\n if (m < 1){\n phi = A * exp( -(log10(mass) - log10(mc)) / (2*sigma*sigma));\n }\n else {\n phi = B * pow(mass, -x);\n }\n\n return phi;\n}\n\ndouble compute_taum (const double m)\n{ //eq 3 Raiteri et al. 1996 \n double mass = m;\n double Z = 0.02;\n double a0 = 10.13 + 0.07547*log10(Z) - 0.008084*log10(Z)*log10(Z);\n double a1 = -4.424 - 0.7939*log10(Z) - 0.1187*log10(Z)*log10(Z);\n double a2 = 1.262 + 0.3385*log10(Z) + 0.05417*log10(Z)*log10(Z);\n\n double logt = a0 + a1*log10(mass) + a2*log10(mass)*log10(mass);\n double t = pow(10, logt) / 1e6 ; //in Myr/h\n\n /* convert into Myrs/h */\n return t;\n}\n", "meta": {"hexsha": "dc131b623a368b12f7af320d97a8e8dc5eb52b7b", "size": 21674, "ext": "c", "lang": "C", "max_stars_repo_path": "src/model_dust.c", "max_stars_repo_name": "dptriani/sage", "max_stars_repo_head_hexsha": "0260b7026efd81d855bc1f187196da2b1839207b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-02-06T02:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T04:14:05.000Z", "max_issues_repo_path": "src/model_dust.c", "max_issues_repo_name": "dptriani/sage", "max_issues_repo_head_hexsha": "0260b7026efd81d855bc1f187196da2b1839207b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model_dust.c", "max_forks_repo_name": "dptriani/sage", "max_forks_repo_head_hexsha": "0260b7026efd81d855bc1f187196da2b1839207b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T05:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T11:12:02.000Z", "avg_line_length": 40.137037037, "max_line_length": 265, "alphanum_fraction": 0.5913998339, "num_tokens": 7271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.40522293733939174}} {"text": "/* ode-initval2/rk2imp.c\n * \n * Copyright (C) 2009, 2010 Tuomo Keskitalo\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Based on rk2imp.c by Gerard Jungman */\n\n/* Runge-Kutta 2, Gaussian implicit. Also known as implicit midpoint\n rule. Error estimation is carried out by the step doubling\n method.\n */\n\n/* Reference: Ascher, U.M., Petzold, L.R., Computer methods for\n ordinary differential and differential-algebraic equations, SIAM,\n Philadelphia, 1998.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"odeiv_util.h\"\n#include \"rksubs.c\"\n#include \"modnewton1.c\"\n\n/* Stage of method */\n#define RK2IMP_STAGE 1\n\ntypedef struct\n{\n gsl_matrix *A; /* Runge-Kutta coefficients */\n double *y_onestep; /* Result with one step */\n double *y_twostep; /* Result with two half steps */\n double *ytmp; /* Temporary work space */\n double *y_save; /* Backup space */\n double *YZ; /* Runge-Kutta points */\n double *fYZ; /* Derivatives at YZ */\n gsl_matrix *dfdy; /* Jacobian matrix */\n double *dfdt; /* time derivative of f */\n modnewton1_state_t *esol; /* nonlinear equation solver */\n double *errlev; /* desired error level of y */\n const gsl_odeiv2_driver *driver; /* pointer to driver object */\n}\nrk2imp_state_t;\n\nstatic void *\nrk2imp_alloc (size_t dim)\n{\n rk2imp_state_t *state = (rk2imp_state_t *) malloc (sizeof (rk2imp_state_t));\n\n if (state == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for rk2imp_state\",\n GSL_ENOMEM);\n }\n\n state->A = gsl_matrix_alloc (RK2IMP_STAGE, RK2IMP_STAGE);\n\n if (state->A == 0)\n {\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for A\", GSL_ENOMEM);\n }\n\n state->y_onestep = (double *) malloc (dim * sizeof (double));\n\n if (state->y_onestep == 0)\n {\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y_onestep\", GSL_ENOMEM);\n }\n\n state->y_twostep = (double *) malloc (dim * sizeof (double));\n\n if (state->y_twostep == 0)\n {\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y_onestep\", GSL_ENOMEM);\n }\n\n state->ytmp = (double *) malloc (dim * sizeof (double));\n\n if (state->ytmp == 0)\n {\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for ytmp\", GSL_ENOMEM);\n }\n\n state->y_save = (double *) malloc (dim * sizeof (double));\n\n if (state->y_save == 0)\n {\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y_save\", GSL_ENOMEM);\n }\n\n state->YZ = (double *) malloc (dim * RK2IMP_STAGE * sizeof (double));\n\n if (state->YZ == 0)\n {\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for YZ\", GSL_ENOMEM);\n }\n\n state->fYZ = (double *) malloc (dim * RK2IMP_STAGE * sizeof (double));\n\n if (state->fYZ == 0)\n {\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for fYZ\", GSL_ENOMEM);\n }\n\n state->dfdt = (double *) malloc (dim * sizeof (double));\n\n if (state->dfdt == 0)\n {\n free (state->fYZ);\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for dfdt\", GSL_ENOMEM);\n }\n\n state->dfdy = gsl_matrix_alloc (dim, dim);\n\n if (state->dfdy == 0)\n {\n free (state->dfdt);\n free (state->fYZ);\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for dfdy\", GSL_ENOMEM);\n }\n\n state->esol = modnewton1_alloc (dim, RK2IMP_STAGE);\n\n if (state->esol == 0)\n {\n gsl_matrix_free (state->dfdy);\n free (state->dfdt);\n free (state->fYZ);\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for esol\", GSL_ENOMEM);\n }\n\n state->errlev = (double *) malloc (dim * sizeof (double));\n\n if (state->errlev == 0)\n {\n modnewton1_free (state->esol);\n gsl_matrix_free (state->dfdy);\n free (state->dfdt);\n free (state->fYZ);\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for errlev\", GSL_ENOMEM);\n }\n\n state->driver = NULL;\n\n return state;\n}\n\nstatic int\nrk2imp_apply (void *vstate, size_t dim, double t, double h,\n double y[], double yerr[],\n const double dydt_in[], double dydt_out[],\n const gsl_odeiv2_system * sys)\n{\n /* Makes a Gaussian implicit 4th order Runge-Kutta step with size h\n and estimates the local error of the step by step doubling.\n */\n\n rk2imp_state_t *state = (rk2imp_state_t *) vstate;\n\n double *const y_onestep = state->y_onestep;\n double *const y_twostep = state->y_twostep;\n double *const ytmp = state->ytmp;\n double *const y_save = state->y_save;\n double *const YZ = state->YZ;\n double *const fYZ = state->fYZ;\n gsl_matrix *const dfdy = state->dfdy;\n double *const dfdt = state->dfdt;\n double *const errlev = state->errlev;\n\n const modnewton1_state_t *esol = state->esol;\n\n /* Runge-Kutta coefficients */\n gsl_matrix *A = state->A;\n const double b[] = { 1.0 };\n const double c[] = { 0.5 };\n gsl_matrix_set (A, 0, 0, 0.5);\n\n if (esol == NULL)\n {\n GSL_ERROR (\"no non-linear equation solver speficied\", GSL_EINVAL);\n }\n\n /* Get desired error levels via gsl_odeiv2_control object through driver\n object, which is a requirement for this stepper.\n */\n\n if (state->driver == NULL)\n {\n return GSL_EFAULT;\n }\n else\n {\n size_t i;\n\n for (i = 0; i < dim; i++)\n {\n if (dydt_in != NULL)\n {\n gsl_odeiv2_control_errlevel (state->driver->c, y[i],\n dydt_in[i], h, i, &errlev[i]);\n }\n else\n {\n gsl_odeiv2_control_errlevel (state->driver->c, y[i],\n 0.0, h, i, &errlev[i]);\n }\n }\n }\n\n /* Evaluate Jacobian for modnewton1 */\n\n {\n int s = GSL_ODEIV_JA_EVAL (sys, t, y, dfdy->data, dfdt);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n /* Calculate a single step with size h */\n\n {\n int s = modnewton1_init ((void *) esol, A, h, dfdy, sys);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n {\n int s = modnewton1_solve ((void *) esol, A, c, t, h, y,\n sys, YZ, errlev);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + c[0] * h, YZ, fYZ);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n {\n int s = rksubs (y_onestep, h, y, fYZ, b, RK2IMP_STAGE, dim);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n /* Error estimation by step doubling */\n\n {\n int s = modnewton1_init ((void *) esol, A, h / 2.0, dfdy, sys);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n /* 1st half step */\n\n {\n int s = modnewton1_solve ((void *) esol, A, c, t, h / 2.0, y,\n sys, YZ, errlev);\n\n if (s != GSL_SUCCESS)\n return s;\n }\n\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + c[0] * h / 2.0, YZ, fYZ);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n {\n int s = rksubs (ytmp, h / 2.0, y, fYZ, b, RK2IMP_STAGE, dim);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n /* Save original y values in case of error */\n\n DBL_MEMCPY (y_save, y, dim);\n\n /* 2nd half step */\n\n {\n int s = modnewton1_solve ((void *) esol, A, c, t + h / 2.0, h / 2.0,\n ytmp, sys, YZ, errlev);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + h / 2.0 + c[0] * h / 2.0, YZ, fYZ);\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n {\n /* Note: rk2imp returns y using the results from two half steps\n instead of the single step since the results are freely\n available and more precise.\n */\n\n int s = rksubs (y_twostep, h / 2.0, ytmp, fYZ, b, RK2IMP_STAGE, dim);\n\n if (s != GSL_SUCCESS)\n {\n DBL_MEMCPY (y, y_save, dim);\n return s;\n }\n }\n\n DBL_MEMCPY (y, y_twostep, dim);\n\n /* Error estimation */\n\n {\n size_t i;\n for (i = 0; i < dim; i++)\n {\n yerr[i] = ODEIV_ERR_SAFETY * 0.5 *\n fabs (y_twostep[i] - y_onestep[i]) / 3.0;\n }\n }\n\n /* Derivatives at output */\n\n if (dydt_out != NULL)\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);\n\n if (s != GSL_SUCCESS)\n {\n /* Restore original values */\n DBL_MEMCPY (y, y_save, dim);\n\n return s;\n }\n }\n\n return GSL_SUCCESS;\n}\n\nstatic int\nrk2imp_set_driver (void *vstate, const gsl_odeiv2_driver * d)\n{\n rk2imp_state_t *state = (rk2imp_state_t *) vstate;\n\n state->driver = d;\n\n return GSL_SUCCESS;\n}\n\nstatic int\nrk2imp_reset (void *vstate, size_t dim)\n{\n rk2imp_state_t *state = (rk2imp_state_t *) vstate;\n\n DBL_ZERO_MEMSET (state->y_onestep, dim);\n DBL_ZERO_MEMSET (state->y_twostep, dim);\n DBL_ZERO_MEMSET (state->ytmp, dim);\n DBL_ZERO_MEMSET (state->y_save, dim);\n DBL_ZERO_MEMSET (state->YZ, dim);\n DBL_ZERO_MEMSET (state->fYZ, dim);\n\n return GSL_SUCCESS;\n}\n\nstatic unsigned int\nrk2imp_order (void *vstate)\n{\n rk2imp_state_t *state = (rk2imp_state_t *) vstate;\n state = 0; /* prevent warnings about unused parameters */\n return 2;\n}\n\nstatic void\nrk2imp_free (void *vstate)\n{\n rk2imp_state_t *state = (rk2imp_state_t *) vstate;\n\n free (state->errlev);\n modnewton1_free (state->esol);\n gsl_matrix_free (state->dfdy);\n free (state->dfdt);\n free (state->fYZ);\n free (state->YZ);\n free (state->y_save);\n free (state->ytmp);\n free (state->y_twostep);\n free (state->y_onestep);\n gsl_matrix_free (state->A);\n free (state);\n}\n\nstatic const gsl_odeiv2_step_type rk2imp_type = {\n \"rk2imp\", /* name */\n 1, /* can use dydt_in? */\n 1, /* gives exact dydt_out? */\n &rk2imp_alloc,\n &rk2imp_apply,\n &rk2imp_set_driver,\n &rk2imp_reset,\n &rk2imp_order,\n &rk2imp_free\n};\n\nconst gsl_odeiv2_step_type *gsl_odeiv2_step_rk2imp = &rk2imp_type;\n", "meta": {"hexsha": "9abac5dc9ce3112615b85b20740d9c1a71f85b5b", "size": 12238, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/ode-initval2/rk2imp.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ode-initval2/rk2imp.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ode-initval2/rk2imp.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 24.0905511811, "max_line_length": 81, "alphanum_fraction": 0.5766465109, "num_tokens": 3652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4050846806788876}} {"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n** **\n** This file forms part of the Underworld geophysics modelling application. **\n** **\n** For full license and copyright information, please refer to the LICENSE.md file **\n** located at the project root, or contact the authors. **\n** **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n\n/*\n\nPerforms y = ( G^T G )^{-1} ( G^T K G ) ( G^T G )^{-1} x\nThis preconditioner is defined as a PC rather than a MatShell\nas we can define and compute the inverse easily without the\nneed of an additional KSP. Compare this to Q_S = G^T Q_K^-1 G,\nwhere Q_S^-1 can only be performed implicitly via an iterative\nmethod.\n\n*/\n#if 1\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"common-driver-utils.h\"\n\n#include \n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )\n #if (PETSC_VERSION_MINOR >=6)\n #include \"petsc/private/pcimpl.h\"\n #include \"petsc/private/kspimpl.h\"\n #else\n #include \"petsc-private/pcimpl.h\"\n #include \"petsc-private/kspimpl.h\"\n #endif\n#else\n #include \"private/pcimpl.h\"\n #include \"private/kspimpl.h\"\n#endif\n\n#include \"pc_GtKG.h\"\n\n#include \n#include \n\n#define PCTYPE_GtKG \"gtkg\"\n\n\n/* private data */\n\ntypedef struct {\n\tMat G, K; /* G \\in [M x N], K \\in [M x M] */\n\tMat M; /* the velocity mass matrix */\n\tVec inv_diag_M;\n\tPetscTruth form_GtG; /* don't allow anything else yet */\n\tMat GtG;\n\tKSP ksp;\n\tVec s,t,X; /* s \\in [M], t \\in [N], X \\in [M] */\n\tPetscTruth monitor_activated;\n\tPetscTruth monitor_rhs_consistency;\n} _PC_GtKG;\n\ntypedef _PC_GtKG* PC_GtKG;\n\n\n/* private prototypes */\nPetscErrorCode BSSCR_PCApply_GtKG( PC pc, Vec x, Vec y );\nPetscErrorCode BSSCR_PCApplyTranspose_GtKG( PC pc, Vec x, Vec y );\nPetscErrorCode BSSCR_BSSCR_PCApply_GtKG_diagonal_scaling( PC pc, Vec x, Vec y );\nPetscErrorCode BSSCR_BSSCR_PCApplyTranspose_GtKG_diagonal_scaling( PC pc, Vec x, Vec y );\nPetscErrorCode BSSCR_PCSetUp_GtKG( PC pc );\n\n\n\n\nPetscErrorCode BSSCR_pc_warn( PC pc, const char func_name[] ) \n{\n\tconst PCType type;\n\tPCGetType( pc, &type );\n\t\n\tif( strcmp(type,PCTYPE_GtKG)!=0 ) {\n\t\tprintf(\"Warning(%s): PC type (%s) should be gtkg \\n\",func_name, type );\n\t\tPetscFunctionReturn(0);\n\t}\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_pc_error( PC pc, const char func_name[] ) \n{\n\tconst PCType type;\n\tPCGetType( pc, &type );\n\t\n\tif( strcmp(type,PCTYPE_GtKG)!=0 ) {\n\t\tprintf(\"Error(%s): PC type (%s) should be gtkg \\n\",func_name, type );\n\t\tPetscFinalize();\n\t\texit(0);\n\t}\n\tPetscFunctionReturn(0);\n}\n\nvoid BSSCR_get_number_nonzeros_AIJ( Mat A, PetscInt *nnz )\n{\n\tMatInfo info;\n\t\n\tMatGetInfo( A, MAT_GLOBAL_SUM, &info );\n\t*nnz = info.nz_used;\n\t\n}\n\n\n/*\nI should not modify setup called!!\nThis is handled via petsc.\n*/\nPetscErrorCode BSSCR_PCSetUp_GtKG( PC pc )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\tPetscReal fill;\n\tMat Ident;\n\tVec diag;\n\tPetscInt M,N, m,n;\n\tMPI_Comm comm;\n\tPetscInt nnz_I, nnz_G;\n\tconst MatType mtype;\n\tconst char *prefix;\n\tPetscTruth wasSetup;\n\t\n\t\n\t\n\tif( ctx->K == PETSC_NULL ) {\n\t\tStg_SETERRQ( PETSC_ERR_SUP, \"gtkg: K not set\" );\n\t}\n\tif( ctx->G == PETSC_NULL ) {\n\t\tStg_SETERRQ( PETSC_ERR_SUP, \"gtkg: G not set\" );\n\t}\n\t\n\tPetscObjectGetComm( (PetscObject)ctx->K, &comm ); \n\t\n\t\n\t/* Check for existence of objects and trash any which exist */\n\tif( ctx->form_GtG == PETSC_TRUE && ctx->GtG != PETSC_NULL ) {\n\t\tStg_MatDestroy(&ctx->GtG );\n\t\tctx->GtG = PETSC_NULL;\n\t}\n\t\n\tif( ctx->s != PETSC_NULL ) {\n\t\tStg_VecDestroy(&ctx->s );\n\t\tctx->s = PETSC_NULL;\n\t}\n\tif( ctx->X != PETSC_NULL ) {\n\t\tStg_VecDestroy(&ctx->X );\n\t\tctx->X = PETSC_NULL;\n\t}\n\tif( ctx->t != PETSC_NULL ) {\n\t\tStg_VecDestroy(&ctx->t );\n\t\tctx->t = PETSC_NULL;\n\t}\n\tif( ctx->inv_diag_M != PETSC_NULL ) {\n\t\tStg_VecDestroy(&ctx->inv_diag_M );\n\t\tctx->inv_diag_M = PETSC_NULL;\n\t}\n\t\n\t\n\t\n\t/* Create vectors */\n\tMatGetVecs( ctx->K, &ctx->s, &ctx->X );\n\tMatGetVecs( ctx->G, &ctx->t, PETSC_NULL );\n\t\n\tif( ctx->M != PETSC_NULL ) {\n\t\tMatGetVecs( ctx->K, &ctx->inv_diag_M, PETSC_NULL );\n\t\tMatGetDiagonal( ctx->M, ctx->inv_diag_M );\n\t\tVecReciprocal( ctx->inv_diag_M );\n\t\t\n\t\t/* change the pc_apply routines */\n\t\tpc->ops->apply = BSSCR_BSSCR_PCApply_GtKG_diagonal_scaling;\n\t\tpc->ops->applytranspose = BSSCR_BSSCR_PCApplyTranspose_GtKG_diagonal_scaling;\n\t}\n\t\n\t\n\t/* Assemble GtG */\n\tMatGetSize( ctx->G, &M, &N );\n\tMatGetLocalSize( ctx->G, &m, &n );\n\t\n\tMatGetVecs( ctx->G, PETSC_NULL, &diag );\n\tVecSet( diag, 1.0 );\n\t\n\tMatCreate( comm, &Ident );\n\tMatSetSizes( Ident, m,m , M, M );\n#if (((PETSC_VERSION_MAJOR==3) && (PETSC_VERSION_MINOR>=3)) || (PETSC_VERSION_MAJOR>3) )\n MatSetUp(Ident);\n#endif\n\n\tMatGetType( ctx->G, &mtype );\n\tMatSetType( Ident, mtype );\n\t\n\tif( ctx->M == PETSC_NULL ) {\n\t\tMatDiagonalSet( Ident, diag, INSERT_VALUES );\n\t}\n\telse {\n\t\tMatDiagonalSet( Ident, ctx->inv_diag_M, INSERT_VALUES );\n\t}\n\t\n\tBSSCR_get_number_nonzeros_AIJ( Ident, &nnz_I );\n\tBSSCR_get_number_nonzeros_AIJ( ctx->G, &nnz_G );\n\t//fill = 1.0;\n\t/* \n\tNot sure the best way to estimate the fill factor.\n\tGtG is a laplacian on the pressure space. \n\tThis might tell us something useful...\n\t*/\n\tfill = (PetscReal)(nnz_G)/(PetscReal)( nnz_I );\n\tMatPtAP( Ident, ctx->G, MAT_INITIAL_MATRIX, fill, &ctx->GtG );\n\t\n\tStg_MatDestroy(&Ident);\n\tStg_VecDestroy(&diag );\n\t\n\t\n\tStg_KSPSetOperators( ctx->ksp, ctx->GtG, ctx->GtG, SAME_NONZERO_PATTERN );\n\t\n\tif (!pc->setupcalled) {\t\n\t\twasSetup = PETSC_FALSE;\n\t\t\n\t\tPCGetOptionsPrefix( pc,&prefix );\n\t\tKSPSetOptionsPrefix( ctx->ksp, prefix );\n\t\tKSPAppendOptionsPrefix( ctx->ksp, \"pc_gtkg_\" ); /* -pc_GtKG_ksp_type , -ksp_GtKG_pc_type */\n\t}\n\telse {\n\t\twasSetup = PETSC_TRUE;\n\t}\t\n\t\n\t\n//\tif (!wasSetup && pc->setfromoptionscalled) {\n\tif (!wasSetup) {\n\t\tKSPSetFromOptions(ctx->ksp);\n\t}\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCDestroy_GtKG( PC pc )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\t\n\t\n\tif( ctx == PETSC_NULL ) {\tPetscFunctionReturn(0); }\n\t\n\tif( ctx->form_GtG == PETSC_TRUE && ctx->GtG != PETSC_NULL ) {\n\t\tStg_MatDestroy(&ctx->GtG );\n\t}\n\tif( ctx->ksp != PETSC_NULL ) {\tStg_KSPDestroy(&ctx->ksp );\t\t}\n\tif( ctx->s != PETSC_NULL ) {\tStg_VecDestroy(&ctx->s );\t\t}\n\tif( ctx->X != PETSC_NULL ) {\tStg_VecDestroy(&ctx->X );\t\t}\n\tif( ctx->t != PETSC_NULL ) {\tStg_VecDestroy(&ctx->t );\t\t}\n\tif( ctx->inv_diag_M != PETSC_NULL ) {\n\t\tStg_VecDestroy(&ctx->inv_diag_M );\n\t\tctx->inv_diag_M = PETSC_NULL;\n\t}\n\t\n\tPetscFree( ctx );\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCView_GtKG( PC pc, PetscViewer viewer )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\t\n\tPetscViewerASCIIPushTab(viewer); //1\n\n\tif( ctx->M == PETSC_NULL ) {\n\t\tPetscViewerASCIIPrintf( viewer, \"gtkg: Standard \\n\" );\n\t}else {\n\t\tPetscViewerASCIIPrintf( viewer, \"gtkg: Least Squares Commutator \\n\" );\n\t}\n\t\n\tPetscViewerASCIIPrintf( viewer, \"gtkg-ksp \\n\" );\n\tPetscViewerASCIIPrintf(viewer,\"---------------------------------\\n\");\n\tPetscViewerASCIIPushTab(viewer);\n\t\tKSPView( ctx->ksp, viewer );\n\tPetscViewerASCIIPopTab(viewer);\n\tPetscViewerASCIIPrintf(viewer,\"---------------------------------\\n\");\n\t\n\tPetscViewerASCIIPopTab(viewer); //1\n\t\n\tPetscFunctionReturn(0);\n}\n\n\nPetscErrorCode BSSCR_Lp_monitor( KSP ksp, PetscInt index )\n{\n\tPetscInt max_it;\n\tPetscReal rnorm;\n\tKSPConvergedReason reason;\n\t\n\tKSPGetIterationNumber( ksp, &max_it );\n\tKSPGetResidualNorm( ksp, &rnorm );\n\tKSPGetConvergedReason( ksp, &reason );\n\tif (ksp->reason > 0) {\n\t\tPetscPrintf(((PetscObject)ksp)->comm,\"\\t: Linear solve converged. its.=%.4d ; |r|=%5.5e ; Reason=%s\\n\", \n\t\t\t\tindex, max_it, rnorm, KSPConvergedReasons[reason] );\n\t} else {\n\t\tPetscPrintf(((PetscObject)ksp)->comm,\"\\t: Linear solve did not converge. its.=%.4d ; |r|=%5.5e ; Reason=%s\\n\", \n\t\t\t\tindex, max_it, rnorm, KSPConvergedReasons[reason]);\n\t}\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCBFBTSubKSPMonitor( KSP ksp, PetscInt index, PetscLogDouble time )\n{\n PetscInt max_it;\n PetscReal rnorm;\n KSPConvergedReason reason;\n\n KSPGetIterationNumber( ksp, &max_it );\n KSPGetResidualNorm( ksp, &rnorm );\n KSPGetConvergedReason( ksp, &reason );\n PetscPrintf(((PetscObject)ksp)->comm,\" PCBFBTSubKSP (%d): %D Residual norm; r0 %12.12e, r %12.12e: Reason %s: Time %5.5e \\n\", \n\t\tindex, max_it, ksp->rnorm0, rnorm, KSPConvergedReasons[reason], time );\n\n PetscFunctionReturn(0);\n}\n\n\n\n/* \nChecks rhs of Lp systems is in the null space of Lp, i.e. {rhs} \\centerdot {null_space} = 0\nSince Lp should contain the null space {1}, we just check the \\sum_i rhs_i = 0\n*/\nPetscErrorCode BSSCRBSSCR_Lp_monitor_check_rhs_consistency( KSP ksp, Vec rhs, PetscInt index )\n{\n\tPetscScalar dot;\n#if 0\n\tVec one;\n\t\n\tVecDuplicate( rhs, &one );\n\tVecSet( one, 1.0 );\n\tVecDot( rhs, one, &dot );\n\tif( PetscAbsReal(dot) > 1.0e-8 ) {\n\t\tPetscPrintf(ksp->comm,\" ($D) Lp z = r: ******* WARNING ******* RHS is not consistent. {b}.{1} = %5.5e \\n\", index, dot );\n\t}\n\t\n\tStg_VecDestroy(&one );\n\tPetscFunctionReturn(0);\n#endif\n#if 0\t\n\tVecSum( rhs, &dot );\n\tif( PetscAbsReal(dot) > 1.0e-8 ) {\n\t\tPetscPrintf(((PetscObject)ksp)->comm,\" (%D) Lp z = r: ******* WARNING ******* RHS is not consistent. {b}.{1} = %5.5e \\n\", \n\t\t\t\tindex, dot );\n\t\tBSSCR_VecRemoveConstNullspace( rhs, PETSC_NULL );\n\t}\n#endif\n\tPetscFunctionReturn(0);\n}\n\n\n/* \nPerforms y <- S^{-1} x \nS^{-1} = ( G^T G )^{-1} G^T K G ( G^T G )^{-1}\n*/\nPetscErrorCode BSSCR_PCApply_GtKG( PC pc, Vec x, Vec y )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\t\n\tKSP ksp;\n\tMat K, G;\n\tVec s,t,X;\n\tPetscLogDouble t0,t1;\t\n\n\tksp = ctx->ksp;\n\tK = ctx->K;\n\tG = ctx->G;\n\ts = ctx->s;\n\tt = ctx->t;\n\tX = ctx->X;\n\t\n\tif (ctx->monitor_rhs_consistency) {\t\tBSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,x,1);\t\t}\n\tPetscGetTime(&t0);\n\tKSPSolve( ksp, x, t ); /* t <- GtG_inv x */\n\tPetscGetTime(&t1);\n\tif (ctx->monitor_activated) {\tBSSCR_PCBFBTSubKSPMonitor(ksp,1,(t1-t0));\t\t}\n\t\n\tMatMult( G, t, s ); /* s <- G t */\n\tMatMult( K, s, X ); /* X <- K s */\n\tMatMultTranspose( G, X, t ); /* t <- Gt X */\n\t\n\tif (ctx->monitor_rhs_consistency) {\t\tBSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,t,2);\t\t}\n\tPetscGetTime(&t0);\n\tKSPSolve( ksp, t, y ); /* y <- GtG_inv t */\n\tPetscGetTime(&t1);\n\tif (ctx->monitor_activated) {\tBSSCR_PCBFBTSubKSPMonitor(ksp,2,(t1-t0));\t\t}\n\t\n\tPetscFunctionReturn(0);\n}\n\n/* Need to check this one if correct */\n/*\nS^{-1} = ( G^T G )^{-1} G^T K G ( G^T G )^{-1}\n = A C A\nS^{-T} = A^T (A C)^T\n = A^T C^T A^T, but A = G^T G which is symmetric\n = A C^T A\n = A G^T ( G^T K )^T A\n = A G^T K^T G A\n\n*/\nPetscErrorCode BSSCR_PCApplyTranspose_GtKG( PC pc, Vec x, Vec y )\n{\n\t\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\t\n\tKSP ksp;\n\tMat K, G;\n\tVec s,t,X;\n\tPetscLogDouble t0,t1;\n\t\n\tksp = ctx->ksp;\n\tK = ctx->K;\n\tG = ctx->G;\n\ts = ctx->s;\n\tt = ctx->t;\n\tX = ctx->X;\n\t\n\tif (ctx->monitor_rhs_consistency) {\t\tBSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,x,1);\t\t}\n\tPetscGetTime(&t0);\n\tKSPSolve( ksp, x, t ); /* t <- GtG_inv x */\n\tPetscGetTime(&t1);\n\tif (ctx->monitor_activated) {\tBSSCR_PCBFBTSubKSPMonitor(ksp,1,(t1-t0));\t\t}\n\t\n\tMatMult( G, t, s ); /* s <- G t */\n\tMatMultTranspose( K, s, X ); /* X <- K^T s */\n\tMatMultTranspose( G, X, t ); /* t <- Gt X */\n\t\n\tif (ctx->monitor_rhs_consistency) {\t\tBSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,t,2);\t\t}\n\tPetscGetTime(&t0);\n\tKSPSolve( ksp, t, y ); /* y <- GtG_inv t */\n\tPetscGetTime(&t1);\n\tif (ctx->monitor_activated) {\tBSSCR_PCBFBTSubKSPMonitor(ksp,2,(t1-t0));\t\t}\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n/* \nPerforms y <- S^{-1} x \nS^{-1} = ( G^T Di G )^{-1} G^T Di K Di G ( G^T Di G )^{-1}\nwhere Di = diag(M)^{-1}\n*/\n\n\nPetscErrorCode BSSCR_BSSCR_PCApply_GtKG_diagonal_scaling( PC pc, Vec x, Vec y )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\t\n\tKSP ksp;\n\tMat K, G;\n\tVec s,t,X,di;\n\t\n\t\n\tksp = ctx->ksp;\n\tK = ctx->K;\n\tG = ctx->G;\n\tdi = ctx->inv_diag_M;\n\ts = ctx->s;\n\tt = ctx->t;\n\tX = ctx->X;\n\t\n\tif (ctx->monitor_rhs_consistency) {\t\tBSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,x,1);\t\t}\n\tKSPSolve( ksp, x, t ); /* t <- GtG_inv x */\n\tif (ctx->monitor_activated) {\tBSSCR_Lp_monitor(ksp,2);\t\t}\n\t\n\tMatMult( G, t, s ); /* s <- G t */\n\tVecPointwiseMult( s, s,di ); /* s <- s * di */\n\t\n\tMatMult( K, s, X ); /* X <- K s */\n\tVecPointwiseMult( X, X,di ); /* X <- X * di */\n\t\n\tMatMultTranspose( G, X, t ); /* t <- Gt X */\n\t\n\tif (ctx->monitor_rhs_consistency) {\t\tBSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,t,2);\t\t}\n\tKSPSolve( ksp, t, y ); /* y <- GtG_inv t */\n\tif (ctx->monitor_activated) {\tBSSCR_Lp_monitor(ksp,2);\t\t}\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_BSSCR_PCApplyTranspose_GtKG_diagonal_scaling( PC pc, Vec x, Vec y )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\t\n\tKSP ksp;\n\tMat K, G;\n\tVec s,t,X,di;\n\t\n\t\n\tksp = ctx->ksp;\n\tK = ctx->K;\n\tG = ctx->G;\n\tdi = ctx->inv_diag_M;\n\ts = ctx->s;\n\tt = ctx->t;\n\tX = ctx->X;\n\t\n\tif (ctx->monitor_rhs_consistency) {\t\tBSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,x,1);\t\t}\n\tKSPSolve( ksp, x, t ); /* t <- GtG_inv x */\n\tif (ctx->monitor_activated) {\tBSSCR_Lp_monitor(ksp,1);\t\t}\n\t\n\tMatMult( G, t, s ); /* s <- G t */\n\tVecPointwiseMult( s, s,di ); /* s <- s * di */\n\t\n\tMatMultTranspose( K, s, X ); /* X <- K^T s */\n\tVecPointwiseMult( X, X,di ); /* X <- X * di */\n\t\n\tMatMultTranspose( G, X, t ); /* t <- Gt X */\n\t\n\tif (ctx->monitor_rhs_consistency) {\t\tBSSCRBSSCR_Lp_monitor_check_rhs_consistency(ksp,t,2);\t\t}\n\tKSPSolve( ksp, t, y ); /* y <- GtG_inv t */\n\tif (ctx->monitor_activated) {\tBSSCR_Lp_monitor(ksp,2);\t\t}\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n\n\n\n/*\nOnly the options related to GtKG should be set here.\n*/\nPetscErrorCode BSSCR_PCSetFromOptions_GtKG( PC pc )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\tPetscTruth ivalue, flg;\n\t\n\tPetscOptionsGetTruth( PETSC_NULL, \"-pc_gtkg_monitor\", &ivalue, &flg );\n\tif( flg==PETSC_TRUE ) {\n\t\tctx->monitor_activated = ivalue;\n\t}\n\t\n\tPetscOptionsGetTruth( PETSC_NULL, \"-pc_gtkg_monitor_rhs_consistency\", &ivalue, &flg );\n\tif( flg==PETSC_TRUE ) {\n\t\tctx->monitor_rhs_consistency = ivalue;\n\t}\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n\n/* ---- Exposed functions ---- */\n\nPetscErrorCode BSSCR_PCCreate_GtKG( PC pc )\n{\n\tPC_GtKG pc_data;\n\tPetscErrorCode ierr;\n\t\n\t/* create memory for ctx */\n\tierr = Stg_PetscNew( _PC_GtKG,&pc_data);CHKERRQ(ierr);\n\t\n\t/* init ctx */\n\tpc_data->K = PETSC_NULL;\n\tpc_data->G = PETSC_NULL;\n\tpc_data->M = PETSC_NULL;\n\tpc_data->GtG = PETSC_NULL;\n\tpc_data->form_GtG = PETSC_TRUE;\n\tpc_data->ksp = PETSC_NULL;\n\tpc_data->monitor_activated = PETSC_FALSE;\n\tpc_data->monitor_rhs_consistency = PETSC_FALSE;\n\t\n\tpc_data->s = PETSC_NULL;\n\tpc_data->t = PETSC_NULL;\n\tpc_data->X = PETSC_NULL;\n\tpc_data->inv_diag_M = PETSC_NULL;\n\t\n\t/* create internals */\n\tKSPCreate( ((PetscObject)pc)->comm, &pc_data->ksp );\n\t\n\t\n\t/* set ctx onto pc */\n\tpc->data = (void*)pc_data;\n\t\n\tierr = PetscLogObjectMemory(pc,sizeof(_PC_GtKG));CHKERRQ(ierr);\n\t\n\t/* define operations */\n\tpc->ops->setup = BSSCR_PCSetUp_GtKG;\n\tpc->ops->view = BSSCR_PCView_GtKG;\n\tpc->ops->destroy = BSSCR_PCDestroy_GtKG;\n\tpc->ops->setfromoptions = BSSCR_PCSetFromOptions_GtKG;\n\t\n\tpc->ops->apply = BSSCR_PCApply_GtKG;\n\tpc->ops->applytranspose = BSSCR_PCApplyTranspose_GtKG;\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n/*\nK & G must different to PETSC_NULL\nM can be PETSC_NULL\n*/\nPetscErrorCode BSSCR_PCGtKGSet_Operators( PC pc, Mat K, Mat G, Mat M )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\t\n\tBSSCR_pc_error( pc, \"__func__\" );\n\t\n\tctx->K = K;\n\tctx->G = G;\n\tctx->M = M;\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCGtKGSet_OperatorForAlgebraicCommutator( PC pc, Mat M )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\t\n\tBSSCR_pc_error( pc, \"__func__\" );\n\t\n\tctx->M = M;\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCGtKGAttachNullSpace( PC pc )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\tMatNullSpace nsp;\n\t\n\tBSSCR_pc_error( pc, \"__func__\" );\n\t\n\t/* Attach a null space */\n\tMatNullSpaceCreate( PETSC_COMM_WORLD, PETSC_TRUE, PETSC_NULL, PETSC_NULL, &nsp );\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR <6) )\n\tKSPSetNullSpace( ctx->ksp, nsp );\n#else\n Mat A;\n KSPGetOperators(ctx->ksp,&A,NULL);//Note: DOES NOT increase the reference counts of the matrix, so you should NOT destroy them. \n MatSetNullSpace( A, nsp);\n#endif\n\t/* \n\tNOTE: This does NOT destroy the memory for nsp, it just decrements the nsp->refct, so that\n\tthe next time MatNullSpaceDestroy() is called, the memory will be released. The next time this\n\tis called will be by KSPDestroy();\n\t*/\n\tMatNullSpaceDestroy( nsp );\n\t\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCGtKGGet_KSP( PC pc, KSP *ksp )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\t\n\tBSSCR_pc_error( pc, \"__func__\" );\n\t\n\t\n\tif( ksp != PETSC_NULL ) {\n\t\t(*ksp) = ctx->ksp;\n\t}\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCGtKGSet_KSP( PC pc, KSP ksp )\n{\n\tPC_GtKG ctx = (PC_GtKG)pc->data;\n\t\n\tBSSCR_pc_error( pc, \"__func__\" );\n\t\n\t\n\tif( ctx->ksp != PETSC_NULL ) {\n\t\tStg_KSPDestroy(&ctx->ksp);\n\t}\n\tctx->ksp = ksp;\n\t\n\tPetscFunctionReturn(0);\n}\n#endif\n\n", "meta": {"hexsha": "906ed26364c4b7a38bd4b3bb0bbff569314c79e8", "size": 17400, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/pc_GtKG.c", "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/pc_GtKG.c", "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 561.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/pc_GtKG.c", "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "avg_line_length": 25.1082251082, "max_line_length": 137, "alphanum_fraction": 0.6305747126, "num_tokens": 6276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4049846167001816}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"bits/matrix-view.h\"\n#include \"utils/fcmp.h\"\n#include \"vector.h\"\n\nnamespace gsl_wrapper\n{\n class Matrix\n {\n public:\n // Constructors and destructor\n Matrix(size_t i, size_t j);\n Matrix(size_t matrix_size);\n Matrix(std::initializer_list> args);\n Matrix(const Vector &vec);\n\n Matrix(const Matrix ©_from);\n Matrix(Matrix &&move_from);\n\n ~Matrix();\n\n // Member functions\n auto get_gsl_matrix() const -> gsl_matrix *;\n auto get_dimensions() const -> std::pair;\n auto num_rows() const -> size_t;\n auto num_collumns() const -> size_t;\n\n // Operators\n auto operator=(const Matrix ©_from) -> Matrix &;\n auto operator=(Matrix &&move_from) -> Matrix &;\n\n auto operator==(const Matrix &comparasion_matrix) const -> bool;\n auto operator!=(const Matrix &comparasion_matrix) const -> bool;\n\n auto operator[](const size_t index) const -> gsl_wrapper::bits::MatrixRow;\n auto operator*(const Matrix &mul) const -> Matrix;\n auto operator*(const double number) const -> Matrix;\n auto operator+(const Matrix &matrix) const -> Matrix;\n auto operator+(const double numer) const -> Matrix;\n\n // Friend declarations\n friend auto operator<<(std::ostream &stream, const Matrix &matrix) -> std::ostream &;\n friend auto operator*(const double number, const Matrix &matrix) -> Matrix;\n friend auto operator+(const double number, const Matrix &matrix) -> Matrix;\n\n private:\n gsl_matrix *m_matrixPtr;\n size_t m_numRows;\n size_t m_numCollumns;\n };\n\n inline Matrix::Matrix(size_t i, size_t j)\n : m_matrixPtr{gsl_matrix_calloc(i, j)}, m_numRows{i}, m_numCollumns{j}\n {\n }\n\n inline Matrix::Matrix(size_t matrix_size)\n : Matrix(matrix_size, matrix_size)\n {\n }\n\n inline Matrix::Matrix(std::initializer_list> args)\n : m_matrixPtr{nullptr}, m_numCollumns{0}, m_numRows{0}\n {\n if (args.size() == 0)\n return;\n size_t num_rows = args.size();\n size_t num_collumns = (*args.begin()).size();\n\n // Setting object properties\n m_numCollumns = num_collumns;\n m_numRows = num_rows;\n m_matrixPtr = gsl_matrix_calloc(m_numRows, m_numCollumns);\n\n size_t row_iterator = 0;\n size_t collumn_iterator = 0;\n for (auto &&row : args)\n {\n if (row.size() != num_collumns)\n throw std::range_error{\"Diffrent number of items in diffrent rows when creating matrix\"};\n\n for (auto &&el : row)\n {\n (*this)[row_iterator][collumn_iterator++] = el;\n }\n collumn_iterator = 0;\n ++row_iterator;\n }\n }\n\n inline Matrix::Matrix(const Vector &vec)\n : m_matrixPtr{gsl_matrix_calloc(vec.size(), 1)},\n m_numCollumns{1},\n m_numRows{vec.size()}\n {\n for (size_t i = 0; i < m_numRows; i++)\n {\n (*this)[i][0] = vec[i];\n }\n }\n\n inline Matrix::Matrix(const Matrix ©_from)\n : m_matrixPtr{gsl_matrix_calloc(copy_from.m_numRows, copy_from.m_numCollumns)},\n m_numRows{copy_from.m_numRows},\n m_numCollumns{copy_from.m_numCollumns}\n {\n gsl_matrix_memcpy(m_matrixPtr, copy_from.m_matrixPtr);\n }\n\n inline Matrix::Matrix(Matrix &&move_from)\n : m_matrixPtr{std::exchange(move_from.m_matrixPtr, nullptr)},\n m_numRows{std::exchange(move_from.m_numRows, 0)},\n m_numCollumns{std::exchange(move_from.m_numCollumns, 0)}\n {\n }\n\n inline Matrix::~Matrix()\n {\n gsl_matrix_free(m_matrixPtr);\n }\n\n inline auto Matrix::get_gsl_matrix() const -> gsl_matrix *\n {\n return m_matrixPtr;\n }\n\n inline auto Matrix::get_dimensions() const -> std::pair\n {\n return {m_numRows, m_numCollumns};\n }\n\n inline auto Matrix::num_rows() const -> size_t\n {\n return m_numRows;\n }\n inline auto Matrix::num_collumns() const -> size_t\n {\n return m_numCollumns;\n }\n\n inline auto Matrix::operator=(const Matrix ©_from) -> Matrix &\n {\n // Prevent self copy\n if (m_matrixPtr == copy_from.m_matrixPtr)\n return *this;\n\n gsl_matrix_free(m_matrixPtr);\n m_matrixPtr = gsl_matrix_calloc(copy_from.m_numRows, copy_from.m_numCollumns);\n gsl_matrix_memcpy(m_matrixPtr, copy_from.m_matrixPtr);\n\n m_numCollumns = copy_from.m_numCollumns;\n m_numRows = copy_from.m_numRows;\n\n return *this;\n }\n\n inline auto Matrix::operator=(Matrix &&move_from) -> Matrix &\n {\n // Prevent self move\n if (m_matrixPtr == move_from.m_matrixPtr)\n return *this;\n\n gsl_matrix_free(m_matrixPtr);\n m_matrixPtr = std::exchange(move_from.m_matrixPtr, nullptr);\n m_numRows = std::exchange(move_from.m_numRows, 0);\n m_numCollumns = std::exchange(move_from.m_numCollumns, 0);\n\n return *this;\n }\n\n inline auto Matrix::operator==(const Matrix &comparasion_matrix) const -> bool\n {\n\n if ((m_numCollumns != comparasion_matrix.m_numCollumns) || (m_numRows != comparasion_matrix.m_numRows))\n return false;\n\n for (size_t i = 0; i < m_numRows; i++)\n {\n for (size_t j = 0; j < m_numCollumns; j++)\n {\n bool test = ::gsl_wrapper::utils::equal((*this)[i][j], comparasion_matrix[i][j]);\n if (!test)\n return false;\n }\n }\n return true;\n }\n\n inline auto Matrix::operator!=(const Matrix &comparasion_matrix) const -> bool\n {\n return !(*this == comparasion_matrix);\n }\n\n inline auto Matrix::operator[](const size_t index) const -> gsl_wrapper::bits::MatrixRow\n {\n using bits::MatrixRow;\n gsl_vector_view view = gsl_matrix_row(m_matrixPtr, index);\n return MatrixRow(view);\n }\n\n inline auto Matrix::operator*(const Matrix &mul) const -> Matrix\n {\n // Check sizes\n if (m_numCollumns != mul.m_numRows)\n throw std::runtime_error{\"Wrong matrix sizes!\"};\n\n Matrix result(m_numRows, mul.m_numCollumns);\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, m_matrixPtr, mul.m_matrixPtr, 0.0, result.get_gsl_matrix());\n\n return result;\n }\n\n inline auto Matrix::operator*(const double number) const -> Matrix\n {\n Matrix result = *this;\n for (size_t i = 0; i < m_numRows; i++)\n {\n for (size_t j = 0; j < m_numCollumns; j++)\n {\n result[i][j] *= number;\n }\n }\n\n return result;\n }\n\n inline auto Matrix::operator+(const Matrix &matrix) const -> Matrix\n {\n if ((m_numCollumns != matrix.m_numCollumns) || (m_numRows != matrix.m_numRows))\n throw std::range_error{\"Wrong matrix sizes when adding\"};\n\n Matrix result = *this;\n gsl_matrix_add(result.m_matrixPtr, matrix.m_matrixPtr);\n\n return result;\n }\n\n inline auto Matrix::operator+(const double number) const -> Matrix\n {\n Matrix result = *this;\n for (size_t i = 0; i < m_numRows; i++)\n {\n for (size_t j = 0; j < m_numCollumns; j++)\n {\n result[i][j] += number;\n }\n }\n\n return result;\n }\n\n inline auto operator<<(std::ostream &stream, const Matrix &matrix) -> std::ostream &\n {\n for (size_t i = 0; i < matrix.m_numRows; i++)\n {\n for (size_t j = 0; j < matrix.m_numCollumns; j++)\n {\n stream << matrix[i][j] << \" \";\n }\n stream << std::endl;\n }\n\n return stream;\n }\n\n inline auto operator*(const double number, const Matrix &matrix) -> Matrix\n {\n Matrix result = matrix;\n for (size_t i = 0; i < matrix.m_numRows; i++)\n {\n for (size_t j = 0; j < matrix.m_numCollumns; j++)\n {\n result[i][j] *= number;\n }\n }\n\n return result;\n }\n\n inline auto operator+(const double number, const Matrix &matrix) -> Matrix\n {\n Matrix result = matrix;\n for (size_t i = 0; i < matrix.m_numRows; i++)\n {\n for (size_t j = 0; j < matrix.m_numCollumns; j++)\n {\n result[i][j] += number;\n }\n }\n\n return result;\n }\n}\n", "meta": {"hexsha": "d786246debb611da3f8a57345e023e86ee4894c6", "size": 7902, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl_wrapper/matrix.h", "max_stars_repo_name": "Szynkaa/gsl_cpp_wrapper", "max_stars_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-09T14:35:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T14:35:36.000Z", "max_issues_repo_path": "include/gsl_wrapper/matrix.h", "max_issues_repo_name": "Szynkaa/gsl_cpp_wrapper", "max_issues_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gsl_wrapper/matrix.h", "max_forks_repo_name": "Szynkaa/gsl_cpp_wrapper", "max_forks_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-10T09:06:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T09:06:07.000Z", "avg_line_length": 25.9934210526, "max_line_length": 112, "alphanum_fraction": 0.6409769679, "num_tokens": 2171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4049845991633538}} {"text": "/*\n** LISA single subject statistical inference using 1st level GLM (general linear modeling).\n** The prewhitening approach is adapted from Worsley et al (2002), Neuroimage 15(1).\n**\n** G.Lohmann, MPI-KYB, 2018\n*/\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nextern gsl_matrix *PseudoInv(gsl_matrix *A,gsl_matrix *B);\nextern void printmat(gsl_matrix *R,char *str);\nextern void printvec(gsl_vector *x,char *str);\n\nextern void prewhite(gsl_matrix_float** pinvX,gsl_matrix_float** invM,gsl_matrix_float* X,int);\n\nextern void dfs(VFloat** Dfs,gsl_matrix_float* pinvX,gsl_matrix_float* X,gsl_matrix_float* con,int);\n\nextern void whitecov(VImage rho_vol,gsl_matrix_float* Y,gsl_matrix_float* invM,\n\t\t gsl_matrix_float* pinvX,gsl_matrix_float* X,int,int);\n\nextern void whitecov2(VImage effect_image, VImage rho_vol,\n\t\t gsl_matrix_float* Y, gsl_matrix_float* X, gsl_matrix_float* con,\n\t\t VFloat* Dfs, int, int slice);\n\n\nvoid CopySlice(gsl_matrix *Data,gsl_matrix_float *Y,VImage map,int slice)\n{\n size_t nvox;\n size_t i=0,j=0;\n double u=0;\n int ncols = VPixel(map,0,3,2,VShort);\n\n gsl_matrix_float_set_zero(Y);\n\n for (nvox=0; nvox < Data->size1; nvox++) {\n int b = VPixel(map,0,0,nvox,VShort);\n if (b != slice) continue;\n int r = VPixel(map,0,1,nvox,VShort);\n int c = VPixel(map,0,2,nvox,VShort);\n i = c + ncols*r;\n if (i >= Y->size2) continue; \n\n for (j=0; jsize2; j++) {\n u = gsl_matrix_get(Data,nvox,j);\n gsl_matrix_float_set(Y,j,i,(float)u);\n }\n }\n}\n\ngsl_matrix_float *GslFloatCpy(gsl_matrix *X)\n{\n int i,j;\n double u;\n gsl_matrix_float *Z = gsl_matrix_float_calloc(X->size2,X->size1);\n for (i=0; isize1; i++) {\n for (j=0; jsize2; j++) {\n u = gsl_matrix_get(X,i,j);\n gsl_matrix_float_set(Z,j,i,(float)u);\n }\n }\n return Z;\n}\n\n\n/*\n** general linear model (GLM) using whitening\n*/\nvoid VWhiteGLM(gsl_matrix *Data,VImage map,gsl_matrix *X0,gsl_vector *con,int numlags,VImage zmap)\n{\n int i,slice;\n int numcon=1;\n int nslices = VPixel(map,0,3,0,VShort);\n int nrows = VPixel(map,0,3,1,VShort);\n int ncols = VPixel(map,0,3,2,VShort);\n int npix = (nrows*ncols);\n int ntimesteps = Data->size2;\n\n gsl_set_error_handler_off();\n VFillImage(zmap,VAllBands,0);\n\n\n /* contrast vector */\n gsl_matrix_float *contrast = gsl_matrix_float_alloc(1,con->size);\n for (i=0; isize; i++) gsl_matrix_float_set(contrast,0,i,(float)con->data[i]);\n\n\n /* copy design matrix */\n gsl_matrix_float *X = GslFloatCpy(X0);\n\n\n /* initialize rho_vol */\n VImage rho_vol = VCreateImage(npix,nslices,numlags,VFloatRepn);\n VFillImage(rho_vol,VAllBands,0);\n\n\n /* prewhitening */\n gsl_matrix_float *pinvX=NULL,*invM=NULL;\n prewhite(&pinvX,&invM,X,numlags);\n\n\n /* degrees of freedom */\n VFloat *dfs_gsl = (VFloat *)VMalloc(sizeof(VFloat)* (numcon+1));\n dfs(&dfs_gsl,pinvX,X,contrast,numlags); \n\n\n /* first pass */\n gsl_matrix_float *Y = gsl_matrix_float_calloc(ntimesteps,npix);\n for (slice=0; slice\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define MAX_ITER 10000\n#define TOL 1.0e-6\n#define sim_num 300\n\n/** sim_num is the bootstrap replicates **/\n\n#define machine_p 1.0e-15\n#define myPHO 0.5\n#define myPI 0.01\n#define Sigma 20.0\n\nstruct fun_params {\n double *dij; \n double *zij; \n double *pj;\n int nn;\n int np;\n int mk;\n};\n\ndouble fdf_eplike(int, const double *, double *, void *);\nvoid myxij(double *, const double *, const double *, void *);\nvoid deveplike(double *, double *, const double *, double *, double *, void *);\n\ndouble maxp(double *, double *, double, const double *, double *, void *);\ndouble normf(double *, double *, double, double, const double *, double *, void *);\n\nextern int conmin(int, double *, double *, double *, int *, int *, double, int, double *, int, double, int,\n double (*)(int, const double *, double *, void *), void *);\n\nint main(int argc, char *argv[])\n{\n FILE *fpi, *fpo1, *fpo2;\n if(argc<=4) {\n printf(\"need: 1) data file name, 2) sample size n, 3) number of covariate p, and 4) the output file1 5) files2...\\n\");\n return 0;\n }\n fpi=fopen(argv[1], \"r\");\n fpo1=fopen(argv[4], \"w\");\n fpo2=fopen(argv[5], \"w\");\n \n int nn=0, np=0, i, j;\n char *cs=malloc(1000*sizeof(char));\n \n sscanf(argv[2], \"%i\", &nn);\n sscanf(argv[3], \"%i\", &np);\n \n if (np>nn) {\n printf(\"sample size should be larger than the number of covariates.\");\n return 0;\n }\n \n double *li= malloc(nn*sizeof(double)), *lia= malloc(nn*sizeof(double)), *li0=malloc(nn*sizeof(double));\n double *ri= malloc(nn*sizeof(double)), *ria= malloc(nn*sizeof(double)), *ri0=malloc(nn*sizeof(double));\n double *zij= malloc(nn*np*sizeof(double)), *zij0= malloc(nn*np*sizeof(double)), *dij=malloc(nn*nn*sizeof(double));\n double *q=malloc(nn*sizeof(double)), *p=malloc(nn*sizeof(double)), *gam= malloc(nn*nn*sizeof(double));\n \n double *pj=calloc(nn, sizeof(double)), *mypj=calloc(nn, sizeof(double));\n \n double alpha0=1.0, theta0=1.0, nvold; \n register double *tau= calloc(nn, sizeof(double));\n double past_time, now_time, mysize, tmp00;\n\n double curt, wt, u, likval1, likval2, likval;\n \n\tint j1, k, mk, ss, iter, status, iter2, cure;\n int *bsi=malloc(nn*sizeof(int)), *bsi2=malloc(nn*sizeof(int));\n \n double *ww=calloc(2*(np+1)*(np+8), sizeof(double)), \n *xx=calloc(2*(np+1), sizeof(double)), *gg=calloc(2*(np+1), sizeof(double)), fval;\n double acc=1e-11, eps=1e-5;;\n int nflag=-1, ifun=-1, ifunter=-1;\n \n struct fun_params *mydata=malloc(sizeof(struct fun_params));\n\n const gsl_rng_type *Ty;\n gsl_rng *rn;\n \n gsl_rng_env_setup();\n Ty = gsl_rng_default;\n rn = gsl_rng_alloc (Ty);\n gsl_rng_set(rn, 100);\n \n /** read the data, first line is the hearder and thus removed ***/\n fgets(cs, 1000, fpi);\n \n for (i = 0; inn = nn;\n mydata->np = np;\n \n /** sim_num is the bootstrap replicates **/\n \n for (ss=0;sszij = zij; \n gsl_sort(ria,1,nn);\n gsl_sort(lia,1,nn);\n\n /*** generate p, q data ***/\n p[0]=ria[0];\n i=j=k=0;\n do {\n while (lia[i]<=p[k] && imk=mk;\n for (i=0; idij= dij;\n \n /** Initial values **/\n \n for (j=0; jpj)=pj;\n \n for (j=0; j<=np; j++) xx[j] = 0.0;\n \n nflag=2;\n fval=9999.0;\n iter2=0;\n do {\n iter2++;\n likval2=fval;\n \n for (j = 0; j < mk; j++) tau[j]=1.0/(mydata->pj)[j];\n nvold = 0.1;\n\n /*** calculate expected Xij ***/\n myxij(gam, xx, pj, mydata);\n\n /*** Primal-dual interior-point method ***/\n \n nvold = maxp(pj, tau, nvold, xx, gam, mydata);\n \n /** minimize to get theta **/\n \n if (nflag!=0) for (j=0; j<=np; j++) xx[j] = 0.1; \n nflag= conmin(np+1, xx, &fval, gg, &ifun, &ifunter, 0.001, 300, ww, 400, 1e-18, 1, fdf_eplike, mydata);\n\n likval1=fval;\n\n } while(fabs(likval1-likval2)>0.0001 & iter2 < MAX_ITER);\n \n now_time = (double) clock ();\n\n /*** outputs ****/\n \n for(j=0; j<=np; j++) fprintf(fpo1, \"%.10f, \", xx[j]); \n fprintf(fpo1, \"%.10f, %.2f \\n\", fval, now_time/(double) CLOCKS_PER_SEC);\n for(j=0; jpj)[j]);\n fprintf(fpo2, \"%i\\n\", mk);\n }\n \n fclose(fpo1);\n fclose(fpo2);\n \n free(li);\n free(ri); \n free(zij);\n\n free(li0);\n free(ri0);\n free(zij0);\n \n free(lia);\n free(ria);\n free(p);\n free(q);\n free(mypj);\n \n free(gam); \n free(tau);\n \n free(xx);\n free(ww);\n free(gg);\n \n free(mydata);\n \n return 0;\n}\n\n/*** the expected likelihood, 0=alpha, 1=theta and the derivative ***/\n\ndouble fdf_eplike(int np1, const double *theta, double *df, void * par)\n{\n struct fun_params * param = (struct fun_params *) par;\n int i,j,j1, m=(param->mk), nn=(param->nn), tmpi;\n \n double alp0, sz, likval, msumval, tmpz, tmpz1, tmpa, tmpc, tmpd, tmp0, dfz1, dfz2;\n double *xij, *cij, *pps, pp;\n \n xij=calloc(m+1, sizeof(double));\n pps=calloc(m+1, sizeof(double));\n cij=calloc(m+1, sizeof(double));\n\n alp0=theta[0];\n \n for(j=0;jpj)[j1]) ;\n }\n\n for(j=0;jzij)[i*(np1-1)+j-1];\n tmpz=exp(alp0 + tmpz1);\n \n tmpc=0.0;\n for(j=0;jpj)[j];\n xij[j] = ((param->dij)[i*(m+1)+j]) * exp( -tmpz* pps[j]) *(1.0- exp(-pp*tmpz));\n tmpc += xij[j];\n }\n xij[m]= (param -> dij)[i*(m+1)+m] * exp(-tmpz);\n tmpc += xij[m];\n \n if (tmpc == 0.0) {\n for(j=0;j pj)[j];\n likval += ( xij[j]* log(1.0- exp(- pp* tmpz )) - cij[j] * pp * tmpz);\n msumval += (( xij[j] *exp(-pp* tmpz) /(1.0- exp(-pp* tmpz)) - cij[j] )*pp);\n }\n df[0] += ((msumval-xij[m])*tmpz);\n \n for(j=1;jzij)[i*(np1-1)+j-1]*tmpz);\n likval -= xij[m]*tmpz;\n }\n \n for(j=0;jmk), nn=(para->nn), np=(para->np);\n double *gj=calloc(m+1, sizeof(double)), *xij=calloc(m+1, sizeof(double));\n double *dij=(para->dij), *zij=(para->zij);\n \n alp0=the[0];\n \n for(j=0;jmk), nn=(para->nn), np=(para->np);\n double *zij=(para->zij);\n \n alp0=the[0];\n for(j=0;jmk);\n \n fj=calloc(m, sizeof(double));\n ffj=calloc(m, sizeof(double));\n \n deveplike(fj, ffj, the, gam, p, parm);\n \n sum1=0.0;\n for(j=0;jmk), nn=(para->nn), np=(para->np);\n double eta, nv, curnv, steps, sum1, sum2, tmp1, tmp2;\n double *fj, *ffj, *delp, *curp, *taunew, *curtau;\n\n fj = calloc(m, sizeof(double)); \n ffj = calloc(m, sizeof(double)); \n delp = calloc(m, sizeof(double)); \n curp= calloc(m, sizeof(double));\n taunew = calloc(m, sizeof(double));\n curtau = calloc(m, sizeof(double));\n \n iter=0;\n do {\n iter++;\n \n // calculate the df=fj and diag(ddf)=ffj\n \n for(j=0;j 0;\n tmp2 = 1.0;\n for(j=0;j (1.0-myPI*steps)*tmp1) {\n steps *= myPHO;\n for(j=0;j TOL)& iter < MAX_ITER*10 );\n \n free(fj);\n free(ffj);\n free(delp);\n free(curtau);\n free(taunew);\n free(curp);\n \n return nvold;\n}\n\n", "meta": {"hexsha": "373b43d92a50bdcbb24b51b17eb1e746d0140098", "size": 14236, "ext": "c", "lang": "C", "max_stars_repo_path": "data_ana.c", "max_stars_repo_name": "hliubcm/Semiparametric-Regression-Cure-Model-for-Interval-Censored-Data", "max_stars_repo_head_hexsha": "c0ec2b7f691c382329fe9f8afa95cc201223380c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data_ana.c", "max_issues_repo_name": "hliubcm/Semiparametric-Regression-Cure-Model-for-Interval-Censored-Data", "max_issues_repo_head_hexsha": "c0ec2b7f691c382329fe9f8afa95cc201223380c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data_ana.c", "max_forks_repo_name": "hliubcm/Semiparametric-Regression-Cure-Model-for-Interval-Censored-Data", "max_forks_repo_head_hexsha": "c0ec2b7f691c382329fe9f8afa95cc201223380c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9938900204, "max_line_length": 126, "alphanum_fraction": 0.4738690643, "num_tokens": 4770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.40407929975995116}} {"text": "/*\n * Copyright 2021 The DAPHNE Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n// ****************************************************************************\n// Struct for partial template specialization\n// ****************************************************************************\n\ntemplate\nstruct MatMul {\n static void apply(DTRes *& res, const DTLhs * lhs, const DTRhs * rhs, DCTX(ctx)) = delete;\n};\n\n// ****************************************************************************\n// Convenience function\n// ****************************************************************************\n\ntemplate\nvoid matMul(DTRes *& res, const DTLhs * lhs, const DTRhs * rhs, DCTX(ctx)) {\n MatMul::apply(res, lhs, rhs, ctx);\n}\n\n// ****************************************************************************\n// (Partial) template specializations for different data/value types\n// ****************************************************************************\n\n// ----------------------------------------------------------------------------\n// DenseMatrix <- DenseMatrix, DenseMatrix\n// ----------------------------------------------------------------------------\n\ntemplate<>\nstruct MatMul, DenseMatrix, DenseMatrix> {\n static void apply(DenseMatrix *& res, const DenseMatrix * lhs, const DenseMatrix * rhs, DCTX(ctx)) {\n const auto nr1 = static_cast(lhs->getNumRows());\n const auto nc1 = static_cast(lhs->getNumCols());\n const auto nc2 = static_cast(rhs->getNumCols());\n assert((nc1 == static_cast(rhs->getNumRows())) && \"#cols of lhs and #rows of rhs must be the same\");\n\n if(res == nullptr)\n res = DataObjectFactory::create>(nr1, nc2, false);\n\n if(nr1 == 1 && nc2 == 1) // Vector-Vector\n res->set(0, 0, cblas_sdot(nc1, lhs->getValues(), 1, rhs->getValues(),\n static_cast(rhs->getRowSkip())));\n else if(nc2 == 1) // Matrix-Vector\n cblas_sgemv(CblasRowMajor, CblasNoTrans, nr1, nc1, 1, lhs->getValues(),\n static_cast(lhs->getRowSkip()), rhs->getValues(),\n static_cast(rhs->getRowSkip()), 0,res->getValues(),\n static_cast(res->getRowSkip()));\n else // Matrix-Matrix\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, nr1, nc2, nc1,\n 1, lhs->getValues(), static_cast(lhs->getRowSkip()), rhs->getValues(),\n static_cast(rhs->getRowSkip()), 0, res->getValues(), static_cast(res->getRowSkip()));\n }\n};\n\ntemplate<>\nstruct MatMul, DenseMatrix, DenseMatrix> {\n static void apply(DenseMatrix *& res, const DenseMatrix * lhs, const DenseMatrix * rhs, DCTX(ctx)) {\n const auto nr1 = static_cast(lhs->getNumRows());\n const auto nc1 = static_cast(lhs->getNumCols());\n const auto nc2 = static_cast(rhs->getNumCols());\n assert((nc1 == static_cast(rhs->getNumRows())) && \"#cols of lhs and #rows of rhs must be the same\");\n\n if(res == nullptr)\n res = DataObjectFactory::create>(nr1, nc2, false);\n\n if(nr1 == 1 && nc2 == 1) // Vector-Vector\n res->set(0, 0, cblas_ddot(nc1, lhs->getValues(), 1, rhs->getValues(),\n static_cast(rhs->getRowSkip())));\n else if(nc2 == 1) // Matrix-Vector\n cblas_dgemv(CblasRowMajor, CblasNoTrans, nr1, nc1, 1, lhs->getValues(),\n static_cast(lhs->getRowSkip()), rhs->getValues(),static_cast(rhs->getRowSkip()), 0,\n res->getValues(), static_cast(res->getRowSkip()));\n else // Matrix-Matrix\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, nr1, nc2, nc1,\n 1, lhs->getValues(), static_cast(lhs->getRowSkip()), rhs->getValues(),\n static_cast(rhs->getRowSkip()), 0, res->getValues(), static_cast(res->getRowSkip()));\n }\n};\n", "meta": {"hexsha": "ef94e7af150c1908bf1cb33e8789f449b15ec066", "size": 5012, "ext": "h", "lang": "C", "max_stars_repo_path": "src/runtime/local/kernels/MatMul.h", "max_stars_repo_name": "daphne-eu/daphne", "max_stars_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T21:49:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:37:06.000Z", "max_issues_repo_path": "src/runtime/local/kernels/MatMul.h", "max_issues_repo_name": "daphne-eu/daphne", "max_issues_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-03-31T22:10:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:46:30.000Z", "max_forks_repo_path": "src/runtime/local/kernels/MatMul.h", "max_forks_repo_name": "daphne-eu/daphne", "max_forks_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.1923076923, "max_line_length": 128, "alphanum_fraction": 0.5556664006, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.40404462804307295}} {"text": "//Filters each vector in X along dim.\n//Filter IIR coefficients are given in vector A with length P+1,\n//where P is the IIR filter order (P=0 means only a0).\n//Filter FIR coefficients are given in vector B with length Q+1,\n//where Q is the FIR filter order (Q=0 means only b0).\n\n//For each vector: a0*Y[t] = (b0*X[t] + b1*X[t-1] + ... + bQ*X[t-Q]) - (a1*Y[t-1] + ... + aP*Y[t-P])\n\n//The calling program must ensure that the sizes are correct, the filter is stable, etc.\n\n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint filter_s (float *Y, const float *X, float *A, float *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t P, const size_t Q, const size_t dim);\nint filter_d (double *Y, const double *X, double *A, double *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t P, const size_t Q, const size_t dim);\nint filter_c (float *Y, const float *X, float *A, float *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t P, const size_t Q, const size_t dim);\nint filter_z (double *Y, const double *X, double *A, double *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t P, const size_t Q, const size_t dim);\n\n\nint filter_s (float *Y, const float *X, float *A, float *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t P, const size_t Q, const size_t dim)\n{\n if (dim>3u) { fprintf(stderr,\"error in filter_s: dim must be in [0 3]\\n\"); return 1; }\n\n const size_t N = R*C*S*H;\n const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n\n //Deal with a0 (usually 1) and b0; also initialize Y\n float a = *A++, b = *B++;\n if (a==1.0f)\n {\n for (size_t p=P; p>0u; --p, ++A) { *A = -*A; }\n for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = b * *X; }\n }\n else\n {\n const float b_a = b / a;\n for (size_t p=P; p>0u; --p, ++A) { *A = -*A / a; }\n for (size_t q=Q; q>0u; --q, ++B) { *B /= a; }\n for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = b_a * *X; }\n B -= Q;\n }\n A -= P; X -= N; Y -= N;\n\n if (N==0u || L==1u) {}\n else if (L==N)\n {\n //FIR\n if (L<3000u)\n {\n for (size_t q=1u; q<=Q; ++q, ++B, X-=L-q+1u, Y-=L-q)\n {\n b = *B;\n for (size_t l=q; l0u; --v)\n {\n //FIR\n if (L<30000u)\n {\n for (size_t q=1u; q<=Q; ++q, ++B)\n {\n b = *B;\n for (size_t l=q; l0u; --g, X+=BS*(L-1u), Y+=BS*(L-1u))\n {\n for (size_t bs=BS; bs>0u; --bs, ++X, Y-=K*L-1u)\n {\n //FIR\n for (size_t q=1u; q<=Q; ++q, ++B) { Y+=K; cblas_saxpy((int)(L-q),*B,X,(int)K,Y,(int)K); }\n Y -= Q*K; B -= Q;\n\n //IIR\n for (size_t l=0u; l3u) { fprintf(stderr,\"error in filter_d: dim must be in [0 3]\\n\"); return 1; }\n\n const size_t N = R*C*S*H;\n const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n\n //Deal with a0 (usually 1) and b0; also initialize Y\n double a = *A++, b = *B++;\n if (a==1.0)\n {\n for (size_t p=P; p>0u; --p, ++A) { *A = -*A; }\n for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = b * *X; }\n }\n else\n {\n const double b_a = b / a;\n for (size_t p=P; p>0u; --p, ++A) { *A = -*A / a; }\n for (size_t q=Q; q>0u; --q, ++B) { *B /= a; }\n for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = b_a * *X; }\n B -= Q;\n }\n A -= P; X -= N; Y -= N;\n\n if (N==0u || L==1u) {}\n else if (L==N)\n {\n //FIR\n if (L<3000u)\n {\n for (size_t q=1u; q<=Q; ++q, ++B, X-=L-q+1u, Y-=L-q)\n {\n b = *B;\n for (size_t l=q; l0u; --v)\n {\n //FIR\n if (L<30000u)\n {\n for (size_t q=1u; q<=Q; ++q, ++B)\n {\n b = *B;\n for (size_t l=q; l0u; --g, X+=BS*(L-1u), Y+=BS*(L-1u))\n {\n for (size_t bs=BS; bs>0u; --bs, ++X, Y-=K*L-1u)\n {\n //FIR\n for (size_t q=1u; q<=Q; ++q, ++B) { Y+=K; cblas_daxpy((int)(L-q),*B,X,(int)K,Y,(int)K); }\n Y -= Q*K; B -= Q;\n\n //IIR\n for (size_t l=0u; l3u) { fprintf(stderr,\"error in filter_c: dim must be in [0 3]\\n\"); return 1; }\n\n const size_t N = R*C*S*H;\n const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n float ar, ai, br, bi, xr, xi, yr, yi;\n\n //Deal with a0 (usually 1) and negate a1 to aP\n //Also, initialize Y\n const float b0r = *B++, b0i = *B++;\n const float a0r = *A++, a0i = *A++, a02 = a0r*a0r + a0i*a0i;\n const float b_ar = (b0r*a0r + b0i*a0i) / a02;\n const float b_ai = (b0i*a0r - b0r*a0i) / a02;\n for (size_t p=P; p>0u; --p)\n {\n ar = -*A; ai = -*(A+1u);\n *A++ = (ar*a0r + ai*a0i) / a02;\n *A++ = (ai*a0r - ar*a0i) / a02;\n }\n for (size_t q=Q; q>0u; --q)\n {\n br = *B++; bi = *B--;\n *B++ = (br*a0r + bi*a0i) / a02;\n *B++ = (bi*a0r - br*a0i) / a02;\n }\n for (size_t n=N; n>0u; --n)\n {\n xr = *X++; xi = *X++;\n *Y++ = b_ar*xr - b_ai*xi;\n *Y++ = b_ar*xi + b_ai*xr;\n }\n A -= 2u*P; B -= 2u*Q; X -= 2u*N; Y -= 2u*N;\n\n if (N==0u || L==1u) {}\n else if (L==N)\n {\n //FIR\n for (size_t q=1u; q<=Q; ++q, X-=2u*(L-q+1u), Y-=2u*(L-q))\n {\n br = *B++; bi = *B++;\n for (size_t l=q; l0u; --v)\n {\n //FIR\n for (size_t q=1u; q<=Q; ++q)\n {\n br = *B++; bi = *B++;\n for (size_t l=q; l0u; --g, X+=2u*BS*(L-1u), Y+=2u*BS*(L-1u))\n {\n for (size_t bs=BS; bs>0u; --bs, X-=2u*K*L-2u, Y-=2u*K*L-2u)\n {\n //FIR\n //for (size_t q=1u; q<=Q; X-=2u*K*(L-q), ++q)\n for (size_t q=1u; q<=Q; ++q)\n {\n br = *B++; bi = *B++;\n for (size_t l=q; l3u) { fprintf(stderr,\"error in filter_z: dim must be in [0 3]\\n\"); return 1; }\n\n const size_t N = R*C*S*H;\n const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n double ar, ai, br, bi, xr, xi, yr, yi;\n\n //Deal with a0 (usually 1) and negate a1 to aP\n //Also, initialize Y\n const double b0r = *B++, b0i = *B++;\n const double a0r = *A++, a0i = *A++, a02 = a0r*a0r + a0i*a0i;\n const double b_ar = (b0r*a0r + b0i*a0i) / a02;\n const double b_ai = (b0i*a0r - b0r*a0i) / a02;\n for (size_t p=P; p>0u; --p)\n {\n ar = -*A; ai = -*(A+1u);\n *A++ = (ar*a0r + ai*a0i) / a02;\n *A++ = (ai*a0r - ar*a0i) / a02;\n }\n for (size_t q=Q; q>0u; --q)\n {\n br = *B++; bi = *B--;\n *B++ = (br*a0r + bi*a0i) / a02;\n *B++ = (bi*a0r - br*a0i) / a02;\n }\n for (size_t n=N; n>0u; --n)\n {\n xr = *X++; xi = *X++;\n *Y++ = b_ar*xr - b_ai*xi;\n *Y++ = b_ar*xi + b_ai*xr;\n }\n A -= 2u*P; B -= 2u*Q; X -= 2u*N; Y -= 2u*N;\n\n if (N==0u || L==1u) {}\n else if (L==N)\n {\n //FIR\n for (size_t q=1u; q<=Q; ++q, X-=2u*(L-q+1u), Y-=2u*(L-q))\n {\n br = *B++; bi = *B++;\n for (size_t l=q; l0u; --v)\n {\n //FIR\n for (size_t q=1u; q<=Q; ++q)\n {\n br = *B++; bi = *B++;\n for (size_t l=q; l0u; --g, X+=2u*BS*(L-1u), Y+=2u*BS*(L-1u))\n {\n for (size_t bs=BS; bs>0u; --bs, X-=2u*K*L-2u, Y-=2u*K*L-2u)\n {\n //FIR\n for (size_t q=1u; q<=Q; ++q)\n {\n br = *B++; bi = *B++;\n for (size_t l=q; l\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\ngsl_spblas_dgemv()\n Multiply a sparse matrix and a vector\n\nInputs: alpha - scalar factor\n A - sparse matrix\n x - dense vector\n beta - scalar factor\n y - (input/output) dense vector\n\nReturn: y = alpha*op(A)*x + beta*y\n*/\n\nint\ngsl_spblas_dgemv(const CBLAS_TRANSPOSE_t TransA, const double alpha,\n const gsl_spmatrix *A, const gsl_vector *x,\n const double beta, gsl_vector *y)\n{\n const size_t M = A->size1;\n const size_t N = A->size2;\n\n if ((TransA == CblasNoTrans && N != x->size) ||\n (TransA == CblasTrans && M != x->size))\n {\n GSL_ERROR(\"invalid length of x vector\", GSL_EBADLEN);\n }\n else if ((TransA == CblasNoTrans && M != y->size) ||\n (TransA == CblasTrans && N != y->size))\n {\n GSL_ERROR(\"invalid length of y vector\", GSL_EBADLEN);\n }\n else\n {\n size_t j, p;\n size_t incX, incY;\n size_t lenX, lenY;\n double *X, *Y;\n double *Ad;\n size_t *Ap, *Ai, *Aj;\n\n if (TransA == CblasNoTrans)\n {\n lenX = N;\n lenY = M;\n }\n else\n {\n lenX = M;\n lenY = N;\n }\n\n /* form y := beta*y */\n\n Y = y->data;\n incY = y->stride;\n\n if (beta == 0.0)\n {\n size_t jy = 0;\n for (j = 0; j < lenY; ++j)\n {\n Y[jy] = 0.0;\n jy += incY;\n }\n }\n else if (beta != 1.0)\n {\n size_t jy = 0;\n for (j = 0; j < lenY; ++j)\n {\n Y[jy] *= beta;\n jy += incY;\n }\n }\n\n if (alpha == 0.0)\n return GSL_SUCCESS;\n\n /* form y := alpha*op(A)*x + y */\n Ap = A->p;\n Ad = A->data;\n X = x->data;\n incX = x->stride;\n\n if ((GSL_SPMATRIX_ISCCS(A) && (TransA == CblasNoTrans)) ||\n (GSL_SPMATRIX_ISCRS(A) && (TransA == CblasTrans)))\n {\n Ai = A->i;\n\n for (j = 0; j < lenX; ++j)\n {\n for (p = Ap[j]; p < Ap[j + 1]; ++p)\n {\n Y[Ai[p] * incY] += alpha * Ad[p] * X[j * incX];\n }\n }\n }\n else if ((GSL_SPMATRIX_ISCCS(A) && (TransA == CblasTrans)) ||\n (GSL_SPMATRIX_ISCRS(A) && (TransA == CblasNoTrans)))\n {\n Ai = A->i;\n\n for (j = 0; j < lenY; ++j)\n {\n for (p = Ap[j]; p < Ap[j + 1]; ++p)\n {\n Y[j * incY] += alpha * Ad[p] * X[Ai[p] * incX];\n }\n }\n }\n else if (GSL_SPMATRIX_ISTRIPLET(A))\n {\n if (TransA == CblasNoTrans)\n {\n Ai = A->i;\n Aj = A->p;\n }\n else\n {\n Ai = A->p;\n Aj = A->i;\n }\n\n for (p = 0; p < A->nz; ++p)\n {\n Y[Ai[p] * incY] += alpha * Ad[p] * X[Aj[p] * incX];\n }\n }\n else\n {\n GSL_ERROR(\"unsupported matrix type\", GSL_EINVAL);\n }\n\n return GSL_SUCCESS;\n }\n} /* gsl_spblas_dgemv() */\n", "meta": {"hexsha": "cadb57c31df873752b130de3610c213a74862dca", "size": 4149, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/spblas/spdgemv.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spblas/spdgemv.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spblas/spdgemv.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8443113772, "max_line_length": 81, "alphanum_fraction": 0.4738491203, "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.40395808218895957}} {"text": "/*\n * particle_filters.c\n *\n * Created on: 18 Sep 2020\n * Author: heine\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"particle_filters.h\"\n\nvoid MLbootstrapfilter(double* y, double sig_std, double obs_std, int data_length,\n double x0, int Nobs, short N_levels, long* sample_sizes, double* x_hats,\n double *filtering_time, double *Rinv0, double *Rinv1, double *worst_case_sign_ratio) {\n\n const char prog_bar[51] = \"-------------------------------------------------\";\n\n clock_t start;\n int bar_segment_count = 0;\n\n long N = 0;\n for (short i = 0; i < N_levels; i++) {\n N += sample_sizes[i];\n// printf(\"N%i = %lu, \", i, sample_sizes[i]);\n }\n// printf(\"N = %lu\\n\", N);\n\n double *X = (double*) malloc(N * sizeof(double));\n double *X_res = (double*) malloc(N * sizeof(double));\n double *W = (double*) malloc(N * sizeof(double));\n double *absW = (double*) malloc(N * sizeof(double));\n short *signs = (short*) malloc(N * sizeof(short));\n short *signs_res = (short*) malloc(N * sizeof(short));\n long *ind = (long*) malloc(N * sizeof(long));\n short *level_indicator = (short*) malloc(N * sizeof(short));\n double x_hat = 0;\n double p_hat = 0;\n\n printf(\n \"%s\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\",\n prog_bar);\n fflush(stdout);\n\n start = clock();\n\n /*\n * Initial sample and level indicator\n */\n long sample_counter = 0;\n short current_level = 0;\n gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus);\n gsl_rng_set(rng, clock());\n for (long i = 0; i < N; i++) {\n\n X[i] = gsl_ran_gaussian(rng, sig_std) + x0; // init sample\n W[i] = (double) 1.0 / (double) N; // init weights\n\n /* Construct level indicator array */\n signs_res[i] = 1;\n if (sample_counter >= sample_sizes[current_level]) {\n current_level++;\n sample_counter = 0;\n } else {\n sample_counter++;\n }\n level_indicator[i] = current_level;\n }\n\n double normaliser = 0;\n double abs_normaliser = 0;\n double diff;\n double ESS, ESSABS;\n double tmp_x_hat;\n double positive_mass, negative_mass;\n\n FILE* bpf_out = fopen(\"bpf_out.txt\", \"w\");\n\n double* raw_like = (double*) malloc(2 * N * sizeof(double));\n long *permutation = (long*) malloc(N * sizeof(long));\n\n double lap1 = 0, lap2 = 0, lap3 = 0, lap4 = 0;\n clock_t iteration_timer;\n clock_t resampling_timer;\n clock_t level_timer_start;\n double level_0_particle_cost = 0;\n double level_1_particle_cost = 0;\n double rsamp_time_per_prcl = 0;\n double time_increment;\n double scaler;\n double num, den;\n worst_case_sign_ratio[0] = 100;\n double sign_balance;\n\n /* FILTER MAIN LOOP */\n for (int n = 0; n < data_length; n++) {\n\n iteration_timer = clock(); // start the stopwatch\n level_timer_start = clock();\n /*\n * Weight calculation\n */\n normaliser = 0;\n abs_normaliser = 0;\n for (long i = 0; i < N; i++) {\n if (level_indicator[i] == 0) {\n /* Use the diagonal observation covariance */\n raw_like[i] = likelihood(n, X[i], y, 0, Rinv0, Nobs, 1);\n raw_like[N + i] = 0;\n } else {\n /* Calculate both, the diagonal and full covariance to get level 1\n * differences */\n raw_like[i] = full_likelihood(n, X[i], y, Rinv1, Nobs, 1);\n raw_like[N + i] = likelihood(n, X[i], y, 0, Rinv0, Nobs, 1);\n }\n if (i == sample_sizes[0]) {\n /* When level indicator changes take the time per particle for level 0 */\n time_increment = (double) (clock() - level_timer_start) / CLOCKS_PER_SEC\n / (double) sample_sizes[0];\n level_0_particle_cost += time_increment;\n level_timer_start = clock();\n }\n }\n /* Time per particle for level 1 */\n time_increment = (double) (clock() - level_timer_start) / CLOCKS_PER_SEC\n / (double) sample_sizes[1];\n level_1_particle_cost += time_increment;\n lap1 += (double) (clock() - iteration_timer) / CLOCKS_PER_SEC;\n \n /*\n * Find scaler for the level 0 likelihood\n * */\n if (N_levels == 2) { // Do this only for non-unilevel\n num = 0;\n den = 0;\n for (int i = (int)sample_sizes[0]; i < N; i++) {\n num += raw_like[i] * raw_like[N + i];\n den += raw_like[N + i] * raw_like[N + i];\n }\n scaler = num / den;\n scaler = isnan(scaler) ? 1 : scaler;\n /*\n * Scale all level 0 weights by 'scaler'\n * */\n for (long i = 0; i < sample_sizes[0]; i++) // level 0\n raw_like[i] *= scaler;\n\n for (long i = sample_sizes[0]; i < N; i++) // Level 1\n raw_like[N + i] *= scaler;\n }\n\n /* Actual weight calculation */\n for (long i = 0; i < N; i++) {\n\n W[i] = (raw_like[i] - raw_like[N + i]) / (double) sample_sizes[level_indicator[i]]\n * (double) signs_res[i];\n\n absW[i] = fabs(W[i]);\n signs[i] = W[i] > 0 ? 1 : -1;\n normaliser += W[i];\n abs_normaliser += absW[i];\n }\n\n /* Normalise */\n tmp_x_hat = 0;\n positive_mass = 0;\n negative_mass = 0;\n for (long i = 0; i < N; i++) {\n W[i] /= normaliser;\n if (W[i] > 0) {\n positive_mass += W[i];\n } else {\n negative_mass += fabs(W[i]);\n }\n absW[i] /= abs_normaliser;\n tmp_x_hat += X[i] * W[i];\n }\n sign_balance = positive_mass / negative_mass;\n if (sign_balance < worst_case_sign_ratio[0]) {\n worst_case_sign_ratio[0] = sign_balance;\n }\n\n ESS = 0;\n ESSABS = 0;\n for (long i = 0; i < N; i++) {\n ESS += W[i] * W[i];\n ESSABS += absW[i] * absW[i];\n }\n ESS = (double) 1.0 / ESS;\n ESSABS = (double) 1.0 / ESSABS;\n\n lap2 += (double) (clock() - iteration_timer) / CLOCKS_PER_SEC;\n\n /* Resample */\n resampling_timer = clock();\n resample(N, absW, ind, rng);\n random_permuter(permutation, N, rng);\n rsamp_time_per_prcl += (double) (clock() - resampling_timer) / CLOCKS_PER_SEC / (double) N;\n\n lap3 += (double) (clock() - iteration_timer) / CLOCKS_PER_SEC;\n\n normaliser = 0;\n for (long i = 0; i < N; i++) {\n X_res[permutation[i]] = X[ind[i]];\n signs_res[permutation[i]] = signs[ind[i]];\n normaliser += signs[ind[i]];\n }\n for (long i = 0; i < N; i++) {\n W[i] = (double) signs_res[i] / normaliser;\n }\n\n /* Calculate the output: posterior mean */\n x_hat = 0;\n for (long i = 0; i < N; i++) {\n x_hat += X_res[i] * W[i];\n }\n x_hats[n] = x_hat;\n\n /* Calculate the output: posterior variance */\n p_hat = 0;\n for (long i = 0; i < N; i++) {\n diff = X_res[i] - x_hat;\n p_hat += diff * diff * W[i];\n }\n\n /* Mutate */\n for (long i = 0; i < N; i++)\n X[i] = X_res[i] + gsl_ran_gaussian(rng, sig_std);\n\n if (floor(n * (double) 50 / data_length) > bar_segment_count) {\n printf(\"â–ˆ\");\n fflush(stdout);\n bar_segment_count++;\n }\n lap4 += (double) (clock() - iteration_timer) / CLOCKS_PER_SEC;\n\n }\n\n filtering_time[0] = (double) (clock() - start) / CLOCKS_PER_SEC / (double) data_length;\n filtering_time[1] = level_0_particle_cost / (double) data_length;\n filtering_time[2] = level_1_particle_cost / (double) data_length;\n filtering_time[3] = rsamp_time_per_prcl / (double) data_length;\n printf(\" %5.2f sec\\n\", filtering_time[0]);\n printf(\" %5.2f %5.2f %5.2f %5.2f\\n\", lap1, lap2, lap3, lap4);\n\n fclose(bpf_out);\n\n free(X);\n free(X_res);\n free(W);\n free(absW);\n free(signs);\n free(signs_res);\n free(ind);\n free(level_indicator);\n free(raw_like);\n free(permutation);\n gsl_rng_free(rng);\n\n}\n\nvoid bootstrapfilter(double* y, double sig_std, double obs_std, int data_length, double x0,\n int Nobs, long N, double* x_hats, double *filtering_time, double *Rinv, short full) {\n\n const char prog_bar[51] = \"-------------------------------------------------\";\n clock_t start;\n int bar_segment_count = 0;\n\n printf(\"Basic BPF with N = %lu\\n\", N);\n\n double *X = (double*) malloc(N * sizeof(double));\n double *X_res = (double*) malloc(N * sizeof(double));\n double *W = (double*) malloc(N * sizeof(double));\n long *ind = (long*) malloc(N * sizeof(long));\n double x_hat = 0;\n double p_hat = 0;\n\n printf(\n \"%s\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\",\n prog_bar);\n fflush(stdout);\n\n start = clock();\n\n /*\n * Initial sample and level indicator\n */\n gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus);\n gsl_rng_set(rng, clock());\n for (long i = 0; i < N; i++) {\n X[i] = gsl_ran_gaussian(rng, sig_std) + x0;\n W[i] = (double) 1.0 / (double) N;\n }\n\n double normaliser = 0;\n double diff;\n double ESS;\n\n FILE* bpf_out = fopen(\"classicbpf_out.txt\", \"w\");\n\n /* Classic BPF main loop */\n for (int n = 0; n < data_length; n++) {\n\n /* Weight calculation */\n normaliser = 0;\n\n /*\n * Weight calculation\n */\n for (long i = 0; i < N; i++) {\n if (full > 0) {\n W[i] = full_likelihood(n, X[i], y, Rinv, Nobs, 1);\n } else {\n W[i] = likelihood(n, X[i], y, 0, Rinv, Nobs, 1);\n }\n normaliser += W[i];\n }\n for (long i = 0; i < N; i++) {\n W[i] /= normaliser;\n }\n\n ESS = 0;\n for (long i = 0; i < N; i++) {\n ESS += W[i] * W[i];\n }\n ESS = (double) 1.0 / ESS;\n\n /* Resample */\n resample(N, W, ind, rng);\n for (long i = 0; i < N; i++) {\n X_res[i] = X[ind[i]];\n }\n\n /* Calculate the output: posterior mean */\n x_hat = 0;\n for (long i = 0; i < N; i++) {\n x_hat += X_res[i] / (double) N;\n }\n x_hats[n] = x_hat;\n /* Calculate the output: posterior variance */\n p_hat = 0;\n for (long i = 0; i < N; i++) {\n diff = X_res[i] - x_hat;\n p_hat += diff * diff / (double) N;\n }\n\n /* Mutate */\n for (long i = 0; i < N; i++)\n X[i] = X_res[i] + gsl_ran_gaussian(rng, sig_std);\n\n fprintf(bpf_out, \"%i %f %f %f\\n\", n, x_hat, p_hat, ESS);\n fflush(bpf_out);\n\n if (floor(n * (double) 50 / data_length) > bar_segment_count) {\n printf(\"â–ˆ\");\n fflush(stdout);\n bar_segment_count++;\n }\n }\n filtering_time[0] = (double) (clock() - start) / CLOCKS_PER_SEC / (double) data_length;\n filtering_time[1] = 0;\n filtering_time[2] = 0;\n filtering_time[3] = 0;\n printf(\" %5.2f sec\\n\", filtering_time[0]);\n\n fclose(bpf_out);\n\n free(X);\n free(X_res);\n free(W);\n free(ind);\n gsl_rng_free(rng);\n}\n\ndouble likelihood(int n, double x, double *y, int band, double *Rinv, int Nobs, double det) {\n\n double diff;\n double log_likelihood = 0;\n for (int j = 0; j < Nobs; j++) {\n diff = y[n * Nobs + j] - x;\n log_likelihood += (y[n * Nobs + j] - x) * Rinv[j * Nobs + j] * diff;\n }\n log_likelihood /= -(double) 2.0;\n return exp(log_likelihood) / det; // / sqrt(pow((2 * M_PI), Nobs) * det);\n\n}\n\ndouble full_likelihood(int n, double x, double *y, double *Rinv, int Nobs, double det) {\n\n double diff;\n double log_likelihood = 0;\n for (int j = 0; j < Nobs; j++) {\n diff = y[n * Nobs + j] - x;\n for (int i = 0; i < Nobs; i++) {\n log_likelihood += (y[n * Nobs + i] - x) * Rinv[j * Nobs + i] * diff;\n }\n }\n log_likelihood /= -(double) 2.0;\n return exp(log_likelihood); // / sqrt(pow((2 * M_PI), Nobs) * det);\n\n}\n\nvoid random_permuter(long *permutation, long N, gsl_rng *r) {\n\n for (long i = 0; i < N; i++)\n permutation[i] = i;\n\n long j;\n long tmp;\n for (long i = N - 1; i > 0; i--) {\n j = gsl_rng_uniform_int(r, i + 1);\n tmp = permutation[j];\n permutation[j] = permutation[i];\n permutation[i] = tmp;\n }\n\n}\n\nvoid resample(long size, double *w, long *ind, gsl_rng *r) {\n\n /* Generate the exponentials */\n double *e = (double*) malloc((size + 1) * sizeof(double));\n double g = 0;\n for (long i = 0; i <= size; i++) {\n e[i] = gsl_ran_exponential(r, 1.0);\n g += e[i];\n }\n /* Generate the uniform order statistics */\n double *u = (double *) malloc((size + 1) * sizeof(double));\n u[0] = 0;\n for (long i = 1; i <= size; i++)\n u[i] = u[i - 1] + e[i - 1] / g;\n\n /* Do the actual sampling with inverse cdf */\n double cdf = w[0];\n long j = 0;\n for (long i = 0; i < size; i++) {\n while (cdf < u[i + 1]) {\n j++;\n cdf += w[j];\n }\n ind[i] = j;\n }\n\n free(e);\n free(u);\n}\n", "meta": {"hexsha": "2827859bebc3751ef8cc25f89f7b4a5a4292c34a", "size": 12281, "ext": "c", "lang": "C", "max_stars_repo_path": "BIG_DATA/particle_filters.c", "max_stars_repo_name": "heinekmp/MLBPF", "max_stars_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BIG_DATA/particle_filters.c", "max_issues_repo_name": "heinekmp/MLBPF", "max_issues_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BIG_DATA/particle_filters.c", "max_forks_repo_name": "heinekmp/MLBPF", "max_forks_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1703539823, "max_line_length": 111, "alphanum_fraction": 0.5587492875, "num_tokens": 3950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.40395808218895957}} {"text": "/* specfunc/erfc.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author: J. Theiler (modifications by G. Jungman) */\n\n/*\n * See Hart et al, Computer Approximations, John Wiley and Sons, New York (1968)\n * (This applies only to the erfc8 stuff, which is the part\n * of the original code that survives. I have replaced much of\n * the other stuff with Chebyshev fits. These are simpler and\n * more precise than the original approximations. [GJ])\n */\n#include \n#include \n#include \n#include \"gsl_sf_erf.h\"\n\n#include \"check.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\n#define LogRootPi_ 0.57236494292470008706\n\n\nstatic double erfc8_sum(double x)\n{\n /* estimates erfc(x) valid for 8 < x < 100 */\n /* This is based on index 5725 in Hart et al */\n\n static double P[] = {\n 2.97886562639399288862,\n 7.409740605964741794425,\n 6.1602098531096305440906,\n 5.019049726784267463450058,\n 1.275366644729965952479585264,\n 0.5641895835477550741253201704\n };\n static double Q[] = {\n 3.3690752069827527677,\n 9.608965327192787870698,\n 17.08144074746600431571095,\n 12.0489519278551290360340491,\n 9.396034016235054150430579648,\n 2.260528520767326969591866945,\n 1.0\n };\n double num=0.0, den=0.0;\n int i;\n\n num = P[5];\n for (i=4; i>=0; --i) {\n num = x*num + P[i];\n }\n den = Q[6];\n for (i=5; i>=0; --i) {\n den = x*den + Q[i];\n }\n\n return num/den;\n}\n\ninline\nstatic double erfc8(double x)\n{\n double e;\n e = erfc8_sum(x);\n e *= exp(-x*x);\n return e;\n}\n\ninline\nstatic double log_erfc8(double x)\n{\n double e;\n e = erfc8_sum(x);\n e = log(e) - x*x;\n return e;\n}\n\n#if 0\n/* Abramowitz+Stegun, 7.2.14 */\nstatic double erfcasympsum(double x)\n{\n int i;\n double e = 1.;\n double coef = 1.;\n for (i=1; i<5; ++i) {\n /* coef *= -(2*i-1)/(2*x*x); ??? [GJ] */\n coef *= -(2*i+1)/(i*(4*x*x*x*x));\n e += coef;\n /*\n if (fabs(coef) < 1.0e-15) break;\n if (fabs(coef) > 1.0e10) break;\n \n [GJ]: These tests are not useful. This function is only\n used below. Took them out; they gum up the pipeline.\n */\n }\n return e;\n}\n#endif /* 0 */\n\n\n/* Abramowitz+Stegun, 7.1.5 */\nstatic int erfseries(double x, gsl_sf_result * result)\n{\n double coef = x;\n double e = coef;\n double del;\n int k;\n for (k=1; k<30; ++k) {\n coef *= -x*x/k;\n del = coef/(2.0*k+1.0);\n e += del;\n }\n result->val = 2.0 / M_SQRTPI * e;\n result->err = 2.0 / M_SQRTPI * (fabs(del) + GSL_DBL_EPSILON);\n return GSL_SUCCESS;\n}\n\n\n/* Chebyshev fit for erfc((t+1)/2), -1 < t < 1\n */\nstatic double erfc_xlt1_data[20] = {\n 1.06073416421769980345174155056,\n -0.42582445804381043569204735291,\n 0.04955262679620434040357683080,\n 0.00449293488768382749558001242,\n -0.00129194104658496953494224761,\n -0.00001836389292149396270416979,\n 0.00002211114704099526291538556,\n -5.23337485234257134673693179020e-7,\n -2.78184788833537885382530989578e-7,\n 1.41158092748813114560316684249e-8,\n 2.72571296330561699984539141865e-9,\n -2.06343904872070629406401492476e-10,\n -2.14273991996785367924201401812e-11,\n 2.22990255539358204580285098119e-12,\n 1.36250074650698280575807934155e-13,\n -1.95144010922293091898995913038e-14,\n -6.85627169231704599442806370690e-16,\n 1.44506492869699938239521607493e-16,\n 2.45935306460536488037576200030e-18,\n -9.29599561220523396007359328540e-19\n};\nstatic cheb_series erfc_xlt1_cs = {\n erfc_xlt1_data,\n 19,\n -1, 1,\n 12\n};\n\n/* Chebyshev fit for erfc(x) exp(x^2), 1 < x < 5, x = 2t + 3, -1 < t < 1\n */\nstatic double erfc_x15_data[25] = {\n 0.44045832024338111077637466616,\n -0.143958836762168335790826895326,\n 0.044786499817939267247056666937,\n -0.013343124200271211203618353102,\n 0.003824682739750469767692372556,\n -0.001058699227195126547306482530,\n 0.000283859419210073742736310108,\n -0.000073906170662206760483959432,\n 0.000018725312521489179015872934,\n -4.62530981164919445131297264430e-6,\n 1.11558657244432857487884006422e-6,\n -2.63098662650834130067808832725e-7,\n 6.07462122724551777372119408710e-8,\n -1.37460865539865444777251011793e-8,\n 3.05157051905475145520096717210e-9,\n -6.65174789720310713757307724790e-10,\n 1.42483346273207784489792999706e-10,\n -3.00141127395323902092018744545e-11,\n 6.22171792645348091472914001250e-12,\n -1.26994639225668496876152836555e-12,\n 2.55385883033257575402681845385e-13,\n -5.06258237507038698392265499770e-14,\n 9.89705409478327321641264227110e-15,\n -1.90685978789192181051961024995e-15,\n 3.50826648032737849245113757340e-16\n};\nstatic cheb_series erfc_x15_cs = {\n erfc_x15_data,\n 24,\n -1, 1,\n 16\n};\n\n/* Chebyshev fit for erfc(x) x exp(x^2), 5 < x < 10, x = (5t + 15)/2, -1 < t < 1\n */\nstatic double erfc_x510_data[20] = {\n 1.11684990123545698684297865808,\n 0.003736240359381998520654927536,\n -0.000916623948045470238763619870,\n 0.000199094325044940833965078819,\n -0.000040276384918650072591781859,\n 7.76515264697061049477127605790e-6,\n -1.44464794206689070402099225301e-6,\n 2.61311930343463958393485241947e-7,\n -4.61833026634844152345304095560e-8,\n 8.00253111512943601598732144340e-9,\n -1.36291114862793031395712122089e-9,\n 2.28570483090160869607683087722e-10,\n -3.78022521563251805044056974560e-11,\n 6.17253683874528285729910462130e-12,\n -9.96019290955316888445830597430e-13,\n 1.58953143706980770269506726000e-13,\n -2.51045971047162509999527428316e-14,\n 3.92607828989125810013581287560e-15,\n -6.07970619384160374392535453420e-16,\n 9.12600607264794717315507477670e-17\n};\nstatic cheb_series erfc_x510_cs = {\n erfc_x510_data,\n 19,\n -1, 1,\n 12\n};\n\n#if 0\ninline\nstatic double\nerfc_asymptotic(double x)\n{\n return exp(-x*x)/x * erfcasympsum(x) / M_SQRTPI;\n}\ninline\nstatic double\nlog_erfc_asymptotic(double x)\n{\n return log(erfcasympsum(x)/x) - x*x - LogRootPi_;\n}\n#endif /* 0 */\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_erfc_e(double x, gsl_sf_result * result)\n{\n const double ax = fabs(x);\n double e_val, e_err;\n\n /* CHECK_POINTER(result) */\n\n if(ax <= 1.0) {\n double t = 2.0*ax - 1.0;\n gsl_sf_result c;\n cheb_eval_e(&erfc_xlt1_cs, t, &c);\n e_val = c.val;\n e_err = c.err;\n }\n else if(ax <= 5.0) {\n double ex2 = exp(-x*x);\n double t = 0.5*(ax-3.0);\n gsl_sf_result c;\n cheb_eval_e(&erfc_x15_cs, t, &c);\n e_val = ex2 * c.val;\n e_err = ex2 * (c.err + 2.0*fabs(x)*GSL_DBL_EPSILON);\n }\n else if(ax < 10.0) {\n double exterm = exp(-x*x) / ax;\n double t = (2.0*ax - 15.0)/5.0;\n gsl_sf_result c;\n cheb_eval_e(&erfc_x510_cs, t, &c);\n e_val = exterm * c.val;\n e_err = exterm * (c.err + 2.0*fabs(x)*GSL_DBL_EPSILON + GSL_DBL_EPSILON);\n }\n else {\n e_val = erfc8(ax);\n e_err = (x*x + 1.0) * GSL_DBL_EPSILON * fabs(e_val);\n }\n\n if(x < 0.0) {\n result->val = 2.0 - e_val;\n result->err = e_err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n }\n else {\n result->val = e_val;\n result->err = e_err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n }\n\n return GSL_SUCCESS;\n}\n\n\nint gsl_sf_log_erfc_e(double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x*x < 10.0*GSL_ROOT6_DBL_EPSILON) {\n const double y = x / M_SQRTPI;\n /* series for -1/2 Log[Erfc[Sqrt[Pi] y]] */\n const double c3 = (4.0 - M_PI)/3.0;\n const double c4 = 2.0*(1.0 - M_PI/3.0);\n const double c5 = -0.001829764677455021; /* (96.0 - 40.0*M_PI + 3.0*M_PI*M_PI)/30.0 */\n const double c6 = 0.02629651521057465; /* 2.0*(120.0 - 60.0*M_PI + 7.0*M_PI*M_PI)/45.0 */\n const double c7 = -0.01621575378835404;\n const double c8 = 0.00125993961762116;\n const double c9 = 0.00556964649138;\n const double c10 = -0.0045563339802;\n const double c11 = 0.0009461589032;\n const double c12 = 0.0013200243174;\n const double c13 = -0.00142906;\n const double c14 = 0.00048204;\n double series = c8 + y*(c9 + y*(c10 + y*(c11 + y*(c12 + y*(c13 + c14*y)))));\n series = y*(1.0 + y*(1.0 + y*(c3 + y*(c4 + y*(c5 + y*(c6 + y*(c7 + y*series)))))));\n result->val = -2.0 * series;\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n /*\n don't like use of log1p(); added above series stuff for small x instead, should be ok [GJ]\n else if (fabs(x) < 1.0) {\n gsl_sf_result result_erf;\n gsl_sf_erf_e(x, &result_erf);\n result->val = log1p(-result_erf.val);\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n */\n else if(x > 8.0) {\n result->val = log_erfc8(x);\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n gsl_sf_result result_erfc;\n gsl_sf_erfc_e(x, &result_erfc);\n result->val = log(result_erfc.val);\n result->err = fabs(result_erfc.err / result_erfc.val);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\n\nint gsl_sf_erf_e(double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(fabs(x) < 1.0) {\n return erfseries(x, result);\n }\n else {\n gsl_sf_result result_erfc;\n gsl_sf_erfc_e(x, &result_erfc);\n result->val = 1.0 - result_erfc.val;\n result->err = result_erfc.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\n\nint gsl_sf_erf_Z_e(double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n {\n const double ex2 = exp(-x*x/2.0);\n result->val = ex2 / (M_SQRT2 * M_SQRTPI);\n result->err = fabs(x * result->val) * GSL_DBL_EPSILON;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n CHECK_UNDERFLOW(result);\n return GSL_SUCCESS;\n }\n}\n\n\nint gsl_sf_erf_Q_e(double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n {\n gsl_sf_result result_erfc;\n int stat = gsl_sf_erfc_e(x/M_SQRT2, &result_erfc);\n result->val = 0.5 * result_erfc.val;\n result->err = 0.5 * result_erfc.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat;\n }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_erfc(double x)\n{\n EVAL_RESULT(gsl_sf_erfc_e(x, &result));\n}\n\ndouble gsl_sf_log_erfc(double x)\n{\n EVAL_RESULT(gsl_sf_log_erfc_e(x, &result));\n}\n\ndouble gsl_sf_erf(double x)\n{\n EVAL_RESULT(gsl_sf_erf_e(x, &result));\n}\n\ndouble gsl_sf_erf_Z(double x)\n{\n EVAL_RESULT(gsl_sf_erf_Z_e(x, &result));\n}\n\ndouble gsl_sf_erf_Q(double x)\n{\n EVAL_RESULT(gsl_sf_erf_Q_e(x, &result));\n}\n", "meta": {"hexsha": "6b3368f80e0b1387db9ce397fa433fd01287fd1b", "size": 11176, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/erfc.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/erfc.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/erfc.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.8703703704, "max_line_length": 96, "alphanum_fraction": 0.6695597709, "num_tokens": 4209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.403953823219547}} {"text": "/*\n** Implementation of LISA algorithm\n** for statistical inference of fMRI images\n**\n** 2nd level inference using a GLM design matrix, \n** e.g. for anova designs\n**\n** G.Lohmann, 2018\n*/\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _OPENMP\n#include \n#endif /*_OPENMP*/\n\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\nextern void VIsolatedVoxels(VImage src,float threshold);\nextern void VHistogram(gsl_histogram *histogram,VString filename);\nextern void VCheckImage(VImage src);\nextern void FDR(VImage src,VImage dest,gsl_histogram *nullhist,gsl_histogram *realhist,double);\nextern double ttest1(double *data1,int n);\nextern void ImageStats(VImage src,double *,double *,double *hmin,double *hmax);\nextern void VBilateralFilter(VImage src,VImage dest,int radius,double var1,double var2,int);\nextern double VImageVar(VImage src);\nextern void VImageCount(VImage src);\nextern void VGetHistRange(VImage src,double *hmin,double *hmax);\nextern void VZScale(VImage src,float mode,float stddev);\nextern float VGetMode(VImage src);\n\nextern void XReadExchange(VString filename,int *exchange,int n);\nextern void GLM2(VImage *src,gsl_matrix *X,gsl_vector *contrast,int *,int *permtable,int *signtable,int signswitch,VImage dest);\nextern gsl_matrix *XRead2ndLevel(VString);\nextern gsl_matrix *PseudoInv(gsl_matrix *A,gsl_matrix *B);\nextern int SignSwitch (gsl_matrix *X,gsl_vector *contrast,int *);\nextern void genperm(long seed,int *exchange,int,int **,int **,int,int,gsl_vector *);\nextern void HistoUpdate(VImage,gsl_histogram *);\nextern gsl_matrix *VReadCovariates(VString,VBoolean);\n\n\n\nint main (int argc, char *argv[])\n{\n static VArgVector in_files1;\n static VString out_filename=\"\"; \n static VString design_filename=\"\";\n static VString exchange_filename=\"\";\n static VString nuisance_filename=\"\";\n static VString mask_filename=\"\";\n static VArgVector cont;\n static VFloat alpha = 0.05; \n static VShort radius = 2;\n static VFloat rvar = 2.0;\n static VFloat svar = 2.0;\n static VShort numiter = 2;\n static VShort numperm = 5000;\n static VLong seed = 99402622;\n static VBoolean centering = FALSE;\n static VBoolean demean = TRUE;\n static VBoolean cleanup = TRUE;\n static VShort nproc = 0;\n static VOptionDescRec options[] = {\n {\"in\", VStringRepn, 0, & in_files1, VRequiredOpt, NULL,\"Input files\" },\n {\"out\", VStringRepn, 1, & out_filename, VRequiredOpt, NULL,\"Output file\" }, \n {\"design\",VStringRepn,1,(VPointer) &design_filename,VRequiredOpt,NULL,\"Design file (2nd level)\"}, \n {\"grp\", VStringRepn, 1, & exchange_filename, VOptionalOpt, NULL,\"Group Ids needed for exchangeability\" },\n {\"contrast\", VFloatRepn, 0, (VPointer) &cont, VRequiredOpt, NULL, \"contrast vector\"},\n {\"nuisance\", VStringRepn, 1, & nuisance_filename, VOptionalOpt, NULL,\"Nuisance regressors\" },\n {\"demean\",VBooleanRepn,1,(VPointer) &demean,VOptionalOpt,NULL,\"Whether to subtract mean in nuisance regressors\"},\n {\"alpha\",VFloatRepn,1,(VPointer) &alpha,VOptionalOpt,NULL,\"FDR significance level\"},\n {\"perm\",VShortRepn,1,(VPointer) &numperm,VOptionalOpt,NULL,\"Number of permutations\"},\n {\"mask\", VStringRepn, 1, (VPointer) &mask_filename, VRequiredOpt, NULL, \"Mask\"}, \n {\"seed\",VLongRepn,1,(VPointer) &seed,VOptionalOpt,NULL,\"Seed for random number generation\"},\n {\"radius\",VShortRepn,1,(VPointer) &radius,VOptionalOpt,NULL,\"Bilateral parameter (radius in voxels)\"},\n {\"rvar\",VFloatRepn,1,(VPointer) &rvar,VOptionalOpt,NULL,\"Bilateral parameter (radiometric)\"},\n {\"svar\",VFloatRepn,1,(VPointer) &svar,VOptionalOpt,NULL,\"Bilateral parameter (spatial)\"},\n {\"filteriterations\",VShortRepn,1,(VPointer) &numiter,VOptionalOpt,NULL,\"Bilateral parameter (number of iterations)\"},\n {\"cleanup\",VBooleanRepn,1,(VPointer) &cleanup,VOptionalOpt,NULL,\"Whether to remove isolated voxels\"},\n {\"j\",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,\"Number of processors to use, '0' to use all\"},\n };\n FILE *fp=NULL;\n VString in_filename;\n VAttrList list1=NULL,out_list=NULL,geolist=NULL;\n VImage *src1;\n int i,j,nimages,npix=0;\n double u=0;\n char *prg_name=GetLipsiaName(\"vlisa_2ndlevel\");\n fprintf (stderr, \"%s\\n\", prg_name);\n\n\n /* parse command line */\n if (! VParseCommand (VNumber (options), options, & argc, argv)) {\n VReportUsage (argv[0], VNumber (options), options, NULL);\n exit (EXIT_FAILURE);\n }\n if (argc > 1) {\n VReportBadArgs (argc, argv);\n exit (EXIT_FAILURE);\n }\n\n\n\n /* omp-stuff */\n#ifdef _OPENMP\n int num_procs=omp_get_num_procs();\n if (nproc > 0 && nproc < num_procs) num_procs = nproc;\n fprintf(stderr,\" using %d cores\\n\",(int)num_procs);\n omp_set_num_threads(num_procs);\n#endif /* _OPENMP */\n\n\n /* images */\n VImage mask = VReadImageFile(mask_filename);\n if (mask==NULL) VError(\"Error reading mask file %s\",mask_filename);\n\n nimages = in_files1.number;\n src1 = (VImage *) VCalloc(nimages,sizeof(VImage));\n for (i = 0; i < nimages; i++) {\n in_filename = ((VString *) in_files1.vector)[i];\n list1 = VReadAttrList(in_filename,0L,TRUE,FALSE);\n VMaskMinval(list1,mask,0.0);\n src1[i] = VReadImage(list1);\n if (src1[i] == NULL) VError(\" no input image found\");\n if (VPixelRepn(src1[i]) != VFloatRepn) VError(\" input pixel repn must be float\");\n if (i == 0) npix = VImageNPixels(src1[i]);\n else if (npix != VImageNPixels(src1[i])) VError(\" inconsistent image dimensions\");\n fprintf(stderr,\" %3d: %s\\n\",i,in_filename);\n\n /* use geometry info from 1st file */\n if (geolist == NULL) geolist = VGetGeoInfo(list1);\n }\n\n\n /* get nuisance file */\n gsl_matrix *XN = NULL;\n if (strlen(nuisance_filename) > 1) {\n XN = VReadCovariates(nuisance_filename,demean);\n fprintf(stderr,\" nuisance covariates dimensions: %d x %d\\n\",(int)XN->size1,(int)XN->size2);\n if (XN->size1 != nimages) \n VError(\" number of input images (%d) does not match number of rows in nuisance covariates file (%d)\",nimages,(int)XN->size1);\n }\n\n\n \n /* get design file and its inverse */\n gsl_matrix *X0 = XRead2ndLevel(design_filename);\n fprintf(stderr,\" design file dimensions: %d x %d\\n\",(int)X0->size1,(int)X0->size2);\n if (X0->size1 != nimages) \n VError(\" number of input images (%d) does not match number of rows in design file (%d)\",nimages,(int)X0->size1);\n\n\n /* read contrast vector */\n if (cont.number != X0->size2) \n VError(\" Dimension of contrast vector (%d) does not match number of columns in design file (%d)\",cont.number,X0->size2);\n gsl_vector *contrast0 = gsl_vector_alloc(cont.number);\n for (i=0; i < cont.number; i++) {\n double u = ((VFloat *)cont.vector)[i];\n gsl_vector_set(contrast0, i, u);\n }\n\n\n /* concatenate design matrix and nuisance covariates */\n gsl_matrix *X = NULL;\n gsl_vector *contrast = NULL;\n int *permflag = NULL;\n\n /* include nuisance covariates, if present */\n if (XN != NULL) {\n permflag = (int *) VCalloc(XN->size2 + X0->size2,sizeof(int));\n for (j=0; jsize2 + X0->size2; j++) permflag[j] = 0;\n for (j=0; jsize2; j++) permflag[j] = 1;\n \n X = gsl_matrix_calloc(X0->size1, X0->size2 + XN->size2);\n for (i=0; isize1; i++) {\n for (j=0; jsize2; j++) {\n\tu = gsl_matrix_get(X0,i,j);\n\tgsl_matrix_set(X,i,j,u);\t\n }\n for (j=0; jsize2; j++) {\n\tu = gsl_matrix_get(XN,i,j);\n\tgsl_matrix_set(X,i,j+X0->size2,u);\n }\n }\n contrast = gsl_vector_calloc(cont.number + XN->size2);\n gsl_vector_set_zero(contrast);\n for (j=0; jsize; j++) gsl_vector_set(contrast,j,contrast0->data[j]);\n }\n\n /* no nuisance covariates */\n else {\n if (X0->size2 == 1) VError(\" Please use 'vlisa_onesample' for onesample tests\");\n permflag = (int *) VCalloc(X0->size2,sizeof(int));\n for (j=0; jsize2; j++) permflag[j] = 1;\n X = gsl_matrix_calloc(X0->size1,X0->size2);\n gsl_matrix_memcpy(X,X0);\n contrast = gsl_vector_calloc(cont.number);\n gsl_vector_memcpy(contrast,contrast0);\n }\n\n \n \n /* read exchangeability information */\n int *exchange = (int *) VCalloc(X->size1,sizeof(int));\n for (i=0; isize1; i++) exchange[i] = 1; /* no restrictions w.r.t. exchangeability */\n if (strlen(exchange_filename) > 1) { \n XReadExchange(exchange_filename,exchange,(int)X->size1);\n }\n\n\n /* ini random permutations and sign switching */\n int signswitch = SignSwitch(X,contrast,permflag);\n int nperm=0;\n int **permtable = (int **) VCalloc(numperm,sizeof(int *));\n int **signtable = (int **) VCalloc(numperm,sizeof(int *));\n genperm((long)seed,exchange,signswitch,permtable,signtable,(int)nimages,(int)numperm,contrast);\n\n\n\n /* estimate null variance based on first 30 permutations */\n double hmin=0,hmax=0;\n float stddev=1.0;\n if (numperm > 0) {\n int tstperm = 30;\n if (tstperm > numperm) tstperm = numperm;\n double varsum=0,nx=0;\n\n#pragma omp parallel for shared(src1,permtable) schedule(dynamic)\n for (nperm = 0; nperm < tstperm; nperm++) {\n VImage zmap = VCreateImageLike(src1[0]);\n GLM2(src1,X,contrast,permflag,permtable[nperm],signtable[nperm],signswitch,zmap);\n#pragma omp critical \n {\n\tvarsum += VImageVar(zmap);\n\tnx++;\n }\n VDestroyImage(zmap);\n }\n double meanvar = varsum/nx;\n stddev = sqrt(meanvar);\n }\n\n \n\n /* no permutation */\n int *nopermtable = (int *) VCalloc(nimages,sizeof(int));\n int *nosigntable = (int *) VCalloc(nimages,sizeof(int));\n for (i=0; i 0) VZScale(zmap1,mode,stddev);\n VBilateralFilter(zmap1,dst1,(int)radius,(double)(rvar),(double)svar,(int)numiter);\n\n\n /* ini histograms */\n VGetHistRange(dst1,&hmin,&hmax);\n size_t nbins = 20000;\n gsl_histogram *hist0 = gsl_histogram_alloc (nbins);\n gsl_histogram_set_ranges_uniform (hist0,hmin,hmax);\n gsl_histogram *histz = gsl_histogram_alloc (nbins);\n gsl_histogram_set_ranges_uniform (histz,hmin,hmax);\n HistoUpdate(dst1,histz);\n\n\n\n /* random permutations */\n#pragma omp parallel for shared(src1,permtable) schedule(dynamic)\n for (nperm = 0; nperm < numperm; nperm++) {\n if (nperm%20 == 0) fprintf(stderr,\" perm %4d of %d\\r\",nperm,(int)numperm);\n\n VImage zmap = VCreateImageLike(src1[0]);\n VImage dst = VCreateImageLike (zmap); \n GLM2(src1,X,contrast,permflag,permtable[nperm],signtable[nperm],signswitch,zmap);\n float mode=0;\n if (centering) mode = VGetMode(zmap);\n VZScale(zmap,mode,stddev);\n VBilateralFilter(zmap,dst,(int)radius,(double)(rvar),(double)svar,(int)numiter);\n\n#pragma omp critical \n {\n HistoUpdate(dst,hist0);\n }\n VDestroyImage(dst);\n VDestroyImage(zmap);\n }\n \n\n /* apply fdr */\n VImage fdrimage = VCopyImage (dst1,NULL,VAllBands);\n if (numperm > 0) {\n FDR(dst1,fdrimage,hist0,histz,(double)alpha);\n\n if (cleanup && alpha < 1.0) {\n VIsolatedVoxels(fdrimage,(float)(1.0-alpha));\n }\n }\n\n\n\n /* write output to disk */\n out_list = VCreateAttrList ();\n VHistory(VNumber(options),options,prg_name,&list1,&out_list);\n VSetGeoInfo(geolist,out_list);\n VAppendAttr (out_list,\"image\",NULL,VImageRepn,fdrimage);\n fp = VOpenOutputFile (out_filename, TRUE);\n if (! VWriteFile (fp, out_list)) exit (1);\n fclose(fp);\n fprintf (stderr, \"\\n%s: done.\\n\", argv[0]);\n exit(0);\n}\n", "meta": {"hexsha": "4f1a2e8e732ec257490f55d599ad1ca8f998968a", "size": 11973, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_2ndlevel/vlisa_2ndlevel.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_2ndlevel/vlisa_2ndlevel.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_2ndlevel/vlisa_2ndlevel.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 35.4230769231, "max_line_length": 131, "alphanum_fraction": 0.6801971102, "num_tokens": 3714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.40347426669908143}} {"text": "/* multimin/test.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"test_funcs.h\"\n\nint\ntest_fdf(const char * desc, gsl_multimin_function_fdf *f, initpt_function initpt, const gsl_multimin_fdfminimizer_type *T);\n\n\nint\nmain (void)\n{\n const gsl_multimin_fdfminimizer_type *fdfminimizers[5];\n const gsl_multimin_fdfminimizer_type ** T;\n\n gsl_ieee_env_setup ();\n\n fdfminimizers[0] = gsl_multimin_fdfminimizer_steepest_descent;\n fdfminimizers[1] = gsl_multimin_fdfminimizer_conjugate_pr;\n fdfminimizers[2] = gsl_multimin_fdfminimizer_conjugate_fr;\n fdfminimizers[3] = gsl_multimin_fdfminimizer_vector_bfgs;\n fdfminimizers[4] = 0;\n\n T = fdfminimizers;\n\n while (*T != 0) \n {\n test_fdf(\"Roth\", &roth, roth_initpt,*T);\n test_fdf(\"Wood\", &wood, wood_initpt,*T);\n test_fdf(\"Rosenbrock\", &rosenbrock, rosenbrock_initpt,*T);\n T++;\n }\n\n T = fdfminimizers;\n\n while (*T != 0) \n {\n test_fdf(\"NRoth\", &Nroth, roth_initpt,*T);\n test_fdf(\"NWood\", &Nwood, wood_initpt,*T);\n test_fdf(\"NRosenbrock\", &Nrosenbrock, rosenbrock_initpt,*T);\n T++;\n }\n\n exit (gsl_test_summary());\n}\n\nint\ntest_fdf(const char * desc, \n gsl_multimin_function_fdf *f,\n\t initpt_function initpt,\n\t const gsl_multimin_fdfminimizer_type *T)\n{\n int status;\n size_t iter = 0;\n double step_size;\n \n gsl_vector *x = gsl_vector_alloc (f->n);\n\n gsl_multimin_fdfminimizer *s;\n\n (*initpt) (x);\n\n step_size = 0.1 * gsl_blas_dnrm2 (x);\n\n s = gsl_multimin_fdfminimizer_alloc(T, f->n);\n\n gsl_multimin_fdfminimizer_set (s, f, x, step_size, 0.1);\n\n#ifdef DEBUG\n printf(\"x \"); gsl_vector_fprintf (stdout, s->x, \"%g\"); \n printf(\"g \"); gsl_vector_fprintf (stdout, s->gradient, \"%g\"); \n#endif\n\n do \n {\n iter++;\n status = gsl_multimin_fdfminimizer_iterate(s);\n\n#ifdef DEBUG\n printf(\"%i: \\n\",iter);\n printf(\"x \"); gsl_vector_fprintf (stdout, s->x, \"%g\"); \n printf(\"g \"); gsl_vector_fprintf (stdout, s->gradient, \"%g\"); \n printf(\"f(x) %g\\n\",s->f);\n printf(\"dx %g\\n\",gsl_blas_dnrm2(s->dx));\n printf(\"\\n\");\n#endif\n\n status = gsl_multimin_test_gradient(s->gradient,1e-3);\n }\n while (iter < 5000 && status == GSL_CONTINUE);\n\n status |= (fabs(s->f) > 1e-5);\n\n gsl_test(status, \"%s, on %s: %i iterations, f(x)=%g\",\n\t gsl_multimin_fdfminimizer_name(s),desc, iter, s->f);\n\n gsl_multimin_fdfminimizer_free(s);\n gsl_vector_free(x);\n\n return status;\n}\n", "meta": {"hexsha": "2ffe4b969a69bb97408b3792945e2a61a9bfac4b", "size": 3299, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/multimin/test.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/multimin/test.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/multimin/test.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 26.392, "max_line_length": 123, "alphanum_fraction": 0.6814186117, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.40322804550022384}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"libhdr\"\n#include \"Library_DFE_v1.8.h\"\n\n\n/******************************************************************************/\nint get_average_egf_vecs_1_and_2(double s,int n1, int n2, double t2_real,\n\t\t\t\t int t2_lower, int t2_upper, double *egf_vec, \n\t\t\t\t char *buffer_p1_n2_t2_lower,\n\t\t\t\t char *buffer_p2_n2_t2_lower, \n\t\t\t\t char *buffer_p1_n2_t2_upper,\n\t\t\t\t char *buffer_p2_n2_t2_upper)\n{\n static double egf_vec1_lower[maxnd+1], egf_vec2_lower[maxnd+1], \n egf_vec1_upper[maxnd+1], egf_vec2_upper[maxnd+1],\n egf_vec1[maxnd+1], egf_vec2[maxnd+1];\n double total_density;\n int i, res;\n int n1d=2*n1;\n int n2d=2*n2;\n\n if (s<-1) \n /* \n The contribution of strongly selected mutations\n is assumed to be inversely proportional to s, as\n expected from mutation selection balance, with a\n contribution from phase 2 mutations only.\n */\n {\n for (i=0; i<=2*n2; i++)\n\t{\n\t egf_vec1[i] = 0;\n\t egf_vec2[i] = 0;\n\t}\n egf_vec2[1] = -2/s;\n }\n else\n {\n res = get_binary_egf_vec(buffer_p1_n2_t2_lower, n2, t2_lower, \n\t\t\t\ts, egf_vec1_lower);\n if (res==0) return 0;\n res = get_binary_egf_vec(buffer_p2_n2_t2_lower, n2, t2_lower, \n\t\t\t\ts, egf_vec2_lower);\n if (res==0) return 0;\n res = get_binary_egf_vec(buffer_p1_n2_t2_upper, n2, t2_upper, \n\t\t\t\ts, egf_vec1_upper);\n if (res==0) return 0;\n res = get_binary_egf_vec(buffer_p2_n2_t2_upper, n2, t2_upper, \n\t\t\t\ts, egf_vec2_upper);\n if (res==0) return 0;\n\n compute_weighted_average_egf_vec(t2_real, t2_lower, t2_upper,\n\t\t\t\t egf_vec1_lower, egf_vec1_upper, egf_vec1, 2*n2);\n // monitorinput();\n compute_weighted_average_egf_vec(t2_real, t2_lower, t2_upper,\n\t\t\t\t egf_vec2_lower, egf_vec2_upper, egf_vec2, 2*n2);\n }\n\n total_density = compute_weighted_average(egf_vec, egf_vec1, egf_vec2, n1d, 2*n2);\n if (s==0)\n {\n total_density_s0 = total_density;\n // printf(\"s=0: total_density %lf\\n\", total_density);\n }\n\n return (1);\n}\n\n/******************************************************************************/\nget_upper_lower_int(double parm, int *lower, int *upper, int n_int_evaluated, int *int_evaluated_vec)\n{\n int i;\n *lower = undefined_int;\n *upper = undefined_int;\n // printf(\"get_upper_lower_int parm %lf n_int_evaluated %d\\n\",\n // parm, n_int_evaluated);\n for (i=0; i= parm)\n\t{\n\t *upper = int_evaluated_vec[i];\n\t if (i != 0) *lower = int_evaluated_vec[i-1];\n\t return;\n\t}\n }\n}\n/******************************************************************************/\nget_upper_lower_double(double parm, double*lower, double *upper,\n\t\t int n_int_evaluated, double *double_evaluated_vec)\n{\n int i;\n *lower = undefined;\n *upper = undefined;\n // printf(\"get_upper_lower_int parm %lf n_int_evaluated %d\\n\",\n // parm, n_int_evaluated);\n for (i=0; i= parm)\n\t{\n\t *upper =double_evaluated_vec[i];\n\t if (i != 0) *lower = double_evaluated_vec[i-1];\n\t return;\n\t}\n }\n}\n/******************************************************************************/\nget_s_ranges()\n{\n int i, stat, ind, i1;\n double d1, d2, d3;\n FILE *inf, *fopen();\n inf = openforreadsilent(s_range_file);\n stat = fscanf(inf, \"%d\", &nranges);\n if (stat!=1) gabort(\"get_s_ranges: input error 1\", 0);\n if (nranges >max_s_ranges)\n gabort(\"get_s_ranges: nranges >max_s_ranges\", nranges);\n for (i=1; i<=nranges; i++)\n {\n stat = fscanf(inf, \"%d %lf %lf %lf %d\", &ind, &d1, &d2, &d3, &i1);\n if (stat!=5) gabort(\"get_s_ranges: input error 2\", 0);\n if (ind!=i) gabort(\"get_s_ranges: ind!=i\", i);\n s_ranges[i].s_lower = d1;\n s_ranges[i].s_upper = d2;\n s_ranges[i].s_step = d3;\n s_ranges[i].s_lower_index = i1;\n }\n\n}\n/******************************************************************************/\nget_int_evaluated_vec(int *int_evaluated_vec, int *n_int_evaluated,\n\t\t int *int_lower, int *int_step, \n\t\t char *int_evaluated_vec_file)\n{\n int i, stat;\n FILE *inf, *fopen();\n int int_input, first_int, second_int, int_upper;\n inf = openforreadsilent(int_evaluated_vec_file);\n i = 0;\n for (;;)\n {\n stat = fscanf(inf, \"%d\", &int_input);\n if (stat==EOF) break;\n if (stat!=1) gabort(\"get_int_evaluated_vec: read error 1\", stat);\n if (*n_int_evaluated >= max_n_int_evaluated)\n\tgabort(\"Value of n_int_evaluated too large: get_int_evaluated_vec\",\n\t get_int_evaluated_vec);\n int_evaluated_vec[*n_int_evaluated] = int_input;\n // printf(\"int_evaluated_vec[%d] %d\\n\",\n // *n_int_evaluated, int_evaluated_vec[*n_int_evaluated]);\n (*n_int_evaluated)++;\n if (i==0)\n\t{\n\t first_int = int_input;\n\t *int_lower = first_int;\n\t}\n if (i==1)\n\t{\n\t second_int = int_input;\n\t}\n int_upper = int_input;\n i++;\n }\n fclose (inf);\n *int_step = second_int - first_int;\n //printf(\"int_lower %d int_upper %d int_step %d\\n\",\n // *int_lower, int_upper, *int_step);\n\n}\n/******************************************************************************/\nscale_vector(double *vec, int n2, double total_density_s0)\n{\n int i;\n double tot = 0;\n // printf(\"scale_vector: n2 %d total_density_s0 %lf\\n\", n2, total_density_s0);\n // monitorinput();\n for (i=1; i=n_s_evaluated_file) return 0;\n // printf(\"s %lf s_lower %lf s_step %lf (s - s_lower)/s_step %lf tab_num %d\\n\",\n // s, s_lower, s_step, (s - s_lower)/s_step, tab_num);\n // monitorinput();\n offset = tab_num*tab_size;\n assign_int_from_read_buff(&n_read, buffer, offset);\n // printf(\"n_read %d\\n\", n_read);\n if (n_read!=n)\n {\n // printf(\"n %d n_read %d\\n\", n, n_read);\n gabort(\"get_binary_egf_vec: read error 1\", n_read);\n }\n offset += sizeof(int);\n assign_int_from_read_buff(&t2_read, buffer, offset);\n //printf(\"t2 %d t2_read %d\\n\", t2, t2_read);\n if (t2_read!=t2) gabort(\"get_binary_egf_vec: read error 2\", t2_read);\n offset += sizeof(int);\n s_read = assign_float_from_read_buff(buffer, offset);\n // printf(\"s_read %f\\n\", s_read);\n size_of_float = sizeof(float);\n for (i=1; i<2*n; i++)\n {\n offset += size_of_float;\n // assign_float_from_read_buff - in line code for speed\n ptr = &freq_read;\n for (j=0; j counter/2; i--)\n {\n vec[j] += vec[i];\n vec[i] = 0;\n j++;\n\n }\n}\n/******************************************************************************/\nfold_vector_int(int *vec, int counter)\n{\n int i, j;\n j = 1;\n for (i=counter - 1; i > counter/2; i--)\n {\n vec[j] += vec[i];\n vec[i] = 0;\n j++;\n\n }\n}\n/******************************************************************************/\nint nearest_n2_ind(int n2_real)\n{\n int i, ind = undefined_int;\n double min = undefined, diff, res;\n for (i=0; i diff)\n\t {\n\t min = diff;\n\t ind = i;\n\t }\n\t}\n }\n if (ind == undefined_int) gabort(\"nearest_n2: ind == undefined_int\", ind);\n res = n2_evaluated_vec[ind];;\n // printf(\"nearest_n2: n2_real %lf result %lf\\n\", n2_real, res);\n // monitorinput();\n return ind;\n}\n/******************************************************************************/\nread_phase1_phase2_file_into_buffer(int n1, int phase, int n2, int t2, \n\t\t\t\t char *buffer,\n\t\t\t\t int file_size_bytes)\n{\n static char n1_str[max_str_len], n2_str[max_str_len], t2_str[max_str_len];\n char file_str[max_str_len];\n int n2d;\n FILE *inf, *fopen();\n\n // printf(\"read_phase1_phase2_file_into_buffer: phase %d n2 %d t2 %d\\n\",\n // phase, n2, t2);\n n2d = 2*n2;\n int_to_string(n1, n1_str, max_str_len);\n\n int_to_string(n2, n2_str, max_str_len);\n\n int_to_string(t2, t2_str, max_str_len);\n\n if (strlen(n1_str) + strlen(n2_str) + strlen(t2_str) >= max_str_len)\n gabort(\"read_phase1_phase2_file_into_buffer: string too long\", max_str_len);\n if (phase==1) \n {\n strcpy(file_str, phase_1_dir);\n strcat(file_str, \"/n1:\");\n strcat(file_str, n1_str);\n strcat(file_str, \":\");\n }\n else\n {\n strcpy(file_str, phase_2_dir);\n strcat(file_str, \"/\");\n }\n strcat(file_str, \"n2:\");\n strcat(file_str, n2_str);\n strcat(file_str, \":t2:\");\n strcat(file_str, t2_str);\n\n inf = openforreadsilent(file_str);\n fread(buffer, 1, file_size_bytes, inf);\n fclose(inf);\n}\n/******************************************************************************/\nread_const_pop_file_into_buffer(int n1, char *buffer, int file_size_bytes)\n{\n char file_str[max_str_len];\n FILE *inf, *fopen();\n\n // printf(\"read_const_pop_file_into_buffer: n1 %d file_size_bytes %d\\n\",\n // n1, file_size_bytes);\n strcpy(file_str, const_pop_dir);\n strcat(file_str, const_pop_file);\n // printf(\"read_const_pop_file_into_buffer: file_str %s\\n\", file_str);\n // monitorinput();\n inf = openforreadsilent(file_str);\n fread(buffer, 1, file_size_bytes, inf);\n fclose(inf);\n}\n/******************************************************************************/\ncompute_weighted_average_egf_vec(double t2_real, int t2_lower, int t2_upper,\n\t\t\t\t double *egf_vec_lower, double *egf_vec_upper,\n\t\t\t\t double *egf_vec, int n2d)\n{\n int i;\n for (i=0; i<=n2d; i++)\n {\n egf_vec[i] = egf_vec_lower[i] + (egf_vec_upper[i] - egf_vec_lower[i])*(t2_real - (double)t2_lower)/(double)(t2_upper - t2_lower);\n }\n}\n/******************************************************************************/\ndouble compute_weighted_average(double *weighted_vec, double *phase1_mut_vec,\n\t\t\t\tdouble *phase2_mut_vec, int n1d, int n2d)\n{\n int i;\n double total = 0;\n for (i=1; i= s_lower)&&(s <= s_upper))\n\t{\n\t s_step = s_ranges[i].s_step;\n\t tab_num = (int)(floor((s - s_lower)/s_step + 0.0000000001));\n\t return(tab_num + s_ranges[i].s_lower_index - 1); \n\t}\n }\n gabort(\"compute_s_tab_num: failure to find tab_num\", 0);\n}\n/******************************************************************************/\nint compute_file_size_bytes(int n)\n{\n int tab_size, file_size_bytes;\n tab_size = (2*sizeof(int)+sizeof(float) + sizeof(float)*(2*n - 1));\n file_size_bytes = n_s_evaluated_file*tab_size;\n return (file_size_bytes);\n}\n/******************************************************************************/\nset_up_file_name(int n1, char *froot, char *file_name)\n{\n int len;\n static char n1_str[max_str_len];\n int_to_string(n1, n1_str, max_str_len);\n // printf(\"set_up_file_name n1 %d froot %s n1_str %s\\n\", n1, froot, n1_str);\n // monitorinput();\n len = strlen(data_path);\n len += strlen(n1_str) + 1;\n len += strlen(froot);\n if (len >= max_str_len) gabort(\"set_up_file_name: string too long (1)\", len);\n strcpy(file_name, data_path);\n strcat(file_name, \"n1_\");\n strcat(file_name, n1_str);\n strcat(file_name, \"/\");\n strcat(file_name, froot);\n // printf(\"set_up_file_name n1 file_name %s\\n\", file_name);\n // monitorinput();\n}\n/******************************************************************************/\nget_data_path(char *data_path)\n{\n FILE *inf, *fopen();\n int stat;\n inf = openforread(\"directory_config.dat\");\n stat = fscanf(inf, \"%s\", data_path);\n if (stat!=1) gabort(\"get_data_path: read error\", 1);\n // printf(\"get_data_path: data_path %s\\n\", data_path); monitorinput();\n}\n/******************************************************************************/\nget_s_evaluated_vec(double *s_evaluated_vec, int *n_s_evaluated,\n\t\t int *n_s_evaluated_file, char *s_evaluated_vec_file)\n{\n int stat;\n FILE *inf, *fopen();\n double s;\n *n_s_evaluated = 0;\n inf = openforreadsilent(s_evaluated_vec_file);\n s = -100.0; // Set up large |s| values specially\n while (s < -1)\n {\n s_evaluated_vec[*n_s_evaluated] = s;\n (*n_s_evaluated)++;\n if (s > -20) s = s + 1.0; else s = s + 5.0;\n }\n *n_s_evaluated_file = 0;\n for (;;)\n {\n stat = fscanf(inf, \"%lf\", &s);\n if (stat==EOF) break;\n if (stat!=1) gabort(\"get_s_limits: read error 1\", stat);\n if (*n_s_evaluated >= max_n_s_evaluated)\n\tgabort(\"Value of n_s_evaluated too large: get_s_evaluated_vec\",\n\t get_s_evaluated_vec);\n s_evaluated_vec[*n_s_evaluated] = s;\n (*n_s_evaluated)++;\n (*n_s_evaluated_file)++;\n }\n fclose (inf);\n // printf(\"n_s_evaluated %d n_s_evaluated_file %d\\n\", *n_s_evaluated,\n // *n_s_evaluated_file);\n // monitorinput();\n}\n/******************************************************************************/\nget_lower_upper(int ind, double *s_evaluated_vec, int n_s_evaluated,\n\t\tdouble *lower, double *upper)\n{\n double x, temp_r;\n if ((ind<0)||(ind>=n_s_evaluated))\n gabort(\"get_lower_upper: ind out of range\", ind);\n x = s_evaluated_vec[ind];\n if (ind 150) z = 150;\n a[row][0] = exp(z);\n y = a[row][0]; /*add up for later*/\n for (j = 1;j<=n; j++)\n {\n\n z = z + log(((double)n + 1.0 - (double)j)/(double)j) + x;\n /* cumulative binomial coeff.*/\n a[row][j] = exp(z);\n y = y + a[row][j]; /*add up*/\n }\n if (y == 0.0) y = .0000000000001;\n for (j=0; j<=n; j++) a[row][j] = a[row][j]/y;\n}\n/******************************************************************************/\nsetupmatrix(double **a, int n1, int n2, double s, double h)\n{\n int i;\n double p;\n\n\n for (i = 1; i<=n1 - 1; i++) /*do variable rows*/\n {\n p = (double)i/(double)n1;\n p = selfn(p, s,h);\n setuprow(a, p, i, n2);\n }\n for (i = 0; i<=n2; i++)\n { /*do constant edges*/\n a[0][i] = 0;\n a[n1][i] = 0;\n }\n a[0][0] = 1.0; /*do absorbing corners*/\n a[n1][n2] = 1.0;\n\n}\n/******************************************************************************/\nmatrixinvert(int N, double **a,double *inverter)\n{\n\n int i, j, lotkin_signum;\n gsl_matrix *lotkin_a,*lotkin_inv;\n gsl_vector *x, *lotkin_b, *lotkin_x;\n\n gsl_permutation *lotkin_perm;\n\n /* allocate a, x, b */\n lotkin_a = gsl_matrix_alloc(N-1, N-1);\n lotkin_inv = gsl_matrix_alloc(N-1, N-1);\n x = gsl_vector_alloc(N-1);\n lotkin_b = gsl_vector_alloc(N-1);\n\n lotkin_x = gsl_vector_alloc(N-1);\n\n gsl_matrix *identity=gsl_matrix_alloc(N-1, N-1);\n\n\n for (i = 0; i<=N-2; i++)\n {\n for (j = 0; j<=N-2; j++)\n\t{\n gsl_matrix_set( identity, i, i,1);\n\t}\n ;\n }\n\n for (i = 0; i<=N-2; i++)\n {\n for (j = 0; j<=N-2; j++)\n\t{\n\t gsl_matrix_set(lotkin_a,i,j,gsl_matrix_get(identity,i,j)-a[i+1][j+1]);\n\t}\n\n }\n\n\n /* LU decomposition and forward&backward substition */\n\n //gsl_blas_dgemv(CblasNoTrans, 1.0, lotkin_a, x, 0.0, lotkin_b);\n\n lotkin_perm = gsl_permutation_alloc(N-1);\n gsl_linalg_LU_decomp(lotkin_a, lotkin_perm, &lotkin_signum);\n gsl_linalg_LU_solve(lotkin_a, lotkin_perm, lotkin_b, lotkin_x);\n gsl_linalg_LU_invert (lotkin_a,lotkin_perm, lotkin_inv);\n\n /*apparently the inversion adds +1 to the first element of the vector\n so I substract it*/\n\n gsl_matrix_set(lotkin_inv,0,0,gsl_matrix_get(lotkin_inv,0,0)-1);\n\n //printf(\"\\n%s\\n\", \"Equilibrium\");\n\n for (i = 0; i<1; i++)\n {\n for (j = 0; j<=N-2; j++)\n\t{\n\n\t // printf(\"%d: %2.3f \",j,gsl_matrix_get(lotkin_inv, i, j));\n\t}\n //printf(\"\\n\");\n }\n\n\n for (i=0;i<=N-2;i++){\n\n inverter[i+1]=gsl_matrix_get(lotkin_inv,0,i);\n\n }\n\n gsl_matrix_free(lotkin_a);\n gsl_matrix_free(lotkin_inv);\n gsl_vector_free(x);\n gsl_vector_free(lotkin_b);\n gsl_vector_free(lotkin_x);\n gsl_matrix_free(identity);\n gsl_permutation_free(lotkin_perm);\n}\n/******************************************************************************/\ntmiterate(double **a,double *mut1,\n\t int t, int n1, int n2,int decay,double *sumf)\n{\n\n int k, i, j = 0;\n double z;\n\n double * steadystatefreq = (double*) calloc (maxnd+1, sizeof(double));\n double * mut2 = (double*) calloc (maxnd+1, sizeof(double));\n\n\n for (k =1 ;k<=t; k++)\n { /*t iterations*/\n\n /* Increment steadystatefreq. distribution*/\n for (i = 0; i<=n1; i++)\n\t{\n\t steadystatefreq[i] = steadystatefreq[i] + mut1[i];\n\t}\n\n /* Perform matrix multiplication*/\n for (i = 0; i<=n2; i++)\n\t{\n\t z = 0;\n\t for (j = 0; j<=n1; j++)\n\t {\n\t z = z + a[j][i]*mut1[j];\n\t }\n\t mut2[i] = z;\n\t}\n\n /* Copy result of multiplication*/\n for (i=0; i<=n2; i++) {mut1[i] = mut2[i];\n\n\tif (decay==0){\n\t sumf[i]+=mut1[i];}\n\tif(decay==1){sumf[i]=mut1[i];}\n }\n\n\n }\n\n free(steadystatefreq);\n free(mut2);\n}\n/******************************************************************************/\ntmiterate2(double **a,double *mut1,\n\t int t, int n1, int n2,int decay,double **a1)\n{\n\n double * steadystatefreq = (double*) calloc (maxnd+1, sizeof(double));\n double * mut2 = (double*) calloc (maxnd+1, sizeof(double));\n\n\n int k, i, j = 0;\n double z;\n\n\n\n for (k = 1; k<=t; k++){ /*t iterations*/\n\n /* Increment steadystatefreq. distribution*/\n for (i = 0; i<=n1; i++)\n {\n\tsteadystatefreq[i] = steadystatefreq[i] + mut1[i];\n }\n\n /* Perform matrix multiplication*/\n for (i = 0; i<=n2; i++)\n {\n\tz = 0;\n\tfor (j = 0; j<=n1; j++)\n\t {\n z = z + a[j][i]*mut1[j];\n\t }\n\tmut2[i] = z;\n }\n\n /* Copy result of multiplication*/\n for (i=0; i<=n2; i++) {mut1[i] = mut2[i];\n\n if (decay==0){\n\n\ta1[k][i]+=mut1[i];\n\tif (k>1){a1[k][i]+=a1[k-1][i];}\n }\n\n if(decay==1){\n \n\ta1[k][i]=mut1[i];\n\t//if (k>0){ a1[k][i]+=a1[k-1][i];}\n }\n }\n\n //dumpvector(a1[k],0,n2,\"matrix\");\n }\n\n free(steadystatefreq);\n free(mut2);\n\n}\n/******************************************************************************/\neqf_using_matrix_inversion(int n1,double s,double **a,double *egf_out)\n{\n setupmatrix(a, n1, n1, s, H);\n matrixinvert(n1,a,egf_out);\n}\n/******************************************************************************/\nvector_average(int n1,int n2,double *fv1,double *fv2, double *fv_out)\n{\n int i;\n for (i=0;i 0);\n}\n/******************************************************************************/\ndouble randomly_select_allele_frequency(double *egf_vec, double *temp1, int nd)\n{\n double u, freq;\n int ind;\n ind = binarysearchcumulative_from_zero(egf_vec, nd-1);\n // printf(\"ind %d\\n\", ind);\n (temp1[ind])++;\n freq = (double)ind/(double)nd;\n // printf(\"ind %d freq %lf\\n\", ind, freq); monitorinput();\n return(freq);\n}\n/******************************************************************************/\nset_up_cumulative_allele_freq_vec(int nd, double *egf_vec, double *cum_vec,\n\t\t\t\t char *str)\n{\n int i;\n for (i=0; i= s)\n {\n s_upper = s_evaluated_vec[i];\n s_ind = i;\n if (i != 0 ) s_lower = s_evaluated_vec[i-1];\n break;\n }\n }\n if ((s_lower==undefined)||(s_upper==undefined)) return 0;\n p_upper = (s - s_lower)/(s_upper - s_lower);\n// printf(\"set_up_gamma_density_vec_equal_effects: s_lower %lf s_upper %lf\\n\",\n// s_lower, s_upper);\n// printf(\"p_upper %lf\\n\", p_upper);\n// monitorinput();\n gamma_density_vec[s_ind] = p_upper;\n if (s_ind==1)\n gamma_density_vec[s_ind] += (1.0 - p_upper);\n else\n gamma_density_vec[s_ind-1] = (1.0 - p_upper);\n// for (i=1; i0){printf(\"%f\\n\",gamma_density_vec[0]);}\n return (1);\n}\n/******************************************************************************/\ndouble compute_beta_densities(double alpha, double *s_evaluated_vec,\n\t\t\t int n_s_evaluated, \n\t\t\t double *gamma_density_vec, double beta)\n{\n int i;\n double lower, upper, area, total_area = 0.0, x, diff, step, inc_x, inc_y, gf;\n\n if (alpha <= 0) return undefined;\n if (beta <= 0) return undefined;\n \n for (i=0; i\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/c_math/gsl_linalg_extra.h\"\n#include \"common/c_math/linalg_common.h\"\n\n#if defined(__arm__)\n// Turn off any error handling by the GSL library. The standard way\n// of doing this is with gsl_set_error_handler_off; however this\n// method does not require bringing in more components of GSL.\nvoid gsl_error(const char *reason, const char *file, int line, int gsl_errno) {\n (void)reason;\n (void)file;\n (void)line;\n (void)gsl_errno;\n}\n#endif // defined(__arm__)\n\n// Operations on vectors with any number of elements.\n\nbool VecIsSize(const Vec *v, int32_t l) { return v != NULL && l == v->length; }\n\ndouble *VecPtr(const Vec *v, int32_t i) {\n assert(0 <= i && i < v->length);\n return &v->d[i];\n}\n\ndouble VecGet(const Vec *v, int32_t i) {\n assert(0 <= i && i < v->length);\n return v->d[i];\n}\n\n// v = [0, 0, ... ]\nconst Vec *VecZero(Vec *v) {\n for (int32_t i = 0; i < v->length; ++i) {\n v->d[i] = 0.0;\n }\n return v;\n}\n\n// v_out = a*v + v_out\nconst Vec *VecAxpy(double a, const Vec *v, Vec *v_out) {\n assert(v->length == v_out->length);\n for (int32_t i = 0; i < v->length; ++i) {\n v_out->d[i] += a * v->d[i];\n }\n return v_out;\n}\n\n// Changes the length of a vector. Returns true on success, false\n// otherwise.\nbool VecResize(int32_t length, Vec *v) {\n if (v->length == length) {\n return true;\n } else if (v->variable_len && 0 <= length && length <= v->max_length) {\n v->length = length;\n return true;\n }\n assert(false);\n return false;\n}\n\n// v_out = v_in\nconst Vec *VecCopy(const Vec *v_in, Vec *v_out) {\n VecResize(v_in->length, v_out);\n for (int32_t i = 0; i < v_out->length; ++i) {\n v_out->d[i] = v_in->d[i];\n }\n return v_out;\n}\n\n// Copy the contents of an array in a Vec.\nconst Vec *VecInit(const double a_in[], int32_t length, Vec *v_out) {\n VecResize(length, v_out);\n for (int32_t i = 0; i < v_out->length; ++i) {\n v_out->d[i] = a_in[i];\n }\n return v_out;\n}\n\n// v_out = scale * v_in\nconst Vec *VecScale(const Vec *v_in, double scale, Vec *v_out) {\n VecResize(v_in->length, v_out);\n for (int32_t i = 0; i < v_in->length; ++i) {\n v_out->d[i] = scale * v_in->d[i];\n }\n return v_out;\n}\n\n// v_out = v0 + v1\nconst Vec *VecAdd(const Vec *v0, const Vec *v1, Vec *v_out) {\n assert(v0->length == v1->length);\n VecResize(v0->length, v_out);\n for (int32_t i = 0; i < v_out->length; ++i) {\n v_out->d[i] = v0->d[i] + v1->d[i];\n }\n return v_out;\n}\n\n// v_out = v0 + v1 + v2\nconst Vec *VecAdd3(const Vec *v0, const Vec *v1, const Vec *v2, Vec *v_out) {\n assert(v0->length == v1->length && v0->length == v2->length);\n VecResize(v0->length, v_out);\n for (int32_t i = 0; i < v_out->length; ++i) {\n v_out->d[i] = v0->d[i] + v1->d[i] + v2->d[i];\n }\n return v_out;\n}\n\n// v_out = v0 - v1\nconst Vec *VecSub(const Vec *v0, const Vec *v1, Vec *v_out) {\n assert(v0->length == v1->length);\n VecResize(v0->length, v_out);\n for (int32_t i = 0; i < v_out->length; ++i) {\n v_out->d[i] = v0->d[i] - v1->d[i];\n }\n return v_out;\n}\n\n// v_out = c0 * v0 + c1 * v1\nconst Vec *VecLinComb(double c0, const Vec *v0, double c1, const Vec *v1,\n Vec *v_out) {\n assert(v0->length == v1->length);\n VecResize(v0->length, v_out);\n for (int32_t i = 0; i < v_out->length; ++i) {\n v_out->d[i] = c0 * v0->d[i] + c1 * v1->d[i];\n }\n return v_out;\n}\n\n// v_out = c0 * v0 + c1 * v1 + c2 * v2\nconst Vec *VecLinComb3(double c0, const Vec *v0, double c1, const Vec *v1,\n double c2, const Vec *v2, Vec *v_out) {\n assert(v0->length == v1->length && v0->length == v2->length);\n VecResize(v0->length, v_out);\n for (int32_t i = 0; i < v_out->length; ++i) {\n v_out->d[i] = c0 * v0->d[i] + c1 * v1->d[i] + c2 * v2->d[i];\n }\n return v_out;\n}\n\n// v_out = v0 .* v1\nconst Vec *VecMult(const Vec *v0, const Vec *v1, Vec *v_out) {\n assert(v0->length == v1->length);\n VecResize(v0->length, v_out);\n for (int32_t i = 0; i < v_out->length; ++i) {\n v_out->d[i] = v0->d[i] * v1->d[i];\n }\n return v_out;\n}\n\n// v0^T * v1\ndouble VecDot(const Vec *v0, const Vec *v1) {\n assert(v0->length == v1->length);\n double tmp = 0.0;\n for (int32_t i = 0; i < v0->length; ++i) {\n tmp += v0->d[i] * v1->d[i];\n }\n return tmp;\n}\n\n// Computes the 2-norm of a vector.\n//\n// TODO: This does not yet handle overflow and underflow\n// gracefully.\ndouble VecNorm(const Vec *v) { return sqrt(VecNormSquared(v)); }\n\ndouble VecNormBound(const Vec *v, double low) { return fmax(low, VecNorm(v)); }\n\ndouble VecNormSquared(const Vec *v) { return VecDot(v, v); }\n\nconst Vec *VecNormalize(const Vec *v_in, Vec *v_out) {\n return VecScale(v_in, 1.0 / VecNormBound(v_in, 1e-9), v_out);\n}\n\n// Return the elements of v_in where inds != 0. The MATLAB logical indexing\n// equivalent is: v_out = v_in(inds).\nconst Vec *VecSlice(const Vec *v_in, const int32_t inds[], Vec *v_out) {\n int32_t i_out = 0;\n for (int32_t i = 0; i < v_in->length; ++i) {\n if (inds[i]) {\n assert(i_out < v_out->max_length);\n // Don't use VecPtr here because we haven't set v_out->length yet.\n v_out->d[i_out] = VecGet(v_in, i);\n i_out++;\n }\n }\n\n // Do not resize v_out until the end of the function if you want to\n // be able to reuse and input as an output.\n VecResize(i_out, v_out);\n return v_out;\n}\n\n// Assigns elements of a larger vector with those from a smaller one. The\n// MATLAB logical indexing equivalent is: v_out(inds) = v_in. The sum(inds != 0)\n// must be equal to length(v_in). Warning: there is no check that\n// length(inds) == length(v_out).\nconst Vec *VecSliceSet(const Vec *v_in, const int32_t inds[], Vec *v_out) {\n assert(v_in != v_out);\n\n int32_t i_in = 0;\n for (int32_t i = 0; i < v_out->length; ++i) {\n if (inds[i]) {\n *VecPtr(v_out, i) = VecGet(v_in, i_in);\n i_in++;\n }\n }\n\n // Assert that the sum(inds != 0) is equal to length(v_in).\n assert(v_in->length == i_in);\n\n return v_out;\n}\n\n// Operations on arbitrary matrices.\n\nbool MatIsSize(const Mat *m, int32_t nr, int32_t nc) {\n return m != NULL && m->nr == nr && m->nc == nc;\n}\n\ndouble *MatPtr(const Mat *m, int32_t i, int32_t j) {\n assert(i < m->nr && j < m->nc);\n return &m->d[i * m->nc + j];\n}\n\ndouble MatGet(const Mat *m, int32_t i, int32_t j) {\n assert(i < m->nr && j < m->nc);\n return m->d[i * m->nc + j];\n}\n\nbool MatResize(int32_t nr, int32_t nc, Mat *m) {\n if (m->nr == nr && m->nc == nc) {\n return true;\n } else if (m->variable_dim && nr * nc <= m->max_size) {\n m->nr = nr;\n m->nc = nc;\n return true;\n }\n assert(false);\n return false;\n}\n\n// Copy the contents of an array into a Mat.\nconst Mat *MatInit(const double *d, int32_t nr, int32_t nc, Mat *m) {\n MatResize(nr, nc, m);\n for (int32_t i = 0; i < m->nr; ++i) {\n for (int32_t j = 0; j < m->nc; ++j) {\n *MatPtr(m, i, j) = d[i * m->nc + j];\n }\n }\n return m;\n}\n\n// m_out = scale * m_in\nconst Mat *MatScale(const Mat *m_in, double scale, Mat *m_out) {\n MatResize(m_in->nr, m_in->nc, m_out);\n for (int32_t i = 0; i < m_out->nr; ++i) {\n for (int32_t j = 0; j < m_out->nc; ++j) {\n *MatPtr(m_out, i, j) = scale * MatGet(m_in, i, j);\n }\n }\n return m_out;\n}\n\nconst Mat *MatZero(Mat *m) {\n MatArrZero(m->nr, m->nc, m->d);\n return m;\n}\n\nconst Mat *MatCopy(const Mat *a, Mat *b) {\n if (a != b) { // No work to do if the Mat pointers are equal.\n MatResize(a->nr, a->nc, b);\n // This is still safe if the data pointers are equal.\n MatArrCopy(a->d, a->nr, a->nc, b->d);\n }\n return b;\n}\n\n// Copies the sub-matrix src(start_row + (1:num_rows), start_col + (1:num_cols))\n// into dest(dest_row + (1:num_rows), dest_col + (1:num_cols)).\n//\n// It is not safe for src and dest to share any memory.\n//\n// Returns:\n// A pointer to dest.\nconst Mat *MatSubmatSet(const Mat *src, int32_t start_row, int32_t start_col,\n int32_t num_rows, int32_t num_cols, int32_t dest_row,\n int32_t dest_col, Mat *dest) {\n assert(src != dest && src->d != dest->d);\n assert(start_row >= 0 && start_col >= 0);\n assert(num_rows >= 0 && num_cols >= 0);\n assert(dest_row >= 0 && dest_col >= 0);\n // Make sure there is sufficient data and sufficient room.\n assert(src->nr >= start_row + num_rows && src->nc >= start_col + num_cols);\n assert(dest->nr >= dest_row + num_rows && dest->nc >= dest_col + num_cols);\n\n for (int32_t i = 0; i < num_rows; ++i) {\n for (int32_t j = 0; j < num_cols; ++j) {\n *MatPtr(dest, dest_row + i, dest_col + j) =\n MatGet(src, i + start_row, j + start_col);\n }\n }\n return dest;\n}\n\nconst Mat *MatI(int32_t n, Mat *m) {\n MatResize(n, n, m);\n MatArrI(n, m->d);\n return m;\n}\n\nconst Mat *MatMult(const Mat *m1, const Mat *m2, Mat *m_out) {\n assert(m1->nc == m2->nr);\n MatResize(m1->nr, m2->nc, m_out);\n MatArrMult(m1->d, m1->nr, m1->nc, m2->d, m2->nc, m_out->d);\n return m_out;\n}\n\n// Generalized matrix-vector multiply.\n//\n// z = alpha*op(a)*x + beta*y.\n//\n// Args:\n// ta: Indicates if a should be transposed.\n// alpha, a, x, beta: See formula above.\n// y: Can be NULL if beta = 0.0.\n// z: Resulting vector. It is safe to reuse y as z.\nconst Vec *MatVecGenMult(TransposeType ta, double alpha, const Mat *a,\n const Vec *x, double beta, const Vec *y, Vec *z) {\n assert(a != NULL && x != NULL && z != NULL);\n assert((ta == kNoTrans ? a->nc : a->nr) == x->length);\n const int32_t zl = (ta == kNoTrans) ? a->nr : a->nc;\n assert(y == NULL || y->length == zl);\n assert(y != NULL || beta == 0.0);\n if (y == NULL) beta = 0.0;\n\n if (y == NULL || beta == 0.0) {\n VecResize(zl, z);\n } else {\n VecCopy(y, z);\n }\n\n MatArrGemv(ta, alpha, a->d, a->nr, a->nc, x->d, beta, z->d);\n return z;\n}\n\n// Generalized matrix-matrix multiply.\n//\n// d = alpha*op(a)*op(b) + beta*c.\n//\n// Args:\n// ta: Indicates if a should be transposed.\n// tb: Indicates if b should be transposed.\n// alpha, a, b, beta: See above formula.\n// c: Can be NULL if beta = 0.0.\n// d: Resulting matrix. It is safe to reuse c as d.\nconst Mat *MatGenMult(TransposeType ta, TransposeType tb, double alpha,\n const Mat *a, const Mat *b, double beta, const Mat *c,\n Mat *d) {\n assert(a != NULL && b != NULL && d != NULL);\n assert((ta == kNoTrans ? a->nc : a->nr) == (tb == kNoTrans ? b->nr : b->nc));\n const int32_t nr_d = (ta == kNoTrans ? a->nr : a->nc);\n const int32_t nc_d = (tb == kNoTrans ? b->nc : b->nr);\n assert(c == NULL || (c->nr == nr_d && c->nc == nc_d));\n assert(c != NULL || beta == 0.0);\n if (c == NULL) beta = 0.0;\n\n if (c == NULL || beta == 0.0)\n MatResize(nr_d, nc_d, d);\n else\n MatCopy(c, d);\n\n MatArrGemm(ta, tb, alpha, a->d, a->nr, a->nc, b->d, nc_d, beta, d->d);\n return d;\n}\n\nconst Mat *MatMult3(const Mat *m0, const Mat *m1, const Mat *m2, Mat *m_out) {\n assert(m0->nc == m1->nr && m1->nc == m2->nr);\n MatResize(m0->nr, m2->nc, m_out);\n MAT(m0->nr, m1->nc, m0m1);\n return MatMult(MatMult(m0, m1, &m0m1), m2, m_out);\n}\n\nconst Vec *MatVecMult(const Mat *m, const Vec *v_in, Vec *v_out) {\n assert(m->nc == v_in->length);\n VecResize(m->nr, v_out);\n MatArrMult(m->d, m->nr, m->nc, v_in->d, 1, v_out->d);\n return v_out;\n}\n\nconst Vec *MatTransVecMult(const Mat *m, const Vec *v_in, Vec *v_out) {\n assert(m->nr == v_in->length);\n VecResize(m->nc, v_out);\n MatArrGemm(kTrans, kNoTrans, 1.0, m->d, m->nr, m->nc, v_in->d, 1, 0.0,\n v_out->d);\n return v_out;\n}\n\nconst Mat *MatTrans(const Mat *m, Mat *m_out) {\n MatResize(m->nc, m->nr, m_out);\n MatArrTrans(m->d, m->nr, m->nc, m_out->d);\n return m_out;\n}\n\nconst Mat *MatAdd(const Mat *m0, const Mat *m1, Mat *m_out) {\n assert(m0->nr == m1->nr && m0->nc == m1->nc);\n MatResize(m0->nr, m0->nc, m_out);\n for (int32_t i = 0; i < m0->nr; ++i) {\n for (int32_t j = 0; j < m0->nc; ++j) {\n *MatPtr(m_out, i, j) = MatGet(m0, i, j) + MatGet(m1, i, j);\n }\n }\n return m_out;\n}\n\nconst Mat *MatSub(const Mat *m0, const Mat *m1, Mat *m_out) {\n assert(m0->nr == m1->nr && m0->nc == m1->nc);\n MatResize(m0->nr, m0->nc, m_out);\n for (int32_t i = 0; i < m0->nr; ++i) {\n for (int32_t j = 0; j < m0->nc; ++j) {\n *MatPtr(m_out, i, j) = MatGet(m0, i, j) - MatGet(m1, i, j);\n }\n }\n return m_out;\n}\n\nvoid MatQrDecomp(const Mat *A, Mat *Q, Mat *R) {\n MatResize(A->nr, A->nc, R);\n double *Qd = NULL;\n if (Q != NULL) {\n MatResize(A->nr, A->nr, Q);\n Qd = Q->d;\n }\n MatArrQrDecomp(A->d, A->nr, A->nc, Qd, R->d);\n}\n\n// Calculates the \"thin\" singular value decomposition of an m x n\n// matrix A, defined by:\n//\n// A = U * S * V'\n//\n// where U is an m x n column-orthogonal matrix (i.e. U'*U = I), S is\n// an n x n diagonal matrix with non-decreasing elements, and V is an\n// n x n orthogonal matrix (i.e. V'*V = V*V' = I). The \"thin\" aspect\n// is equivalent to MATLAB's \"economy\" SVD.\n//\n// Args:\n// A: Input m x n matrix with m >= n.\n// U: Output m x n column-orthogonal matrix.\n// s: Output n length vector of the diagonal elements of S.\n// V: Output n x n orthogonal matrix.\n//\n// Returns:\n// kLinalgErrorNone on success and kLinalgErrorMaxIter if GSL's\n// solver reached its maximum number of iterations.\nint32_t MatThinSvDecomp(const Mat *A, Mat *U, Vec *s, Mat *V) {\n assert(A != NULL && U != NULL && s != NULL && V != NULL);\n assert(A->nc <= VEC_MAX_ELEMENTS);\n assert(A->nr >= A->nc);\n\n MatCopy(A, U);\n VecResize(A->nc, s);\n MatResize(A->nc, A->nc, V);\n\n double work_data[VEC_MAX_ELEMENTS];\n gsl_matrix_view U_gsl =\n gsl_matrix_view_array(U->d, (size_t)U->nr, (size_t)U->nc);\n gsl_matrix_view V_gsl =\n gsl_matrix_view_array(V->d, (size_t)V->nr, (size_t)V->nc);\n gsl_vector_view s_gsl = gsl_vector_view_array(s->d, (size_t)s->length);\n gsl_vector_view work = gsl_vector_view_array(work_data, (size_t)s->length);\n int32_t ret = gsl_linalg_SV_decomp(&U_gsl.matrix, &V_gsl.matrix,\n &s_gsl.vector, &work.vector);\n // These are the only errors that gsl_linalg_SV_decomp should ever\n // return, assuming we're passing in matrices and vectors of the\n // appropriate sizes.\n assert(ret == GSL_SUCCESS || ret == GSL_EMAXITER);\n\n if (ret == GSL_EMAXITER) {\n assert(false);\n return kLinalgErrorMaxIter;\n }\n return kLinalgErrorNone;\n}\n\n// Calculates the rank of a matrix. Performs a QR decomposition (with\n// pivoting) of the input matrix and finds the number of diagonal\n// elements of R with magnitude greater than a specified tolerance.\n//\n// Args:\n// A: Input matrix.\n// tol: Tolerance for checking linear independence of vectors.\n//\n// Returns:\n// Rank of the matrix.\nint32_t MatRank(const Mat *A, double tol) {\n assert(A != NULL);\n assert(A->nr * A->nc <= MAT_MAX_ELEMENTS);\n assert(A->nr <= VEC_MAX_ELEMENTS && A->nc <= VEC_MAX_ELEMENTS);\n assert(tol >= DBL_EPSILON);\n\n int32_t min_dim = (A->nr < A->nc) ? A->nr : A->nc;\n if (min_dim == 0) return 0;\n\n double qr_data[MAT_MAX_ELEMENTS];\n double tau_data[VEC_MAX_ELEMENTS];\n double norm_data[VEC_MAX_ELEMENTS];\n size_t perm_data[VEC_MAX_ELEMENTS];\n int signum;\n gsl_matrix_const_view A_gsl =\n gsl_matrix_const_view_array(A->d, (size_t)A->nr, (size_t)A->nc);\n gsl_matrix_view QR =\n gsl_matrix_view_array(qr_data, (size_t)A->nr, (size_t)A->nc);\n gsl_vector_view tau = gsl_vector_view_array(tau_data, (size_t)min_dim);\n gsl_permutation p = {(size_t)A->nc, perm_data};\n gsl_vector_view norm = gsl_vector_view_array(norm_data, (size_t)A->nc);\n\n gsl_matrix_memcpy(&QR.matrix, &A_gsl.matrix);\n int32_t ret = gsl_linalg_QRPT_decomp(&QR.matrix, &tau.vector, &p, &signum,\n &norm.vector);\n assert(ret == GSL_SUCCESS);\n (void)ret;\n\n int32_t rank = 0;\n while (rank < min_dim) {\n if (fabs(gsl_matrix_get(&QR.matrix, (size_t)rank, (size_t)rank)) <= tol) {\n break;\n }\n rank++;\n }\n\n return rank;\n}\n\n// Solves A*x = b for x similar to x = A \\ b.\nint32_t MatVecLeftDivide(const Mat *A, const Vec *b, Vec *x) {\n assert(A != NULL && b != NULL && x != NULL);\n assert(b != x);\n assert(A->nr == b->length && A->nr > 0);\n VecResize(A->nc, x);\n if (A->nc == 0) return kLinalgErrorNone;\n\n size_t m = (size_t)A->nr, n = (size_t)A->nc;\n gsl_matrix_const_view A_gsl = gsl_matrix_const_view_array(A->d, m, n);\n gsl_matrix_const_view b_gsl = gsl_matrix_const_view_array(b->d, m, 1U);\n gsl_matrix_view x_gsl = gsl_matrix_view_array(x->d, n, 1U);\n int32_t ret =\n GslMatrixDivide(CblasLeft, &A_gsl.matrix, &b_gsl.matrix, &x_gsl.matrix);\n assert(ret == GSL_SUCCESS || ret == GSL_ESING);\n return (ret == GSL_ESING) ? kLinalgErrorSingularMat : kLinalgErrorNone;\n}\n\n// Solves x*A = b for x similar to x = b / A.\nint32_t MatVecRightDivide(const Mat *A, const Vec *b, Vec *x) {\n assert(A != NULL && b != NULL && x != NULL);\n assert(b != x);\n assert(A->nc == b->length && A->nc > 0);\n VecResize(A->nr, x);\n if (A->nr == 0) return kLinalgErrorNone;\n\n size_t m = (size_t)A->nr, n = (size_t)A->nc;\n gsl_matrix_const_view A_gsl = gsl_matrix_const_view_array(A->d, m, n);\n gsl_matrix_const_view b_gsl = gsl_matrix_const_view_array(b->d, 1U, n);\n gsl_matrix_view x_gsl = gsl_matrix_view_array(x->d, 1U, m);\n int32_t ret =\n GslMatrixDivide(CblasRight, &A_gsl.matrix, &b_gsl.matrix, &x_gsl.matrix);\n assert(ret == GSL_SUCCESS || ret == GSL_ESING);\n return (ret == GSL_ESING) ? kLinalgErrorSingularMat : kLinalgErrorNone;\n}\n\n// Solves A*X = b for X similar to X = A \\ B.\nint32_t MatMatLeftDivide(const Mat *A, const Mat *B, Mat *X) {\n assert(A != NULL && B != NULL && X != NULL);\n assert(A != X && B != X);\n assert(A->nr == B->nr && A->nr > 0);\n MatResize(A->nc, B->nc, X);\n if (A->nc == 0) return kLinalgErrorNone;\n\n size_t m = (size_t)A->nr, n = (size_t)A->nc, k = (size_t)B->nc;\n gsl_matrix_const_view A_gsl = gsl_matrix_const_view_array(A->d, m, n);\n gsl_matrix_const_view B_gsl = gsl_matrix_const_view_array(B->d, m, k);\n gsl_matrix_view X_gsl = gsl_matrix_view_array(X->d, n, k);\n int32_t ret =\n GslMatrixDivide(CblasLeft, &A_gsl.matrix, &B_gsl.matrix, &X_gsl.matrix);\n assert(ret == GSL_SUCCESS || ret == GSL_ESING);\n return (ret == GSL_ESING) ? kLinalgErrorSingularMat : kLinalgErrorNone;\n}\n\n// Solves X*A = B for X similar to X = B / A.\nint32_t MatMatRightDivide(const Mat *A, const Mat *B, Mat *X) {\n assert(A != NULL && B != NULL && X != NULL);\n assert(A != X && B != X);\n assert(A->nc == B->nc && A->nc > 0);\n MatResize(B->nr, A->nr, X);\n if (A->nr == 0) return kLinalgErrorNone;\n\n size_t m = (size_t)A->nr, n = (size_t)A->nc, k = (size_t)B->nr;\n gsl_matrix_const_view A_gsl = gsl_matrix_const_view_array(A->d, m, n);\n gsl_matrix_const_view B_gsl = gsl_matrix_const_view_array(B->d, k, n);\n gsl_matrix_view X_gsl = gsl_matrix_view_array(X->d, k, m);\n int32_t ret =\n GslMatrixDivide(CblasRight, &A_gsl.matrix, &B_gsl.matrix, &X_gsl.matrix);\n assert(ret == GSL_SUCCESS || ret == GSL_ESING);\n return (ret == GSL_ESING) ? kLinalgErrorSingularMat : kLinalgErrorNone;\n}\n\nbool MatIsUpperTriangular(const Mat *r) {\n return MatArrIsUpperTriangular(r->d, r->nr, r->nc);\n}\n\nbool MatIsLowerTriangular(const Mat *l) {\n return MatArrIsLowerTriangular(l->d, l->nr, l->nc);\n}\n\nbool MatHasNonnegDiag(const Mat *m) {\n assert(m != NULL);\n for (int32_t i = 0; i < m->nc && i < m->nr; ++i) {\n if (MatGet(m, i, i) < 0.0) return false;\n }\n return true;\n}\n\n// Calculates the matrix square root of P = A'*A + B'*B by calculating a QR\n// decomposition, Q*R = [A ; B]. It is assumed that the matrix [A ; B] is full\n// row rank (i.e. has linearly independent columns).\n//\n// Q is an orthogonal matrix and R \"trapezoidal matrix\", i.e. R = [sqrt_P ; 0]\n// where sqrt_P is upper triangular. Thus:\n// P = A'*A + B'*B = [A ; B]'*[A ; B] = [sqrT_P ; 0]'*Q'*Q*[sqrt_P ; 0].\n//\n// Args:\n// A: na-by-nc matrix.\n// B: nb-by-nc matrix.\n// sqrt_P: Upper-triangular matrix with positive diagonal elements such that\n// sqrt_P'*sqrt_P = P.\n//\n// Note: it is safe to reuse A or B as sqrt_P (assuming shapes match).\nvoid MatSqrtSum(const Mat *A, const Mat *B, Mat *sqrt_P) {\n assert(A != NULL && B != NULL && sqrt_P != NULL);\n assert(A->nc == B->nc);\n assert(A->nr + B->nr >= A->nc); // This is required for full row rank.\n MatResize(A->nc, A->nc, sqrt_P);\n\n // Define a temporary matrix, stack = [A ; B].\n MAT(A->nr + B->nr, A->nc, stack);\n MatSubmatSet(A, 0, 0, A->nr, A->nc, 0, 0, &stack);\n MatSubmatSet(B, 0, 0, B->nr, B->nc, A->nr, 0, &stack);\n MatQrDecomp(&stack, NULL, &stack);\n MatSubmatSet(&stack, 0, 0, A->nc, A->nc, 0, 0, sqrt_P);\n // Next, enforce a non-negative diagonal.\n for (int32_t i = 0; i < sqrt_P->nr; ++i) {\n if (MatGet(sqrt_P, i, i) < 0.0) {\n for (int32_t j = i; j < sqrt_P->nc; ++j) {\n *MatPtr(sqrt_P, i, j) *= -1.0;\n }\n }\n }\n}\n\nint32_t MatMatBackSub(const Mat *R, const Mat *b, Mat *x) {\n assert(b->nr == R->nr && b->nc == x->nc);\n assert(x->nr == R->nc);\n return MatArrBackSub(R->d, R->nr, R->nc, b->d, b->nc, x->d);\n}\n\nint32_t MatMatForwardSub(const Mat *L, const Mat *b, Mat *x) {\n assert(b->nr == L->nr && b->nc == x->nc);\n assert(x->nr == L->nc);\n return MatArrForwardSub(L->d, L->nr, L->nc, b->d, b->nc, x->d);\n}\n\nint32_t MatVecBackSub(const Mat *R, const Vec *b, Vec *x) {\n assert(b->length == R->nr);\n assert(x->length == R->nc);\n return MatArrBackSub(R->d, R->nr, R->nc, b->d, 1, x->d);\n}\n\nint32_t MatVecForwardSub(const Mat *L, const Vec *b, Vec *x) {\n assert(b->length == L->nr);\n assert(x->length == L->nc);\n return MatArrForwardSub(L->d, L->nr, L->nc, b->d, 1, x->d);\n}\n\n// Returns the rows and columns of m where rows != 0 and cols != 0\nconst Mat *MatSlice(const Mat *m, const int32_t rows[], const int32_t cols[],\n Mat *m_out) {\n int32_t nr_out = 0, nc_out = 0;\n if (rows == NULL) {\n nr_out = m->nr;\n } else {\n for (int32_t i = 0; i < m->nr; ++i)\n if (rows[i]) nr_out++;\n }\n if (cols == NULL) {\n nc_out = m->nc;\n } else {\n for (int32_t i = 0; i < m->nc; ++i)\n if (cols[i]) nc_out++;\n }\n\n if (m_out->variable_dim) {\n assert(nr_out * nc_out <= m_out->max_size);\n } else {\n assert(m_out->nr == nr_out && m_out->nc == nc_out);\n }\n\n int32_t i_out = 0;\n for (int32_t i = 0; i < m->nr; ++i) {\n if (rows == NULL || rows[i]) {\n int32_t j_out = 0;\n for (int32_t j = 0; j < m->nc; ++j) {\n if (cols == NULL || cols[j]) {\n // Don't use MatPtr here because we haven't set m_out->nc yet.\n m_out->d[i_out * nc_out + j_out] = MatGet(m, i, j);\n j_out++;\n }\n }\n i_out++;\n }\n }\n\n // Do not resize m until the end of the function if you want to be\n // able to reuse the input as the output. Otherwise, the matrix\n // indexing in MatGet will be off.\n MatResize(nr_out, nc_out, m_out);\n return m_out;\n}\n\nconst double *MatArrMult(const double *m1, int32_t nr1, int32_t nc1,\n const double *m2, int32_t nc2, double *m_out) {\n assert(m_out != m1 && m_out != m2);\n return MatArrGemm(kNoTrans, kNoTrans, 1.0, m1, nr1, nc1, m2, nc2, 0.0, m_out);\n}\n\n// This is modeled after the BLAS function GEMV, which calculates:\n// y <-- alpha*op(A)*x + beta*y,\n// where op either returns the matrix or its transpose.\n//\n// Args:\n// ta: Whether to transpose A.\n// alpha: See above formula.\n// a: Data for A.\n// nra: Number of rows of A without transpose applied.\n// nca: Number of columns of A without transpose applied.\n// x: Data for x.\n// beta: See above formula.\n// c: Data for y.\nconst double *MatArrGemv(TransposeType ta, double alpha, const double *a,\n int32_t nra, int32_t nca, const double *x, double beta,\n double *y) {\n assert(x != y);\n int32_t ly = ((ta == kNoTrans) ? nra : nca);\n int32_t lx = ((ta == kNoTrans) ? nca : nra);\n double aij, axj;\n for (int32_t i = 0; i < ly; ++i) { // For each entry of y.\n axj = 0.0;\n for (int32_t j = 0; j < lx; ++j) { // Walk down the row of op(A).\n aij = (ta == kNoTrans) ? a[i * nca + j] : a[j * nca + i];\n axj += aij * x[j];\n }\n if (beta == 0.0) {\n y[i] = alpha * axj;\n } else {\n y[i] = alpha * axj + beta * y[i];\n }\n }\n return y;\n}\n\n// This is modeled after the BLAS function GEMM, which calculates:\n// C <-- alpha*op(A)*op(B) + beta*C,\n// where op either returns the matrix or its transpose.\n//\n// Args:\n// ta: Whether to transpose A.\n// tb: Whether to transpose B.\n// alpha: See above formula.\n// a: Data for A.\n// nra: Number of rows of A without transpose applied.\n// nca: Number of columns of A without transpose applied.\n// b: Data for B.\n// ncc: Number of columns of C.\n// beta: See above formula.\n// c: Data for C.\nconst double *MatArrGemm(TransposeType ta, TransposeType tb, double alpha,\n const double *a, int32_t nra, int32_t nca,\n const double *b, int32_t ncc, double beta, double *c) {\n assert(a != c && b != c);\n int32_t nrc = (ta == kNoTrans) ? nra : nca;\n int32_t nk = (ta == kNoTrans) ? nca : nra;\n double ABij, aik, bkj;\n for (int32_t i = 0; i < nrc; ++i) {\n for (int32_t j = 0; j < ncc; ++j) {\n ABij = 0.0;\n for (int32_t k = 0; k < nk; ++k) {\n aik = (ta == kNoTrans) ? a[i * nca + k] : a[k * nca + i];\n bkj = (tb == kNoTrans) ? b[k * ncc + j] : b[j * nk + k];\n ABij += aik * bkj;\n }\n if (beta == 0.0) {\n c[i * ncc + j] = alpha * ABij;\n } else {\n c[i * ncc + j] = alpha * ABij + beta * c[i * ncc + j];\n }\n }\n }\n return c;\n}\n\nconst double *MatArrZero(int32_t nr, int32_t nc, double *m_out) {\n for (int32_t i = 0; i < nr; ++i) {\n for (int32_t j = 0; j < nc; ++j) {\n m_out[i * nc + j] = 0.0;\n }\n }\n return m_out;\n}\n\nvoid MatArrCopy(const double *d_in, int32_t nr, int32_t nc, double *d_out) {\n for (int32_t i = 0; i < nr; ++i) {\n for (int32_t j = 0; j < nc; ++j) {\n d_out[i * nc + j] = d_in[i * nc + j];\n }\n }\n}\n\nvoid MatArrTrans(const double *m_in, int32_t nr, int32_t nc, double *m_out) {\n assert(m_out != m_in && m_out != NULL);\n for (int32_t i = 0; i < nr; ++i) {\n for (int32_t j = 0; j < nc; ++j) {\n m_out[j * nr + i] = m_in[i * nc + j];\n }\n }\n}\n\nconst double *MatArrI(int32_t nr, double *m_out) {\n MatArrZero(nr, nr, m_out);\n for (int32_t i = 0; i < nr; ++i) {\n m_out[i * nr + i] = 1.0;\n }\n return m_out;\n}\n\n// QR decomposition. Decompose a matrix into orthogonal and\n// upper-right-triangular components.\n//\n// You may reuse a as r, and you may skip calculating q by passing a\n// NULL pointer.\nvoid MatArrQrDecomp(const double *a, int32_t nr, int32_t nc, double *q,\n double *r) {\n assert(q != a && r != q && r != NULL);\n assert(nr <= VEC_MAX_ELEMENTS && nc <= VEC_MAX_ELEMENTS);\n\n double tau_data[VEC_MAX_ELEMENTS];\n gsl_matrix_const_view A =\n gsl_matrix_const_view_array(a, (size_t)nr, (size_t)nc);\n gsl_matrix_view QR = gsl_matrix_view_array(r, (size_t)nr, (size_t)nc);\n gsl_vector_view tau =\n gsl_vector_view_array(tau_data, (nr < nc) ? (size_t)nr : (size_t)nc);\n gsl_matrix_memcpy(&QR.matrix, &A.matrix);\n gsl_linalg_QR_decomp(&QR.matrix, &tau.vector);\n\n if (q != NULL) {\n gsl_matrix_view Q = gsl_matrix_view_array(q, (size_t)nr, (size_t)nr);\n gsl_matrix_view R = gsl_matrix_view_array(r, (size_t)nr, (size_t)nc);\n gsl_linalg_QR_unpack(&QR.matrix, &tau.vector, &Q.matrix, &R.matrix);\n } else {\n for (int32_t i = 1; i < nr; ++i) {\n for (int32_t j = 0; j < i && j < nc; ++j) {\n r[i * nc + j] = 0.0;\n }\n }\n }\n}\n\nbool MatArrIsUpperTriangular(const double *r, int32_t nr, int32_t nc) {\n for (int32_t i = 1; i < nr; ++i) {\n for (int32_t j = 0; j < i && j < nc; ++j) {\n if (fabs(r[i * nc + j]) >= DBL_EPSILON) {\n return false;\n }\n }\n }\n return true;\n}\n\nbool MatArrIsLowerTriangular(const double *l, int32_t nr, int32_t nc) {\n for (int32_t i = 0; i < nr; ++i) {\n for (int32_t j = i + 1; j < nc; ++j) {\n if (fabs(l[i * nc + j]) >= DBL_EPSILON) {\n return false;\n }\n }\n }\n return true;\n}\n\n// Solves R*X = B using back substitution where R is an upper\n// triangular matrix. If the triangular matrix contains a zero\n// diagonal element (i.e. the matrix is singular), we set the\n// corresponding x element to zero.\n//\n// Returns kLinalgErrorNone on success and kLinalgErrorSingularMat\n// if the matrix was singular.\n//\n// Note: Confirmed safe to reuse b as x.\nint32_t MatArrBackSub(const double *r, int32_t nr, int32_t nc, const double *b,\n int32_t nc_b, double *x) {\n assert(r != x);\n assert(nr >= nc);\n assert(nr >= 0 && nc >= 0 && nc_b >= 0);\n assert(MatArrIsUpperTriangular(r, nr, nc));\n (void)nr;\n\n int32_t err = kLinalgErrorNone;\n // Solve for the k-th column of x.\n for (int32_t k = 0; k < nc_b; ++k) {\n // Iterate over the rows of r.\n for (int32_t i = nc - 1; i >= 0; --i) {\n if (fabs(r[i * nc + i]) <= DBL_EPSILON) {\n err = kLinalgErrorSingularMat;\n x[i * nc_b + k] = 0.0;\n } else {\n double sum = 0.0;\n for (int32_t j = nc - 1; j > i; --j) {\n sum += x[j * nc_b + k] * r[i * nc + j];\n }\n x[i * nc_b + k] = (b[i * nc_b + k] - sum) / r[i * nc + i];\n }\n }\n // TODO: If nr > nc, then the bottom of r is all zeros.\n // Should we test if b has non-zero elements for these rows?\n }\n return err;\n}\n\n// Solves L*X = B using forward substitution where L is a lower\n// triangular matrix. If the triangular matrix contains a zero\n// diagonal element (i.e. the matrix is singular), we set the\n// corresponding x element to zero.\n//\n// Returns kLinalgErrorNone on success and kLinalgErrorSingularMat\n// if the matrix is singular.\n//\n// Note: Confirmed safe to reuse b as x.\nint32_t MatArrForwardSub(const double *l, int32_t nr, int32_t nc,\n const double *b, int32_t nc_b, double *x) {\n assert(nr <= nc);\n assert(MatArrIsLowerTriangular(l, nr, nc));\n int32_t err = kLinalgErrorNone;\n for (int32_t k = 0; k < nc_b; ++k) { // Solve for the k-th column of x.\n for (int32_t i = 0; i < nr; ++i) { // Iterate over the rows of l.\n if (fabs(l[i * nc + i]) <= DBL_EPSILON) {\n err = kLinalgErrorSingularMat;\n x[i * nc_b + k] = 0.0;\n } else {\n double sum = 0.0;\n for (int32_t j = 0; j < i; ++j) {\n sum += x[j * nc_b + k] * l[i * nc + j];\n }\n x[i * nc_b + k] = (b[i * nc_b + k] - sum) / l[i * nc + i];\n }\n }\n for (int32_t i = nr; i < nc; ++i) {\n x[i * nc_b + k] = 0.0;\n }\n }\n return err;\n}\n", "meta": {"hexsha": "0246d36202731d91f7b4536d70f3ab74d4a0120b", "size": 31459, "ext": "c", "lang": "C", "max_stars_repo_path": "common/c_math/linalg.c", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "common/c_math/linalg.c", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "common/c_math/linalg.c", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 31.4904904905, "max_line_length": 80, "alphanum_fraction": 0.5940112527, "num_tokens": 10905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.40263493288248625}} {"text": "#include \"globals.h\"\n#include \"peano.h\"\n#include \n\n\npeanoKey Peano_Key ( const double x, const double y, const double z );\nstatic void reorder_particles();\n\nvoid Print_Int_Bits128 ( const peanoKey val )\n{\n for ( int i = 127; i >= 0; i-- ) {\n\n printf ( \"%llu\", ( long long ) ( ( val & ( ( peanoKey ) 1 << i ) ) >> i ) );\n\n if ( i % 3 == 0 && i != 0 ) {\n printf ( \".\" );\n }\n }\n printf ( \"\\n\" );\n fflush ( stdout );\n\n return ;\n}\n\nvoid Print_Int_Bits128r ( const peanoKey val )\n{\n for ( int i = 127; i >= 0; i-- ) {\n\n printf ( \"%llu\", ( long long ) ( ( val & ( ( peanoKey ) 1 << i ) ) >> i ) );\n\n if ( i % 3 - 2 == 0 && i != 0 ) {\n printf ( \".\" );\n }\n }\n printf ( \"\\n\" );\n fflush ( stdout );\n\n return ;\n}\n\nint compare_peanoKeys ( const void *a, const void *b )\n{\n const peanoKey *x = ( const peanoKey * ) a;\n const peanoKey *y = ( const peanoKey * ) b;\n\n return ( int ) ( *x > *y ) - ( *x < *y );\n}\n\nstatic peanoKey *Keys = NULL;\nstatic size_t *Idx = NULL;\n\nvoid Sort_Particles_By_Peano_Key()\n{\n if ( Keys == NULL ) {\n Keys = malloc ( Param.Npart * sizeof ( *Keys ) );\n } else {\n memset ( Keys, 0, Param.Npart * sizeof ( *Keys ) );\n }\n\n if ( Idx == NULL ) {\n Idx = malloc ( Param.Npart * sizeof ( *Idx ) );\n } else {\n memset ( Idx, 0, Param.Npart * sizeof ( *Idx ) );\n }\n\n #pragma omp parallel for\n for ( int ipart = 0; ipart < Param.Npart; ipart++ ) {\n\n double px = P[ipart].Pos[0] / Problem.Boxsize[0];\n double py = P[ipart].Pos[1] / Problem.Boxsize[1];\n double pz = P[ipart].Pos[2] / Problem.Boxsize[2];\n\n P[ipart].Key = Keys[ipart] = Peano_Key ( px, py, pz );\n }\n\n gsl_heapsort_index ( Idx, Keys, Param.Npart, sizeof ( *Keys ), &compare_peanoKeys );\n\n reorder_particles();\n\n return ;\n}\n\nstatic void reorder_particles()\n{\n for ( int i = 0; i < Param.Npart; i++ ) {\n\n if ( Idx[i] == i ) {\n continue;\n }\n\n int dest = i;\n\n struct ParticleData Ptmp = P[i];\n struct GasParticleData Sphtmp = SphP[i];\n\n int src = Idx[i];\n\n for ( ;; ) {\n\n P[dest] = P[src];\n SphP[dest] = SphP[src];\n\n Idx[dest] = dest;\n\n dest = src;\n\n src = Idx[dest];\n\n if ( src == i ) {\n break;\n }\n }\n\n P[dest] = Ptmp;\n SphP[dest] = Sphtmp;\n\n Idx[dest] = dest;\n\n } // for i\n\n return ;\n}\n\npeanoKey Peano_Key ( const double x, const double y, const double z )\n{\n Assert ( x >= 0 && x <= 1, \"X coordinate of out range [0,1] have %g\", x );\n Assert ( y >= 0 && y <= 1, \"Y coordinate of out range [0,1] have %g\", y );\n Assert ( z >= 0 && z <= 1, \"Z coordinate of out range [0,1] have %g\", z );\n\n const uint64_t m = 1UL << 63; // = 2^63;\n\n uint64_t X[3] = { y * m, z * m, x * m };\n\n /* Inverse undo */\n\n for ( uint64_t q = m; q > 1; q >>= 1 ) {\n\n uint64_t P = q - 1;\n\n if ( X[0] & q ) {\n X[0] ^= P; // invert\n }\n\n for ( int i = 1; i < 3; i++ ) {\n\n if ( X[i] & q ) {\n\n X[0] ^= P; // invert\n\n } else {\n\n uint64_t t = ( X[0] ^ X[i] ) & P;\n\n X[0] ^= t;\n X[i] ^= t;\n\n } // exchange\n }\n }\n\n /* Gray encode (inverse of decode) */\n\n for ( int i = 1; i < 3; i++ ) {\n X[i] ^= X[i - 1];\n }\n\n uint64_t t = X[2];\n\n for ( int i = 1; i < 64; i <<= 1 ) {\n X[2] ^= X[2] >> i;\n }\n\n t ^= X[2];\n\n for ( int i = 1; i >= 0; i-- ) {\n X[i] ^= t;\n }\n\n /* branch free bit interleave of transpose array X into key */\n\n peanoKey key = 0;\n\n X[1] >>= 1;\n X[2] >>= 2; // lowest bits not important\n\n for ( int i = 0; i < N_PEANO_TRIPLETS + 1; i++ ) {\n\n uint64_t col = ( ( X[0] & 0x8000000000000000 )\n | ( X[1] & 0x4000000000000000 )\n | ( X[2] & 0x2000000000000000 ) ) >> 61;\n\n key <<= 3;\n\n X[0] <<= 1;\n X[1] <<= 1;\n X[2] <<= 1;\n\n key |= col;\n }\n\n key <<= 2;\n\n return key;\n}\n\n/* This constructs the peano key with reversed triplet order. The order in the\n * triplets however is the same ! Also level zero is carried explicitely\n * to ease tree construction. */\n\npeanoKey Reversed_Peano_Key ( const double x, const double y, const double z )\n{\n Assert ( x >= 0 && x <= 1, \"X coordinate of out range [0,1] have %g\", x );\n Assert ( y >= 0 && y <= 1, \"Y coordinate of out range [0,1] have %g\", y );\n Assert ( z >= 0 && z <= 1, \"Z coordinate of out range [0,1] have %g\", z );\n\n const uint64_t m = 1UL << 63; // = 2^63;\n\n uint64_t X[3] = { y * m, z * m, x * m };\n\n /* Inverse undo */\n\n for ( uint64_t q = m; q > 1; q >>= 1 ) {\n\n uint64_t P = q - 1;\n\n if ( X[0] & q ) {\n X[0] ^= P; // invert\n }\n\n for ( int i = 1; i < 3; i++ ) {\n\n if ( X[i] & q ) {\n\n X[0] ^= P; // invert\n\n } else {\n\n uint64_t t = ( X[0] ^ X[i] ) & P;\n\n X[0] ^= t;\n X[i] ^= t;\n\n } // exchange\n }\n }\n\n /* Gray encode (inverse of decode) */\n\n for ( int i = 1; i < 3; i++ ) {\n X[i] ^= X[i - 1];\n }\n\n uint64_t t = X[2];\n\n for ( int i = 1; i < 64; i <<= 1 ) {\n X[2] ^= X[2] >> i;\n }\n\n t ^= X[2];\n\n for ( int i = 1; i >= 0; i-- ) {\n X[i] ^= t;\n }\n\n /* branch free reversed (!) bit interleave of transpose array X into key */\n\n peanoKey key = 0;\n\n X[0] >>= 18;\n X[1] >>= 19;\n X[2] >>= 20; // lowest bits not important\n\n for ( int i = 0; i < N_PEANO_TRIPLETS + 1; i++ ) {\n\n uint64_t col = ( ( X[0] & 0x4 ) | ( X[1] & 0x2 ) | ( X[2] & 0x1 ) );\n\n key <<= 3;\n\n key |= col;\n\n X[0] >>= 1;\n X[1] >>= 1;\n X[2] >>= 1;\n }\n\n key <<= 3; // include level 0\n\n return key;\n}\n\n\nvoid test_peanokey()\n{\n const double box[3] = { 1.0, 1, 1};\n double a[3] = { 0 };\n int order = 1;\n float delta = 1 / pow ( 2.0, order );\n int n = roundf ( 1 / delta );\n\n for ( int i = 0; i < n; i++ ) {\n for ( int j = 0; j < n; j++ ) {\n for ( int k = 0; k < n; k++ ) {\n\n a[0] = ( i + 0.5 ) * delta / box[0];\n a[1] = ( j + 0.5 ) * delta / box[1];\n a[2] = ( k + 0.5 ) * delta / box[2];\n\n peanoKey stdkey = Peano_Key ( a[0], a[1], a[2] );\n\n printf ( \"%g %g %g %llu \\n\", a[0], a[1], a[2],\n ( long long ) stdkey );\n\n Print_Int_Bits128 ( stdkey );\n\n printf ( \"\\n\" );\n }\n }\n }\n\n return ;\n}\n", "meta": {"hexsha": "2463081d7f6bac1f7545614ef9f9981564a67106", "size": 6830, "ext": "c", "lang": "C", "max_stars_repo_path": "src/peano.c", "max_stars_repo_name": "elehcim/WVTICs", "max_stars_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-07-29T04:44:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T08:18:47.000Z", "max_issues_repo_path": "src/peano.c", "max_issues_repo_name": "elehcim/WVTICs", "max_issues_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-23T12:22:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-23T12:22:14.000Z", "max_forks_repo_path": "src/peano.c", "max_forks_repo_name": "elehcim/WVTICs", "max_forks_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-29T09:38:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:31:56.000Z", "avg_line_length": 21.2111801242, "max_line_length": 88, "alphanum_fraction": 0.4178623719, "num_tokens": 2319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4026349255062284}} {"text": " // MIT License\n\n // Copyright (c) [2017] [Vinay Yuvashankar]\n\n // Permission is hereby granted, free of charge, to any person obtaining a copy\n // of this software and associated documentation files (the \"Software\"), to deal\n // in the Software without restriction, including without limitation the rights\n // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n // copies of the Software, and to permit persons to whom the Software is\n // furnished to do so, subject to the following conditions:\n\n // The above copyright notice and this permission notice shall be included in all\n // copies or substantial portions of the Software.\n\n // THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n // SOFTWARE.\n\n\n/** \\file ERSP.cc\n\t\n\t\\brief This file contains all of the function required to generate the Event Related Spectral Pertubation of EEG signals.\n*/\n#include \"wavelet.h\"\n#include \n\n#define NORMALIZATION_FACTOR 0.375402913609157562\n\nint ERSP (double * raw_data, double* scales, const int sampling_frequency, const int n, \n\tconst int J, int const trials, const int padding_type, \n\tdouble * output)\n{\n\tint i, j, x;\n\n\t//Calculate the necessary constants for the Continuous Wavelet Transform.\n const int PADDED_SIZE = CalculatePaddingSize(n, padding_type);\n const int m = PRE_EVENT_TIME * sampling_frequency;\n const double dw = (2 * M_PI * sampling_frequency)/(PADDED_SIZE); //NOT IN RAD/SEC in Hz\n\n fftw_init_threads();\n #pragma omp parallel private(i, j, x) shared(raw_data, output, scales) default(none)\n {\n \t//Array Inits\n \tdouble * pre_stimulus, *wavelet_out, *baseline_out;\n \tfftw_complex *data_in, *fft_data, *filter_convolution, *fftw_result;\n \tfftw_plan plan_forward, plan_backward;\n\n\t //Memory Allocations\n\t wavelet_out = (double*) malloc( n * J * sizeof(double) );\n\t baseline_out = (double*) malloc( n * J * sizeof(double) );\n\t pre_stimulus = (double*) malloc( m * sizeof(double) );\n\n\t //FFTW Memory Allocations\n\t data_in = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE );\n\t\tfft_data = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE );\n\t\tfilter_convolution = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE );\n\t\tfftw_result = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE );\n\n\t\t#pragma omp critical (make_plan)\n\t\t{\n\t\t\tfftw_plan_with_nthreads(1);\n\t\t\tif (fftw_import_wisdom_from_filename(\"FFTW_Plan.wise\") == 0)\n\t\t\t{\n\t\t\t\tprintf(\"No FFTW Plan, using an unoptimized method\\n\");\n\t\t\t\tplan_forward = fftw_plan_dft_1d(PADDED_SIZE, data_in, fft_data, FFTW_FORWARD, FFTW_ESTIMATE);\n\t\t\t\tplan_backward = fftw_plan_dft_1d(PADDED_SIZE, filter_convolution, fftw_result, FFTW_BACKWARD, FFTW_ESTIMATE);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tplan_forward = fftw_plan_dft_1d(PADDED_SIZE, data_in, fft_data, FFTW_FORWARD, FFTW_EXHAUSTIVE);\n\t\t\t\tplan_backward = fftw_plan_dft_1d(PADDED_SIZE, filter_convolution, fftw_result, FFTW_BACKWARD, FFTW_EXHAUSTIVE);\t\n\t\t\t}\n\t\t}\n\n\t\t/*Begin ERSP*/\n\t\t#pragma omp for\n\t\tfor ( x = 0; x < trials; ++x)\n\t\t{\n\t\t\tmemset(data_in, 0.0, sizeof( fftw_complex ) * PADDED_SIZE);\n\t\t\tmemset(fft_data, 0.0, sizeof( fftw_complex ) * PADDED_SIZE);\n\t\t\tmemset(filter_convolution, 0.0, sizeof( fftw_complex ) * PADDED_SIZE);\n\t\t\tmemset(fftw_result, 0.0, sizeof( fftw_complex ) * PADDED_SIZE);\n\n\t\t\t/*Begin Wavelet Analysis*/\n\t\t\tPopulateDataArray(raw_data, n, x, \n\t\t\t\t\t\t\t PADDED_SIZE, padding_type, data_in);\n\t\t\tfftw_execute(plan_forward);\n\n\t\t\tfor (i = 0; i < J; ++i)\n\t\t\t{\n\t\t\t\tFrequencyMultiply(fft_data, PADDED_SIZE, scales[i], dw, \n\t\t\t\t\t\t\t\t filter_convolution);\n\n\t\t\t\t//Take the inverse FFT and store it in fftw_result\n\t\t\t\tfftw_execute(plan_backward);\n\n\t\t\t\t//Calculate the power and store it in result this may need to be changed to accomodate for phase\n\t\t\t\tfor (j = 0; j < n; ++j)\n\t\t\t\t{\n\t\t\t\t\twavelet_out[i * n + j] = MAGNITUDE(fftw_result[j][0], fftw_result[j][1]) / (NORMALIZATION_FACTOR * sqrt(scales[i]) );\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*End Wavelet Analysis*/\n\n\t\t\t//Remove the baseline\n\t\t\tRemoveBaseline(pre_stimulus, wavelet_out,\n\t\t\t\t\t\t n, J, m,\n\t\t\t\t\t\t baseline_out);\n\n\t\t\tfor ( i = 0; i < n * J; ++i)\n\t\t\t{\n\t\t\t\toutput[i] += fabs(baseline_out[i]);\n\t\t\t}\n\t\t}\n\n\t\t#pragma omp for simd\n\t\tfor ( i = 0; i < n * J; ++i)\n\t\t{\n\t\t\toutput[i] /= trials;\n\t\t}\n\t\t/*End ERSP*/\n\n\t\t//Sanitation Engineering\n\t\tfftw_destroy_plan(plan_forward); fftw_destroy_plan(plan_backward);\n\t\tfftw_free(data_in); fftw_free(fft_data); fftw_free(filter_convolution); fftw_free(fftw_result);\n\t\tfree(pre_stimulus); free(baseline_out); free(wavelet_out);\n\n }/*End of OpenMP*/\n\treturn(0);\n}\n\nint RemoveBaseline(double* pre_stimulus, double* pre_baseline_array, \n\tconst int n, const int J, const int m,\n\tdouble* output)\n{\n\tdouble value;\n\tdouble mean, sDeviation;\n\tconst int stride = 1;\n\tint i, j;\n\n\tfor ( i = 0; i < J; ++i)\n\t{\n\t\t//Copy the pre trial results from each frequency block into pre_stimulus.\n\t\tfor ( j = 0; j < m; ++j)\t\t\n\t\t{\t\t\n\t\t\tpre_stimulus[j] = pre_baseline_array[i * n + j]; \t\t\n\t\t}\n\n\t\t//Calculate mean and standard deviation\n\t\tmean = gsl_stats_mean(pre_stimulus, stride, m);\n \tsDeviation = gsl_stats_sd_m(pre_stimulus, stride, m, mean);\n\n \t//Remove the Baseline\n\t for ( j = 0; j < n; ++j)\n\t {\n\t \tvalue = pre_baseline_array[i * n + j] * pre_baseline_array[i * n + j];\n\t output[i * n + j] = (fabs(value) - mean) / sDeviation;\n\t // output[i * n + j] = ( pre_baseline_array[i * n + j] - mean ) / sDeviation;\n\t }\n\t}\n\n\treturn(0);\n}\n\nint Generate_FFTW_Wisdom(int padded_size)\n{\n\tint success_flag = 1;\n\t\n\t//Array Inits\n\tfftw_complex *data_in, *fft_data, *filter_convolution, *fftw_result;\n\tfftw_plan plan_forward, plan_backward;\n\t\n\tfftw_init_threads();\n\t\n\t//FFTW Memory Allocations\n data_in = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * padded_size );\n\tfft_data = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * padded_size );\n\tfilter_convolution = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * padded_size );\n\tfftw_result = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * padded_size );\n\n\t//FFTW Planning\n\tfftw_plan_with_nthreads(1);\n\tprintf(\"Generating an Exhaustive FFTW Plan\\n\");\n\tplan_forward = fftw_plan_dft_1d(padded_size, data_in, fft_data, FFTW_FORWARD, FFTW_EXHAUSTIVE);\n\tplan_backward = fftw_plan_dft_1d(padded_size, filter_convolution, fftw_result, FFTW_BACKWARD, FFTW_EXHAUSTIVE);\n\t\n\tprintf(\"Writing FFTW plan to FFTW_Plan.wise\\n\");\n\tif (fftw_export_wisdom_to_filename(\"FFTW_Plan.wise\") != 0)\n\t{\n\t\tsuccess_flag = 0;\n\t}\n\n\tfftw_destroy_plan(plan_forward); fftw_destroy_plan(plan_backward);\n\tfftw_free(data_in); fftw_free(fft_data); fftw_free(filter_convolution); fftw_free(fftw_result);\n\n\treturn(success_flag);\n}\n\n\nint FrequencyMultiply(fftw_complex* fft_data, \n\tconst int data_size, const double scale, const double dw,\n\tfftw_complex* filter_convolution)\n{\n\tint j; \n\tdouble value; \n\t//Compute the Fourier Morlet at 0 and N/2\n\tdouble norm = sqrt(scale);\n\tvalue = CompleteFourierMorlet(0.0, scale, norm);\n\n\tfilter_convolution[0][0] = (fft_data[0][0]/data_size) * value;\n\tfilter_convolution[0][1] = (fft_data[0][1]/data_size) * value;\n\t\n\tfilter_convolution[data_size/2][0] = 0.0;\n\tfilter_convolution[data_size/2][1] = 0.0;\n\n\t//Compute the Fourier Morlet Convolution in between\n\tfor (j = 1; j < data_size/2 - 1; ++j)\n\t{\n\t\tvalue = CompleteFourierMorlet( j * dw , scale, norm);\n\t\tfilter_convolution[j][0] = (fft_data[j][0]/data_size) * value;\n\t\tfilter_convolution[j][1] = (fft_data[j][1]/data_size) * value;\n\n\t\tfilter_convolution[data_size- j][0] = 0.0;\n\t\tfilter_convolution[data_size- j][1] = 0.0;\n\t}\n\n\treturn(0);\n}\n\n\nint PopulateDataArray(double* input_data, const int data_size, const int trial_number,\n\tconst int padded_size, const int padding_type,\n\tfftw_complex* output_data)\n{\n\tconst double ramp = 2.0/data_size; // = 1.0/ n / 2\n\tdouble gain; \n\tint i;\n\n\tint output_counter = 0;\n\tint input_counter = 0;\n\n\tswitch(padding_type)\n\t{\n\t\tcase 0: //No Padding what so ever\n\t\t\t//populate the FFTW data vector. \n\t\t\tfor (i = 0; i < data_size; ++i)\n\t\t {\n\t\t \toutput_data[i][0] = input_data[trial_number * data_size + i];\n\t\t \toutput_data[i][1] = 0.0;\n\t\t }\n\t\t break;\n\t\t\n\t\tcase 1: //Zero - Padding\n\t\t\t//populate the FFTW data vector. \n\t\t\tfor (i = 0; i < data_size; ++i)\n\t\t {\n\t\t \toutput_data[i][0] = input_data[trial_number * data_size + i];\n\t\t \toutput_data[i][1] = 0.0;\n\t\t }\n\n\t\t //Horse the rest of the data vector to zero just in case\n\t\t for (i = data_size; i < padded_size; ++i)\n\t\t {\n\t\t \toutput_data[i][0] = 0.0;\n\t\t \toutput_data[i][1] = 0.0;\n\t\t }\n\t\t break;\n\t\t\n\t\tcase 2: //Duplicate array and ramp up and ramp down output\n\t\t\tfor (i = 0; i < data_size; ++i)\n\t\t {\n\t\t \toutput_data[i][0] = input_data[trial_number * data_size + i];\n\t\t \toutput_data[i][1] = 0.0;\n\t\t }\n\n\t\t for (i = 0; i < (int) (0.5* data_size); ++i)\n\t\t {\n\t\t \toutput_counter = data_size + i;\n\t\t \tinput_counter = (int) (trial_number * data_size + (0.5*data_size) + i);\n\t\t \tgain = i * ramp;\n\n\t\t \toutput_data[output_counter][0] = (1.0 - gain) * input_data[input_counter];\n\t\t \toutput_data[output_counter][1] = 0.0;\n\n\t\t \toutput_data[output_counter + (int) (0.5 * data_size)][0] = gain * input_data[trial_number * data_size + i];\n\t\t \toutput_data[output_counter + (int) (0.5 * data_size)][1] = 0.0;\n\t\t }\n\t\t\tbreak;\n\t\t\n\t\tdefault: //Return just the array no padding. \n\t\t\t//populate the FFTW data vector. \n\t\t\tfor (i = 0; i < data_size; ++i)\n\t\t {\n\t\t \toutput_data[i][0] = input_data[trial_number * data_size + i];\n\t\t \toutput_data[i][1] = 0.0;\n\t\t }\n\t\t break;\n\t}\n return(padding_type);\n}", "meta": {"hexsha": "224415a7d874ff1646ecf5785e7727f8882ebc8d", "size": 10215, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ERSP.c", "max_stars_repo_name": "yuvashankar/Research", "max_stars_repo_head_hexsha": "bc96cd74939a7022d64dbea86483fb4a579dd24d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ERSP.c", "max_issues_repo_name": "yuvashankar/Research", "max_issues_repo_head_hexsha": "bc96cd74939a7022d64dbea86483fb4a579dd24d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ERSP.c", "max_forks_repo_name": "yuvashankar/Research", "max_forks_repo_head_hexsha": "bc96cd74939a7022d64dbea86483fb4a579dd24d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6019736842, "max_line_length": 122, "alphanum_fraction": 0.6674498287, "num_tokens": 2987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584174871563662, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4025445825490355}} {"text": "#pragma once\n#include \n#include \"BooleanNodes.h\"\n#include \"BooleanDAG.h\"\n#include \"NodeVisitor.h\"\n#include \"VarStore.h\"\n#include \n#include \"FloatSupport.h\"\n#include \n\n#include \n#include \n\nusing namespace std;\n\n\n\nclass Line { // m(x - x0) + d < 0 (x0 is fixed for a particular evaluator, hence not stored in the line)\npublic:\n\tdouble d;\n\tgsl_vector* m;\n\tLine(double _d, gsl_vector* _m): d(_d), m(_m) {}\n\t~Line(void) {\n\t\tdelete m;\n\t}\n\t\n\tdouble getOffset(const gsl_vector* x0) { // m.x0 - d\n\t\tdouble r = 0.0;\n\t\tfor (int i = 0; i < x0->size; i++) {\n\t\t\tr += gsl_vector_get(x0, i) * gsl_vector_get(m, i);\n\t\t}\n\t\treturn r - d;\n\t}\n\t\n\tdouble getCoeff(int i) {\n\t\treturn gsl_vector_get(m, i);\n\t}\n\t\n\tdouble getDist() {\n\t\tdouble r = 0;\n\t\tfor (int i = 0; i < m->size; i++) {\n\t\t\tr += gsl_vector_get(m, i) * gsl_vector_get(m, i);\n\t\t}\n\t\treturn d/sqrt(r);\n\t}\n\t\n\tstring print() {\n\t\tstringstream str;\n\t\tstr << \"<\";\n\t\tfor (int i = 0; i < m->size; i++) {\n\t\t\tstr << gsl_vector_get(m, i) << \" \";\n\t\t}\n\t\tstr << d << \">\";\n\t\treturn str.str();\n\t}\n};\n\n\nclass Region { // Intersection of lines\npublic:\n\tvector lines;\n\tint size() {\n\t\treturn lines.size();\n\t}\n\tLine* get(int i) {\n\t\treturn lines[i];\n\t}\n\tvoid addLine(Line* l) {\n\t\tif (find(lines.begin(), lines.end(), l) == lines.end()) {\n\t\t\tlines.push_back(l);\n\t\t}\n\t}\n\t\n\tstatic Region* intersect(Region* r1, Region* r2) {\n\t\tRegion* r = new Region();\n\t\tfor (int i = 0; i < r1->size(); i++) {\n\t\t\tr->addLine(r1->get(i));\n\t\t}\n\t\tfor (int i = 0; i < r2->size(); i++) {\n\t\t\tr->addLine(r2->get(i));\n\t\t}\n\t\treturn r;\n\t}\n\t\n\tstatic Region* copy(Region* r1) {\n\t\tRegion* r = new Region();\n\t\tfor (int i = 0; i < r1->size(); i++) {\n\t\t\tr->addLine(r1->get(i));\n\t\t}\n\t\treturn r;\n\t}\n\t\n\tdouble getMaxDist() {\n\t\tdouble d = - numeric_limits::max();\n\t\tfor (int i = 0; i < lines.size(); i++) {\n\t\t\tif (lines[i]->getDist() > d) {\n\t\t\t\td = lines[i]->getDist();\n\t\t\t}\n\t\t}\n\t\treturn d;\n\t}\n\t\n\tgsl_vector* getMaxGrad() {\n\t\tdouble d = - numeric_limits::max();\n\t\tgsl_vector* g;\n\t\tfor (int i = 0; i < lines.size(); i++) {\n\t\t\tif (lines[i]->d > d) {\n\t\t\t\td = lines[i]->d;\n\t\t\t\tg = lines[i]->m;\n\t\t\t}\n\t\t}\n\t\treturn g;\n\n\t}\n\t\n\t~Region(void) {\n\t\tfor (int i = 0; i < lines.size(); i++) {\n\t\t\tdelete lines[i];\n\t\t}\n\t}\n\t\n\tstring print() {\n\t\tstringstream str;\n\t\tstr << \"{\";\n\t\tfor (int i = 0; i < lines.size(); i++) {\n\t\t\tstr << lines[i]->print() << \" \";\n\t\t}\n\t\tstr << \"}\";\n\t\treturn str.str();\n\t}\n\t\n};\n\nclass Value {\npublic:\n\tdouble val;\n\tgsl_vector* grad;\n\tValue(double v, gsl_vector* g): val(v), grad(g) {}\n\t~Value(void) {\n\t\tdelete grad;\n\t}\n\t\n\tdouble getOffset(const gsl_vector* x0) { // d - m.x0\n\t\tdouble r = 0.0;\n\t\tfor (int i = 0; i < x0->size; i++) {\n\t\t\tr += gsl_vector_get(x0, i) * gsl_vector_get(grad, i);\n\t\t}\n\t\treturn val - r;\n\t}\n\t\n\tdouble getCoeff(int i) {\n\t\treturn gsl_vector_get(grad, i);\n\t}\n\t\n\tstatic Value* add(Value* v1, Value* v2);\n\tstatic Value* mult(Value* v1, Value* v2);\n\tstatic Value* div(Value* v1, Value* v2);\n\tstatic Value* neg(Value* v1);\n\tstatic Value* copy(Value* v1);\n\tstatic Value* arctan(Value* v1);\n\tstatic Value* tan(Value* v1);\n\tstatic Value* cos(Value* v1);\n\tstatic Value* sin(Value* v1);\n\tstatic Value* sqrt(Value* v1);\n\tstatic Value* square(Value* v1);\n\t\n\tstring print() {\n\t\tstringstream str;\n\t\tstr << \"<\";\n\t\tfor (int i = 0; i < grad->size; i++) {\n\t\t\tstr << gsl_vector_get(grad, i) << \" \";\n\t\t}\n\t\tstr << val << \">\";\n\t\treturn str.str();\n\t}\n};\n\nclass RegionValuePair {\npublic:\n\tRegion* r;\n\tValue* v;\n\tRegionValuePair(Region* _r, Value* _v): r(_r), v(_v) {}\n\t\n\tstring print() {\n\t\tstringstream str;\n\t\tstr << r->print() << \" -> \" << v->print();\n\t\treturn str.str();\n\t}\n};\n\ntypedef vector ValuesList;\n\n\nclass LP {\n\tglp_prob* lp;\n\tint ia[1+1000], ja[1+1000];\n\tdouble ar[1+1000];\n\tdouble LOWBND = -32.0; // TODO: don;t hardcode\n\tdouble HIGHBND = 32.0;\n\tdouble PRECISION = 1e-5;\n\t\npublic:\n\tdouble optimize(RegionValuePair* rv, const gsl_vector* x0) {\n\t\tlp = glp_create_prob();\n\t\tglp_set_obj_dir(lp, GLP_MIN);\n\t\tint numrows = rv->r->size();\n\t\tif (numrows > 0) {\n\t\t\tglp_add_rows(lp, numrows);\n\t\t\tfor (int i = 0; i < numrows; i++) {\n\t\t\t\tglp_set_row_name(lp, (i+1), \"r\" + (i+1));\n\t\t\t\tdouble c = rv->r->lines[i]->getOffset(x0);\n\t\t\t\tglp_set_row_bnds(lp, (i+1), GLP_UP, 0.0, c - PRECISION);\n\t\t\t}\n\t\t}\n\t\tint numcols = x0->size;\n\t\tglp_add_cols(lp, numcols);\n\t\tfor (int i = 0; i < numcols; i++) {\n\t\t\tglp_set_col_name(lp, (i+1), \"x\" + (i+1));\n\t\t\tglp_set_col_bnds(lp, (i+1), GLP_DB, LOWBND, HIGHBND);\n\t\t\tglp_set_obj_coef(lp, (i+1), rv->v->getCoeff(i));\n\t\t}\n\t\tint counter = 1;\n\t\tfor (int i = 0; i < numrows; i++) {\n\t\t\tfor (int j = 0; j < numcols; j++) {\n\t\t\t\tia[counter] = (i+1);\n\t\t\t\tja[counter] = (j+1);\n\t\t\t\tar[counter] = rv->r->lines[i]->getCoeff(j);\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t\tAssert(counter-1 <= 1000, \"Out of bounds\");\n\t\t\n\t\tglp_load_matrix(lp, counter-1, ia, ja, ar);\n\t\tglp_simplex(lp, NULL);\n\t\tint status = glp_get_prim_stat(lp);\n\t\tcout << \"status: \" << status << endl;\n\t\tif (status == GLP_FEAS) {\n\t\t\tdouble z = glp_get_obj_val(lp);\n\t\t\tcout << \"z = \" << z;\n\t\t\tfor (int i = 0; i < numcols; i++) {\n\t\t\t\tcout << \" x\" << i << \" = \" << glp_get_col_prim(lp, (i+1));\n\t\t\t}\n\t\t\tglp_delete_prob(lp);\n\t\t\treturn z + rv->v->getOffset(x0);\n\t\t} else {\n\t\t\treturn 1000;\n\t\t}\n\t\t\n\t}\n\t\n\tbool check(Region* r, const gsl_vector* x0) {\n\t\tint numrows = r->size();\n\t\tif (numrows == 0) return true;\n\t\t\n\t\tlp = glp_create_prob();\n\t\tglp_set_obj_dir(lp, GLP_MIN);\n\t\tglp_add_rows(lp, numrows);\n\t\tfor (int i = 0; i < numrows; i++) {\n\t\t\tstringstream str;\n\t\t\tstr << \"r\" << (i+1);\n\t\t\tglp_set_row_name(lp, (i+1), str.str().c_str());\n\t\t\tdouble c = r->lines[i]->getOffset(x0);\n\t\t\tglp_set_row_bnds(lp, (i+1), GLP_UP, 0.0, c-PRECISION);\n\t\t}\n\t\tint numcols = x0->size;\n\t\tglp_add_cols(lp, numcols);\n\t\tfor (int i = 0; i < numcols; i++) {\n\t\t\tstringstream str;\n\t\t\tstr << \"x\" << (i+1);\n\t\t\tglp_set_col_name(lp, (i+1), str.str().c_str());\n\t\t\tglp_set_col_bnds(lp, (i+1), GLP_DB, LOWBND, HIGHBND);\n\t\t\tglp_set_obj_coef(lp, (i+1), 0.0);\n\t\t}\n\t\tint counter = 1;\n\t\tfor (int i = 0; i < numrows; i++) {\n\t\t\tfor (int j = 0; j < numcols; j++) {\n\t\t\t\tia[counter] = (i+1);\n\t\t\t\tja[counter] = (j+1);\n\t\t\t\tar[counter] = r->lines[i]->getCoeff(j);\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t\t\n\t\tglp_load_matrix(lp, counter-1, ia, ja, ar);\n\t\tglp_smcp param;\n\t\tglp_init_smcp(¶m);\n\t\tparam.msg_lev = GLP_MSG_ERR;\n\t\tglp_simplex(lp, ¶m);\n\t\tint status = glp_get_prim_stat(lp);\n\t\tglp_delete_prob(lp);\n\t\tif (status == GLP_FEAS) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n};\n\nclass GlobalEvaluator: NodeVisitor\n{\n\tFloatManager& floats;\n\tBooleanDAG& bdag;\n map floatCtrls; // Maps float ctrl names to indices with grad vectors\n int nctrls; // number of float ctrls\n\tgsl_vector* ctrls; // Ctrl values\n\tvector values; // Keeps track of values for each node for different regions\n\tmap inputValues; // Maps node id to values set by the SAT solver\n\tdouble error = 0.0;\n\tgsl_vector* errorGrad;\n\t\n\tint DEFAULT_INP = -1;\n\tstatic gsl_vector* tmp;\n\tLP* lp;\n\t\n\tint MAX_REGIONS = 16;\n\tint ctr = 0; \npublic:\n GlobalEvaluator(BooleanDAG& bdag_p, FloatManager& _floats, const map& floatCtrls_p);\n ~GlobalEvaluator(void);\n \n virtual void visit( SRC_node& node );\n virtual void visit( DST_node& node );\n virtual void visit( CTRL_node& node );\n virtual void visit( PLUS_node& node );\n virtual void visit( TIMES_node& node );\n virtual void visit( ARRACC_node& node );\n virtual void visit( DIV_node& node );\n virtual void visit( MOD_node& node );\n virtual void visit( NEG_node& node );\n virtual void visit( CONST_node& node );\n virtual void visit( LT_node& node );\n virtual void visit( EQ_node& node );\n\tvirtual void visit( AND_node& node );\n\tvirtual void visit( OR_node& node );\n\tvirtual void visit( NOT_node& node );\n virtual void visit( ARRASS_node& node );\n virtual void visit( UFUN_node& node );\n virtual void visit( TUPLE_R_node& node );\n\tvirtual void visit( ASSERT_node& node );\n \n double run(const gsl_vector* ctrls_p, map& inputValues_p, gsl_vector* errorGrad_p);\n\tvoid truncate(ValuesList& vl, const gsl_vector* x0, int numRegions);\n\tvoid truncate(vector& vl, const gsl_vector* x0, int numRegions);\n\tvoid truncateUnfeasibleRegions(ValuesList& vl, const gsl_vector* x0);\n\tvoid truncateUnfeasibleRegions(vector& vl, const gsl_vector* x0);\n\tvoid truncateFarRegions(ValuesList& vl, const gsl_vector* x0, int numRegions);\n\tvoid truncateFarRegions(vector& vl, const gsl_vector* x0, int numRegions);\n\t\n\tvoid setvalues(bool_node& bn, ValuesList& v) {\n\t\tvalues[bn.id] = v;\n\t}\n\t\n\tValuesList& getvalues(bool_node& bn) {\n\t\treturn values[bn.id];\n\t}\n\t\n\tValuesList& getvalues(bool_node* bn) {\n\t\treturn getvalues(*bn);\n\t}\n\t\n\tvoid print() {\n for (int i = 0; i < bdag.size(); i++) {\n cout << bdag[i]->lprint() << endl;\n\t\t}\n }\n\t\n\tbool isFloat(bool_node& bn) {\n\t\treturn (bn.getOtype() == OutType::FLOAT);\n\t}\n\t\n\tbool isFloat(bool_node* bn) {\n\t\treturn (bn->getOtype() == OutType::FLOAT);\n\t}\n\t\n\tint getInputValue(bool_node& bn) {\n\t\tif (inputValues.find(bn.id) != inputValues.end()) {\n\t\t\tint val = inputValues[bn.id];\n\t\t\tAssert(val == 0 || val == 1, \"NYI: Integer values\");\n\t\t\treturn val;\n\t\t} else {\n\t\t\treturn DEFAULT_INP;\n\t\t}\n\t}\n\t\n\tint getInputValue(bool_node* bn) {\n\t\treturn getInputValue(*bn);\n\t}\n\t\n\tstatic gsl_vector* default_grad(int nctrls) {\n\t\tgsl_vector* g = gsl_vector_alloc(nctrls);\n\t\tfor (int i = 0; i < nctrls; i++) {\n\t\t\tgsl_vector_set(g, i, 0);\n\t\t}\n\t\treturn g;\n\t}\n\t\n\tstatic gsl_vector* add_grad(gsl_vector* g1, gsl_vector* g2);\n\tstatic gsl_vector* mult_grad(double v1, double v2, gsl_vector* g1, gsl_vector* g2);\n\tstatic gsl_vector* div_grad(double v1, double v2, gsl_vector* g1, gsl_vector* g2);\n\tstatic gsl_vector* neg_grad(gsl_vector* g1);\n\tstatic gsl_vector* copy_grad(gsl_vector* g1);\n\tstatic gsl_vector* sub_grad(gsl_vector* g1, gsl_vector* g2);\n\tstatic gsl_vector* arctan_grad(double v1, gsl_vector* g1);\n\tstatic gsl_vector* tan_grad(double v1, gsl_vector* g1);\n\tstatic gsl_vector* cos_grad(double v1, gsl_vector* g1);\n\tstatic gsl_vector* sin_grad(double v1, gsl_vector* g1);\n\tstatic gsl_vector* sqrt_grad(double v1, gsl_vector* g1);\n\tstatic gsl_vector* square_grad(double v1, gsl_vector* g1);\n\t\n};\n\n", "meta": {"hexsha": "ef9ca57184aa6eadc3ae0e0b984d96a10c7931d5", "size": 10180, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/GlobalEvaluator.h", "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": ["X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/GlobalEvaluator.h", "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_licenses": ["X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/GlobalEvaluator.h", "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": ["X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6489104116, "max_line_length": 104, "alphanum_fraction": 0.6196463654, "num_tokens": 3392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4019127070692996}} {"text": "/*\n** Task-related edge density, main algorithm\n**\n** Ref: Lohmann et al (2016) PLoS One, 11(6):e0158185\n** \n** G.Lohmann, MPI-KYB, Jan 2015\n*/\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"viaio/Vlib.h\"\n#include \"viaio/VImage.h\"\n#include \"viaio/mu.h\"\n#include \"viaio/option.h\"\n\n\n#ifdef _OPENMP\n#include \n#endif /*_OPENMP*/\n\n#define SQR(x) ((x) * (x))\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\nextern VImage *VImagePointer(VAttrList list,int *nt);\nextern void VReadImagePointer(VAttrList list,VImage *src);\nextern VImage VoxelMap(VImage mask,size_t *nvoxels);\nextern void VDataMatrix(VImage *src,int first,int len,VImage map,gsl_matrix_float *X);\nextern void VCheckMatrix(gsl_matrix_float *X);\nextern long VMaskCoverage(VAttrList list,VImage mask);\nextern float ZMatrix(gsl_histogram *histogram,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2,\n\t\t VImage roi,VImage map,VImage,int,float elength,float quantile,int,int);\nextern void GetSNR(gsl_matrix_float **X1,gsl_matrix_float **X2,int *,int n,gsl_matrix_float *SNR,int);\nextern void GetMedian(gsl_matrix_float **X1,gsl_matrix_float **X2,int *,int n,gsl_matrix_float *SNR,int);\nextern void VPrintHistogram(gsl_histogram *histogram,int numperm,VString filename);\nextern void HistoUpdate(float *A,size_t nvox,gsl_histogram *hist);\n\nextern size_t EdgeDensity(float *C,int *I,int *J,size_t nedges,\n\t\t\t gsl_histogram *histogram,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2,\n\t\t\t VImage roi,VImage map,VImage,int,float,float,int,int,int,float,int);\n\nextern size_t EstimateEdges(float *E,int *I,int *J,size_t fulldim,\n\t\t\t gsl_histogram *TedHist,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2,\n\t\t\t VImage roi,VImage map,VImage mapimage,int adjdef,float elength,float zthreshold,float,int);\n\n\n/* generate permutation table */\nint genperm(gsl_rng *rx,int *table,int n,int numperm)\n{\n int s=0;\n int ks = 0;\n int kc=3;\n if (numperm < 10) {\n if (n%2==0) kc = n/2;\n else kc = n/2-1;\n }\n int iter=0;\n while ((ks < kc || ks > n-kc)) {\n if (iter > 100) VError(\" not possible to generate random permutations, perhaps not enough input data ?\");\n ks=0;\n for (s=0; s 100) fprintf(stderr,\" incomplete mask_coverage %s: %ld\\n\",in_filenames[i],count);\n VReleaseStorage(list);\n list = NULL;\n }\n return geolist;\n}\n\ngsl_matrix_float **VReadImageData(VStringConst *in_filenames,VImage *src,VImage map,size_t n,size_t nvox,size_t first,size_t len)\n{\n size_t i;\n VAttrList list=NULL;\n FILE *fp=NULL;\n\n /* allocate data struct */\n gsl_matrix_float **X = VCalloc(n,sizeof(gsl_matrix_float));\n for (i=0; i 1) {\n VReportBadArgs (argc, argv);\n exit (EXIT_FAILURE);\n }\n\n\n /* whether to produce output file, or only compute histogram */\n VBoolean histonly = FALSE;\n if (strlen(out_filename) < 2) histonly = TRUE;\n\n\n\n /* omp-stuff */\n#ifdef _OPENMP\n int num_procs=omp_get_num_procs();\n int jprocs = num_procs;\n if (nproc > 0 && nproc < num_procs) jprocs = nproc;\n fprintf(stderr,\" using %d cores of %d\\n\",(int)jprocs,(int)num_procs);\n omp_set_num_threads(jprocs);\n#endif /* _OPENMP */\n\n\n\n /* input filenames */\n size_t n1 = (size_t)in_files1.number;\n size_t n2 = (size_t)in_files2.number;\n if (n1 != n2) VError(\" n1 != n2, %d %d\",n1,n2);\n\n VStringConst *in_filenames1 = (VStringConst *) VCalloc(n1,sizeof(VStringConst));\n for (i=0; i 1) {\n fp = VOpenInputFile (roi_filename, TRUE);\n list2 = VReadFile (fp, NULL);\n if (! list2) VError(\"Error reading roi file\");\n fclose(fp);\n\n for (VFirstAttr (list2, & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n if (VGetAttrRepn (& posn) != VImageRepn) continue;\n VGetAttrValue (& posn, NULL,VImageRepn, & roi);\n if (VPixelRepn(roi) == VFloatRepn || VPixelRepn(roi) == VDoubleRepn) {\n\troi = NULL;\n\tcontinue;\n }\n }\n if (roi == NULL) VError(\" no roi found\");\n }\n\n /* Check mask coverage */\n VAttrList geo=NULL;\n geo = VCheckMaskCoverage(in_filenames1,n1,mask);\n geo = VCheckMaskCoverage(in_filenames2,n2,mask);\n if (geolist == NULL) geolist = geo;\n\n\n\n /* voxel map */\n VImage map = VoxelMap(mask,&nvox);\n\n\n /* get image dimensions */\n fp = VOpenInputFile (in_filenames1[0], TRUE);\n list = VReadFile (fp, NULL);\n if (! list) VError(\"Error reading image\");\n fclose(fp);\n\n int nt=0;\n VImage *src = VImagePointer(list,&nt);\n\n if (first >= nt || first < 0) VError(\" illegal value, first= %d, nt= %d\",first,nt);\n if (len <= 0) len = nt-first;\n if (first + len >= nt) len = nt-first;\n if (len < 2) VError(\" len= %d\",len);\n fprintf(stderr,\" image: %d x %d x %d, nt: %d, nvox: %ld\\n\",(int)nslices,(int)nrows,(int)ncols,nt,nvox);\n\n /* read image data */\n gsl_matrix_float **X1 = VReadImageData(in_filenames1,src,map,n1,nvox,first,len);\n gsl_matrix_float **X2 = VReadImageData(in_filenames2,src,map,n2,nvox,first,len);\n\n \n /* voxel addresses */\n VImage mapimage = VCreateImage(nslices,nrows,ncols,VIntegerRepn);\n VFillImage(mapimage,VAllBands,(VInteger)(-1));\n for (i=0; i 0) startperm = 1;\n\n\n for (nperm = startperm; nperm <= numperm; nperm++) {\n\n fprintf(stderr,\"\\n perm %3d: \",nperm);\n if (nperm > 0) {\n ks = genperm(rx,table,n,(int)numperm);\n }\n for (s=0; s 0.0 && nperm == numperm && histonly == FALSE) {\n size_t old_estimate = nedges_estimated;\n nedges_estimated = EstimateEdges(E,I,J,old_estimate,TedHist,SNR1,SNR2,n1,n2,roi,map,mapimage,\n\t\t\t\t (int)adjdef,elength,zthr,noise_cutoff,(int)metric);\n \n E = VCalloc(nedges_estimated,sizeof(float)); /* matrix of edge densities */\n I = VCalloc(nedges_estimated,sizeof(int)); /* row indices in matrix E */\n J = VCalloc(nedges_estimated,sizeof(int)); /* col indices in matrix E */\n }\n\n\n /* edge densities */\n fprintf(stderr,\" Computing edge densities...\\n\");\n nedges = EdgeDensity(E,I,J,nedges_estimated,TedHist,SNR1,SNR2,n1,n2,roi,map,mapimage,(int)adjdef,\n\t\t\t elength,zthr,nperm,numperm,(int)1,noise_cutoff,(int)metric);\n }\n\n \n /* free storage */\n for (i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"fileio.h\"\n#include \"ipf_balance.h\"\n#include \"likelihood.h\"\n#include \"master_tasks.h\"\n#include \"mutation.h\"\n#include \"randomisation.h\"\n#include \"resampling.h\"\n#include \"typedefs.h\"\n\nstatic const int ALG = 5;\nstatic const int MASTER = 0;\n\nint \nmain (\n int argc, \n char *argv[] ) \n{\n\n struct Process process;\n struct Estimates estimates;\n long * inds;\n long * BM;\n int do_resampling;\n double * w;\n double * x;\n double * x_resamp;\n double * proc_w;\n double * output;\n double my_normal_weight;\n double rsamp_time = 0;\n double rsamp_start = 0;\n double comm_time = 0;\n double comm_start;\n double comm_time2 = 0;\n double total_w = 1.0;\n double weight_time = 0.0;\n double mutation_time = 0.0;\n double init_time = 0.0;\n long n_xfer;\n unsigned int *cnts;\n long *cnts_l;\n const gsl_rng_type *T;\n double timer_start;\n\n // Parse command line arguments\n int run_idx = 0;\n if(argc > 1)\n run_idx = atoi(argv[1]);\n\n long N = 1000;\n if(argc > 2)\n N = atol(argv[2]);\n\n int state_dim;\n if ( argc > 3 ) \n state_dim = atoi( argv[ 3 ] );\n else { \n perror(\"State dimesion must be provided\");\n return -1;\n }\n\n double epc_threshold;\n if (argc > 4 ) \n epc_threshold = atof( argv[ 4 ] );\n else {\n perror(\"Reampling threshold must be provided\");\n return -1;\n }\n\n // Initialize the MPI environment\n MPI_Init(NULL, NULL);\n \n gsl_rng_env_setup();\n T = gsl_rng_default;\n gsl_rng *rgen;\n rgen = gsl_rng_alloc( T ); \n\n // Get the number of processes\n int world_size;\n MPI_Comm_size(MPI_COMM_WORLD, &world_size);\n \n // Get the rank of the process\n int world_rank;\n MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);\n\n // Start the timer\n struct timespec start_time;;\n clock_gettime(CLOCK_REALTIME, &start_time);\n\n MPI_Barrier( MPI_COMM_WORLD );\n timer_start = MPI_Wtime();\n \n long data_length;\n process = readProcessFile( state_dim );\n data_length = (int)process.n;\n \n //---------------\n // Initialisation\n //---------------\n x = malloc( sizeof( double ) * N * state_dim); \n w = malloc( sizeof( double ) * N ); \n\n inds = malloc( sizeof( long ) * N );\n x_resamp = malloc( sizeof( double ) * N * state_dim);\n \n proc_w = malloc( sizeof( double ) * world_size );\n cnts = malloc( sizeof( unsigned int ) * world_size );\n cnts_l = malloc( sizeof( long ) * world_size );\n\n BM = malloc( sizeof( long ) * world_size * world_size );\n initialise_balancing( world_size );\n\n // Initial distribution setup \n setupInitialSeed( world_rank, rgen );\n\n // Create initial sample\n createInitialSample( x, N, rgen, state_dim );\n\n // Setup the randomisation\n set_resamplingseed( world_rank );\n\n int output_dim = 2 + state_dim + 2 * world_size + world_size * state_dim;\n if ( world_rank == MASTER )\n output = malloc( sizeof( double ) * output_dim * data_length );\n\n MPI_Barrier( MPI_COMM_WORLD );\n init_time += MPI_Wtime() - timer_start;\n\n my_normal_weight = 1.0 / world_size;\n\n // main loop\n for( long n = 0; n < data_length; n++ ) {\n\n // -----------------------------------------------------------------------------\n MPI_Barrier( MPI_COMM_WORLD );\n timer_start = MPI_Wtime();\n\n evaluateLikelihoods( x, process, state_dim, data_length, N, n, w, \n\t\t\t my_normal_weight );\n \n MPI_Barrier( MPI_COMM_WORLD );\n weight_time += MPI_Wtime() - timer_start ;\n\n // compute the relevant estimates\n estimates = estimateOutput( w, x, world_rank, N, run_idx, state_dim );\n \n // Combine the results of all filters\n combineEstimates( world_rank, state_dim, estimates, output, n,\n\t\t output_dim, world_size, &total_w, &my_normal_weight,\n\t\t &do_resampling, epc_threshold );\n // printf(\"My weight %i: %f\\n\", (int)world_rank,my_normal_weight);\n // -----------------------------\n // RESAMPLING\n // -----------------------------\n \n // Resampling within processors\n\n MPI_Barrier( MPI_COMM_WORLD );\n rsamp_start = MPI_Wtime();\n\n serial_multinomial_resample_sng_noutk( N, w, inds, N );\n \n for ( long i = 0; i < N; i++)\n for ( int d = 0; d < state_dim; d++ ) \n\tx_resamp[ state_dim * i + d ] = x[ state_dim * inds[ i ] + d ];\n\n for ( long i = 0; i < N; i++)\n for ( int d = 0; d < state_dim ; d++ ) \n\tx[ state_dim * i + d ] = x_resamp[ state_dim * i + d ];\n\n // -----------------------------------------------------------------------------\n MPI_Barrier( MPI_COMM_WORLD );\n rsamp_time += MPI_Wtime() - rsamp_start;\n comm_start = MPI_Wtime(); \n \n if ( do_resampling ) {\n \n //my_weight = estimates.w; // sum of weights for the current process\n\n // --------------------------\n // START THE FULL INTERACTION\n // --------------------------\n \n // Processes send their weights to the MASTER process\n MPI_Gather( &my_normal_weight, 1, MPI_DOUBLE, proc_w, 1, MPI_DOUBLE, MASTER, \n\t\t MPI_COMM_WORLD );\n MPI_Barrier( MPI_COMM_WORLD );\n \n // Sample how many particles need to be taken from each process\n if ( world_rank == MASTER ) {\n\t\n\tgsl_ran_multinomial( rgen, ( size_t ) world_size, \n\t\t\t ( unsigned int ) ( world_size ), proc_w, cnts );\n\t\n\tfor( int j = 0; j < world_size; j++ )\n\t cnts_l[ j ] = ( long ) cnts[ j ];\n\t\n }\n \n // Send the island resampled index array to all processes\n MPI_Bcast( cnts_l, world_size, MPI_LONG, MASTER, MPI_COMM_WORLD ); \n \n //if ( world_rank == MASTER ) \n // for ( int j = 0; j < world_size; j++ ) \n // output[ output_dim * n + count_offset + j ] = cnts_l[ j ];\n \n // -----------------------------------------------------------------------------\n MPI_Barrier( MPI_COMM_WORLD );\n comm_time2 += MPI_Wtime() - comm_start;\n comm_start = MPI_Wtime();\n \n // Calculate how the islands should be communicated\n calculate_balancing_matrix( cnts_l, world_size , BM , 1 );\n \n if ( cnts_l[ world_rank ] < 1 ) { // this process needs an island\n\t\n\t// iterate over all processes (other than the current) and see if that \n\t// process has surplus particles\n\tfor ( int i = 0; i < world_size; i++ ) {\n\t \n\t if ( i != world_rank ) {\n\t \n\t // NB! BM[ world_size * i + world_rank ] should be 0 or 1\n\t n_xfer = BM[ world_size * i + world_rank ] * N; \n\t \n\t if ( n_xfer > 0 ) {\n\t \n\t MPI_Recv( x, N * state_dim, MPI_DOUBLE, i, 2, MPI_COMM_WORLD, \n\t\t\tMPI_STATUS_IGNORE );\n\t \n\t cnts_l[ world_rank ] += n_xfer;\n\t \n\t }\n\t }\n\t}\n\t\n } else if ( cnts_l[ world_rank ] > 1 ) { // this process has excess islands\n\t\n\t// iterate over all processes (other than the current) and see if \n\t// they need particles\n\tfor (int i = 0; i < world_size; i++ ) {\n\t if( world_rank != i ) {\n\t \n\t // NB! BM[ world_size * i + world_rank ] should be 0 or 1\n\t n_xfer = BM[ world_size * world_rank + i] * N;\n\t \n\t if ( n_xfer > 0 ) {\n\t \n\t MPI_Send( x, n_xfer * state_dim, MPI_DOUBLE, i, 2, MPI_COMM_WORLD );\n\t \n\t cnts_l[ world_rank ] -= n_xfer;\n\t \n\t }\n\t }\n\t}\n\t\n }\n\n my_normal_weight = 1.0 / world_size;\n } \n //else {\n // printf(\"Skip resample!\\n\");\n // }\n\n //if ( world_rank == MASTER ) {\n // printf(\"%i: %f\\n\", (int)n,my_normal_weight);\n //}\n\n\n // ----------------------------------------------------------------------------\n MPI_Barrier( MPI_COMM_WORLD );\n comm_time += MPI_Wtime() - comm_start;\n timer_start = MPI_Wtime();\n\n mutation(N, x, state_dim, rgen );\n\n // -----------------------------------------------------------------------------\n MPI_Barrier( MPI_COMM_WORLD );\n mutation_time += MPI_Wtime() - timer_start ;\n \n } \n \n struct timespec end_time;\n clock_gettime(CLOCK_REALTIME, &end_time);\n \n createOutput( ALG, world_rank, output, data_length, world_size,\n\t\trun_idx, N, state_dim, start_time, end_time, comm_time, rsamp_time, \n\t\tcomm_time2, weight_time, mutation_time, init_time, \n\t\t(int)( atof( argv[ 4 ] ) * 100 ) );\n\n finalise_balancing();\n\n // Finalize the MPI environment.\n MPI_Finalize();\n\n return 0;\n}\n\n\n", "meta": {"hexsha": "994b25adb4e47b5d22403bbfad7eee90bc8b36cc", "size": 8273, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ipf2.c", "max_stars_repo_name": "heinekmp/AIRPF", "max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z", "max_issues_repo_path": "src/ipf2.c", "max_issues_repo_name": "heinekmp/AIRPF", "max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ipf2.c", "max_forks_repo_name": "heinekmp/AIRPF", "max_forks_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6012861736, "max_line_length": 86, "alphanum_fraction": 0.5752447722, "num_tokens": 2274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4013711534732251}} {"text": "/*GENLIB library routines */\n/* Compile progs: gcc -O3 -o prog prog.c ~/genlib.c -lm -lgsl -lgslcblas */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define pi 3.14159265358979\n#define infinity 999999\n#define true 1\n#define false 0\n#define maxranges 5 /* for numerical integration */\n#define maxsimpsonpoints 1025 /* change libhdr if these changed */\n\n#define MBIG 1000000000\n#define MSEED 161803398\n#define FAC (1.0/MBIG)\n\n\n#define ib1 1\n#define ib2 2\n#define ib5 16\n#define ib18 131072\n\n#define undefined -99999999999999.9999999\n\n\ntypedef double (*fun1)();\n\nFILE *seedfileptr, *tmoutfile, *fopen();\n\n\nint inputcounter=0;\n\n/* GSL random number definitions */\ngsl_rng * gsl_rng_r;\nunsigned long int seed;\nint random_number_generator_initialised_flag = 0;\n\nlong sseed; /* seed for the slow generator */\nint tracelevel;\n\n\nstruct acc\n{\n int n;\n double sum;\n double sumsq;\n};\n\nstruct covacc\n{\n int n;\n double sumxy, sumx, sumy, sumx2, sumy2;\n};\n\ngabort(char *s, int r)\n{\n printf(\"ERROR %s %d\\n\", s, r);\n exit(1);\n}\n\n \n/* This is the random number generator ran3 from Numerical Recipes from\nKnuth. It's the fastest of the ``non-quick-and-dirty'' generators, and\nis supposed to have decent properties */\ndouble uniform_old()\n{\n\tstatic int inext,inextp;\n\tstatic long ma[56];\n\tstatic int iff=0;\n\tlong mj,mk;\n double res;\n\tint i,ii,k;\n\t\n\tif(sseed<0||iff==0)\n\t{\n\t\tiff=1;\n\t\tmj=MSEED-(sseed<0?-sseed:sseed);\n\t\tmj%=MBIG;\n\t\tma[55]=mj;\n\t\tmk=1;\n\t\tfor(i=1;i<=54;i++)\n\t\t{\n\t\t\tii=(21*i)%55;\n\t\t\tma[ii]=mk;\n\t\t\tmk=mj-mk;\n\t\t\tif(mk<0) mk+=MBIG;\n\t\t\tmj=ma[ii];\n\t\t}\n\t\tfor(k=1;k<=4;k++)\n\t\t\tfor(i=1;i<=55;i++)\n\t\t\t{\n\t\t\t\tma[i] -=ma[1+(i+30)%55];\n\t\t\t\tif(ma[i]<0) ma[i]+=MBIG;\n\t\t\t}\n\t\tinext=0;\n\t\tinextp=31;\n\t\tsseed=1;\n\t}\n\tif(++inext==56) inext=1;\n\tif(++inextp==56) inextp=1;\n\tmj=ma[inext]-ma[inextp];\n\tif(mj<0) mj+=MBIG;\n\tma[inext]=mj;\n\tsseed=mj;\n res = mj*FAC;\n if (res > 1.0) res = 1.0;\n else if (res < 0.0) res = 0.0;\n\treturn res;\n}\n\n\n\ndouble uniform()\n{\n double res;\n if (!random_number_generator_initialised_flag)\n gabort(\"uniform() called, but !random_number_generator_initialised_flag\", 0);\n res = gsl_ran_flat(gsl_rng_r,0.0,1.0);\n return(res);\n}\n\n\nint irbit1(unsigned long *iseed)\n/* routine to return random bits */\n{\n unsigned long newbit;\n newbit = (*iseed &ib18) >> 17\n ^ (*iseed &ib5) >> 4\n ^ (*iseed &ib2) >> 1\n ^ (*iseed &ib1);\n *iseed = (*iseed<<1) | newbit;\n return (int)newbit;\n}\n\n\ninitialise_uniform_generator()\n{\n/* create a generator chosen by the environment variable GSL_RNG_TYPE */\n const gsl_rng_type * T;\n// printf(\"initialise_uniform_generator\\n\");\n gsl_rng_env_setup();\n T = gsl_rng_default;\n gsl_rng_r = gsl_rng_alloc (T);\n random_number_generator_initialised_flag = 1;\n}\n\n\ngetseed()\n{\n FILE *seedfileptr;\n static int c = 1;\n if (c==1) // first time routine called\n {\n initialise_uniform_generator();\n c = 0;\n }\n printf(\"Enter seed (-99 to read from file) \");\n manual: scanf(\"%lu\", &seed);\n if (seed == -99)\n {\n seedfileptr = fopen(\"seedfile\", \"r\");\n if (seedfileptr==0)\n {\n printf(\"No seedfile, enter seed please \");\n goto manual;\n }\n fscanf(seedfileptr, \"%lu\", &seed);\n// printf(\"Seed read %lu\\n\", seed);\n fclose(seedfileptr);\n }\n gsl_rng_set(gsl_rng_r, seed);\n}\n\ngetseedquick()\n{\n FILE *seedfileptr;\n static int c = 1;\n if (c==1) // first time routine called\n {\n initialise_uniform_generator();\n c = 0;\n }\n seedfileptr = fopen(\"seedfile\", \"r\");\n if (seedfileptr==0)\n {\n printf(\"No seedfile, enter seed please \");\n scanf(\"%lu\", &seed);\n }\n else\n {\n fscanf(seedfileptr, \"%lu\", &seed);\n fclose(seedfileptr);\n }\n// printf(\"getseedquick: Seed read %lu\\n\", seed);\n gsl_rng_set(gsl_rng_r, seed);\n}\n\n\nterminate_uniform_generator()\n{\n gsl_rng_free(gsl_rng_r);\n}\n\nwriteseed()\n{\n FILE *seedfileptr;\n double temp, x;\n x = uniform();\n temp = floor(x*100000000);\n seed = (unsigned long int)temp;\n// printf(\"Write seed %lu\\n\", seed);\n seedfileptr = fopen(\"seedfile\", \"w\");\n fprintf(seedfileptr, \"%lu\\n\", seed);\n fclose(seedfileptr);\n terminate_uniform_generator();\n}\n\n\n\n\ninitacc(a)\nstruct acc *a;\n{\n a -> n = 0;\n a -> sum = 0;\n a -> sumsq = 0;\n}\n\n\naccum(struct acc *a, double x)\n{\n a->n = a->n + 1;\n a->sum = a->sum + x;\n a->sumsq = a->sumsq + x*x;\n}\n\ndouble accmean(struct acc *a)\n{\n return(a->sum/(double)(a->n));\n}\n\ndouble variance(struct acc *a)\n{\n double num, denom;\n if (a->n == 0) return((double)-infinity);\n num = a->sumsq - (a->sum)*(a->sum)/((double)(a->n));\n denom = (double)(a->n) - (double)1;\n return(num/denom);\n}\n\n\n/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! normal\n! ------\n! Returns 2 random long reals from the standard normal distribution.\n!\n! Parameters: mu = mean\n! sdev = standard deviation\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/\n\n\n\ndouble normal(double mu, double sdev)\n{\n double u1, u2, r;\n u1= uniform();\n if (u1==0.0) u1 = 0.00001; /*prevent fatal error*/\n if (u1==1.0) u1 = .999999;\n u2= uniform();\n r = sqrt (-2.0*log(u1)) * cos(2.0*pi*u2);\n return(r*sdev + mu);\n}\n\n\n/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! quick normal\n! ------------\n! Returns two uniform long reals from the normal distribution.\n!\n! Parameters: x1, x2 -> return values\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/\nquicknormal (double *x1, double *x2)\n{\n double u1, u2, r;\n u1= uniform();\n if (u1==0.0) u1 = 0.00001; /*prevent fatal error*/\n if (u1==1.0) u1 = .999999;\n u2 = uniform();\n *x1 = sqrt (-2.0*log(u1)) * cos(2.0*pi*u2);\n *x2 = sqrt (-2.0*log(u1)) * sin(2.0*pi*u2);\n}\n\n\n\n/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! wishart\n! -------\n!\n! Returns two uniform real numbers from the wishart (bivariate) distribution.\n! These are obtained by squaring correlated uniform numbers from the bivariate\n! normal distribution.\n!\n! Parameters : z1 = return value for symmetrical distribution (i.e. metric)\n! z2 = ,, ,, ,, negative sided distribution (i.e. fitness)\n! epsilon1 = sqrt(E(z1*z1))\n! epsilon2 = sqrt(E(z2*z2))\n! rho = correlation of absolute values.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */\nwishart(double *z1, double *z2, double epsilon1, double epsilon2, double rho)\n{\n double sq;\n rho = sqrt(rho);\n sq = 1/sqrt(3.0);\n quicknormal(z1, z2);\n *z2 = *z1*rho + *z2*sqrt(1.0 - rho*rho);\n *z1 = sq*epsilon1*(*z1)*(*z1);\n *z2 = -sq*epsilon2*(*z2)*(*z2);\n if (uniform() > 0.5) *z1 = -(*z1);\n}\n\n\n/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! bivnormal\n! -------\n!\n! Returns two real numbers from the bivariate normal distribution.\n!\n! Parameters : z1 = return value for symmetrical distribution (i.e. metric)\n! z2 = ,, ,, ,, negative sided distribution (i.e. fitness)\n! epsilon1 = sqrt(E(z1*z1))\n! epsilon2 = sqrt(E(z2*z2))\n! rho = correlation of absolute values.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */\nbivnormal(double *z1, double *z2, double epsilon1, double epsilon2, double rho)\n{\n rho = sqrt(rho);\n quicknormal(z1, z2);\n *z2 = *z1*rho + *z2*sqrt(1.0 - rho*rho);\n *z1 = epsilon1*(*z1);\n *z2 = -epsilon2*(*z2);\n if (*z2 > 0.0) *z2 = -*z2;\n}\n\n\n\ncubenormal(z1, z2, epsilon1, epsilon2, rho)\ndouble *z1, *z2, epsilon1, epsilon2, rho;\n{\n double sq;\n sq = 1.0/sqrt(16.0);\n rho = sqrt(rho);\n quicknormal(z1, z2);\n *z2 = *z1*rho + *z2*sqrt(1.0 - rho*rho);\n *z1 = sq*epsilon1*(*z1)*(*z1)*(*z1);\n *z2 = -sq*epsilon2*(*z2)*(*z2)*(*z2);\n if (*z2 > 0.0) *z2 = -*z2;\n}\n\n\n\n/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! doublegamma\n! -----------\n!\n! Returns uniform long real from the double gamma distribution.\n!\n! Parameter: epsilon = sqrt(E(a*a))\n! proportion positive = proportion of distribution +ve\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/\ndouble doublegamma (epsilon, proppositive)\ndouble epsilon, proppositive;\n{\n double r, sigma;\n sigma = sqrt(epsilon*1.0/sqrt(3.0));\n r= normal(0.0, sigma);\n r= r*r;\n if (uniform() > proppositive) r= -r; /*uniformly allocate sign*/\n return(r);\n}\n\n\ndouble gamdev(int ia, double epsilon)\n/* returns random number from gamma distribution with integer parameter\ntaken from Numerical Recipes in C */\n{\n int j;\n double x;\n if ((ia<1)||(ia>=6)) gabort(\"Parameter to gamdev() invalid \", (double)ia);\n x = 1.0;\n for (j=1; j<=ia; j++)\n {\n x *= uniform();\n }\n x = -log(x);\n x = (epsilon*x)/sqrt((double)(ia*(ia+1)));\n return x;\n}\n\n\n\ninitcovacc(struct covacc *a)\n{\n a->n = 0;\n a->sumx = 0;\n a->sumy = 0;\n a->sumxy = 0;\n a->sumx2 = 0;\n a->sumy2 = 0;\n}\n\n\ncovaccum(struct covacc *a, double x, double y)\n\n{\n a->n = a->n + 1;\n a->sumx = a->sumx + x;\n a->sumy = a->sumy + y;\n a->sumxy = a->sumxy + x*y;\n a->sumx2 = a->sumx2 + x*x;\n a->sumy2 = a->sumy2 + y*y;\n}\n\n\n\ndouble covariance(struct covacc *a)\n{\n if (a->n < 2)\n {\n return(-infinity);\n }\n return((a->sumxy - (a->sumx*a->sumy/(double)a->n))/((double)a->n - 1.0));\n}\n\n\n\ndouble correlation(struct covacc *a)\n{\n double num, denom, cov, v1, v2;\n if (a->n < 2)\n {\n return(-infinity);\n }\n cov = covariance(a);\n num = a->sumx2 - (a->sumx)*(a->sumx)/((double)(a->n));\n denom = (double)(a->n) - 1.0;\n v1 = num/denom;\n num = a->sumy2 - (a->sumy)*(a->sumy)/((double)(a->n));\n denom = (double)(a->n) - 1.0;\n v2 = num/denom;\n return(cov/sqrt(v1*v2));\n}\n\n\ndouble se(a)\nstruct acc *a;\n{\n if (a->n < 1) return(-infinity);\n if (variance(a)/a->n < 0) return(-infinity);\n return(sqrt(variance(a)/a->n));\n}\n\n\nprintmse(s, r)\nchar *s;\nstruct acc *r;\n{\n\n printf(\"%s %f +/- %f\\n\", s, accmean(r), se(r));\n}\n\n\n/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! generate poisson table\n! ----------------------\n!\n! generates a table of probabilities for each whole number given a poisson\n! distribution.\n!\n! Parametes: mean = mean of poisson.\n! last number = max. elements in table\n! table -> table of probabilities.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/\n\ngeneratepoissontable (double mean, int *lastnumber, double *table, int max)\n{\n int j;\n double prev;\n prev = exp(-mean);\n if (prev == 0) gabort(\"Insufficient resolution in generate poisson table\", 0);\n table[0] = prev;\n for (j = 1; j <= max; j++)\n {\n *lastnumber = j;\n prev = prev*mean/(double)j;\n table[j] = table[j-1] + prev;\n if (1 - table[j] < 0.000001) break;\n }\n}\n\n\n\n\n/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! poisson\n! -------\n!\n! Looks up a table of probabilities of the poisson distribution already\n! set up. Returns the index of this probability. This discrete vaue\n! will come from the posson distribution.\n!\n! Parameters: last number = last entry in the table\n! table -> table of probabilities\n!\n! Returns : integer from poisson distribution.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/\n\nint poisson (int lastnumber, double *table)\n{\n int j;\n float u;\n u = uniform();\n for (j = 0; j<=lastnumber; j++)\n {\n if ((double)u < table[j]) return(j);\n }\n return(lastnumber);\n}\n\n\n/*-------------------------------------------------------------------*/\n/* binarysearchcumulative */\n/* ---------------------- */\n\n/* Assumes array contains a cumulative density function of a discrete*/\n/* distribution. Returns an */\n/* integer randomly drawn from the density function. */\n\n/* Parameters array -> cdf. */\n/* size = no. of elements in array [1..size] */\n/*-------------------------------------------------------------------*/\n\nint binarysearchcumulative(array, size)\ndouble *array;\nint size;\n{\n int cur, pre, post;\n double r;\n r = uniform();\n/* printf(\"Uniform %f\\n\", r);*/\n pre = 1;\n post = size;\n cur = (size + 1)/2;\n do\n {\n if (array[cur] < r) pre = cur; else post = cur;\n cur = (pre + post)/2;\n if ((cur==post) || (cur==pre))\n {\n if (r < array[pre])\n {\n/* printf(\"Returning pre %d\\n\", pre);*/\n return(pre);\n }\n else\n {\n/* printf(\"Returning post %d\\n\", post);*/\n return(post);\n }\n }\n } while (size > 0);\n}\n\n\n\n/*----------------------------------------------------------------------*/\n/*\t\t\t\t\t\t\t\t\t*/\n/* discrete \t\t\t\t\t\t\t\t*/\n/* --------\t\t\t\t\t\t\t\t*/\n/*\t\t\t\t\t\t\t\t\t*/\n/* Returns random integer in range 1..n with equal probability. */\n/* Parameter: n = max. integer to return.\t\t\t\t*/\n/*\t\t\t\t\t\t\t\t\t*/\n/*----------------------------------------------------------------------*/\nint discrete(int n)\n{\n int res;\n res = (int)(uniform()*(double)n) + 1;\n if (res<1) res = 1;\n else if (res>n) res = n;\n return(res);\n}\n\n\n\n \n/*----------------------------------------------------------------------*/\n/* \t\t\t\t\t\t*/\n/* samplewithoutreplacement\t\t\t\t\t\t*/\n/* ------------------------\t\t\t\t\t\t*/\n/*\t\t\t\t\t\t\t\t\t*/\n/* Returns a random integer from those present in array, which is valid */\n/* from 1 to limit. Overwrites sampled integer with array[limit], */\n/* then decrements limit.\t\t\t\t\t\t*/\n/* Parameters: limit -> no. valid integers in array */\n/* array -> array[1..limit] of integers to sample */\n/* \t\t\t\t\t\t\t\t\t*/\n/*----------------------------------------------------------------------*/\nint samplewithoutreplacement(limit, array)\nint *limit, *array;\n{\n int index, res;\n index = discrete(*limit);\n res = array[index];\n array[index] = array[*limit];\n *limit = *limit - 1;\n return(res);\n}\n \n/* trap - asks for input to stop program */\ntrap()\n{\n int i;\n printf(\"Enter any int to continue\\n\");\n scanf(\"%d\", &i);\n}\n\n\n/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! getint;\n! -------\n!\n! Displays a prompt and reads in an integer. Checks the range of the integer\n! and stops the program if it is out of range.\n!\n! Parameters: s -> string prompt\n! i -> integer variable to input.\n! min = max value\n! max = min value.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\ngetint(char *s, int *i, int min, int max)\n{\n printf(\"%s\", s);\n scanf(\"%d\", i);\n if ((min != -infinity) && (*i < min))\n {\n printf(\"Value too small. Reading %s. Terminating.\", s);\n printf(\"\\n\");\n printf(\"Min allowable: \");\n printf(\"%d\", min);\n printf(\"\\n\");\n gabort(\"\", 0);\n } \n if ((max != infinity) && (*i > max)) \n {\n printf(\"Value too large. Reading %s. Terminating.\", s);\n printf(\"\\n\");\n printf(\"Max allowable: \");\n printf(\"%d\", max);\n printf(\"\\n\");\n gabort(\"\", 0);\n }\n}\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! getint and skip;\n! ----------------\n!\n! Displays a prompt and reads in an integer, skipping\n! to the end of the line. Checks the range of the integer\n! and stops the program if it is out of range.\n!\n! Parameters: s -> string prompt\n! i -> integer variable to input.\n! min = max value\n! max = min value.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\ngetintandskip(char *s, int *i, int min, int max)\n{\n char ch;\n printf(s);\n printf(\" \");\n scanf(\"%d\", i);\n do\n {\n ch = getchar();\n }\n while (ch != '\\n');\n if ((min != -infinity) && (*i < min))\n {\n printf(\"Value too small. Reading %s. Terminating.\", s);\n printf(\"\\n\");\n printf(\"Min allowable: \");\n printf(\"%d\", min);\n printf(\"\\n\");\n gabort(\"\", 0);\n } \n if ((max != infinity) && (*i > max)) \n {\n printf(\"Value too large. Reading %s. Terminating.\", s);\n printf(\"\\n\");\n printf(\"Max allowable: \");\n printf(\"%d\", max);\n printf(\"\\n\");\n gabort(\"\", 0);\n }\n}\n\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\nprintreal(s,r, x, y)\nchar *s;\ndouble r;\nint x, y;\n{\n printf(\"%s %f\\n\", s, r);\n\n}\n\n\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! printint;\n! ---------\n!\n! Prints out the integer with leading spaces x after the string s.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\nprintint (s, i, x)\nchar *s;\nint i, x;\n{\n printf(\"%s %d\", s, i);\n printf(\"\\n\");\n}\n\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! print tail\n! ----------\n!\n! Prints a line of dashes.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\n\nprinttail()\n{\n int j;\n printf(\"\\n\");\n for (j=1; j<=80; j++)\n {\n printf(\"-\");\n }\n printf(\"\\n\\n\");\n}\n\n\n\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! cointoss\n! --------\n!\n! Uses random number to return false with probability 0.5 otherwise\n! returns a non zero integer.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\nint cointoss()\n{\n if (uniform() > 0.5) return(0);\n return(1);\n}\n\n\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! printline\n! ----------\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\nprintline (s)\nchar *s;\n{\n printf(s);\n printf(\"\\n\");\n}\n\nspaces(n)\nint n;\n{\n int i;\n for (i=1; i<=n; i++) printf(\" \");\n}\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! getreal and skip;\n! ----------------\n!\n! Displays a prompt and reads in an real, skipping\n! to the end of the line. Checks the range of the integer\n! and stops the program if it is out of range.\n!\n! Parameters: s -> string prompt\n! i -> integer variable to input.\n! min = max value\n! max = min value.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\ngetrealandskip(char *s, double *i, double min, double max)\n{\n char ch;\n printf(s);\n printf(\" \");\n scanf(\"%lf\", i);\n do\n {\n ch = getchar();\n }\n while (ch != '\\n');\n if ((min != -infinity) && (*i < min))\n {\n printf(\"Value too small. Reading %s. Terminating.\", s);\n printf(\"\\n\");\n printf(\"Min allowable: \");\n printf(\"%f\", min);\n printf(\"\\n\");\n gabort(\"\", 0);\n } \n if ((max != infinity) && (*i > max)) \n {\n printf(\"Value too large. Reading %s. Terminating.\", s);\n printf(\"\\n\");\n printf(\"Max allowable: \");\n printf(\"%f\", max);\n printf(\"\\n\");\n gabort(\"\", 0);\n }\n}\n\ndouble calculaterealmean(double *a, int n)\n{\n double sum;\n int i;\n sum = 0.0;\n for (i=1; i<=n; i++)\n {\n sum = sum + a[i];\n }\n return(sum/(double)n);\n}\n \ntracestart()\n{\nprintf(\"Enter trace level \");\nscanf(\"%d\", &tracelevel);\n}\n\ntrace(s, i)\n{\n if (tracelevel==0) return(0);\n printf(\"%s %d\\n\", s, i);\n}\n\n\noutputrep(int j, int howoften)\n{\n if ((double)j/(double)howoften - floor((double)j/(double)howoften) == 0.0)\n printf(\"Completed iteration %d\\n\", j);\n}\n\n\noutputrepdot(int j, int reps)\n{\n int howoften;\n howoften = reps/10;\n if ((double)j/(double)howoften - floor((double)j/(double)howoften) == 0.0)\n {\n printf(\"%d.\", j/howoften);\n if (j==reps) printf(\"\\n\");\n fflush(stdout);\n }\n}\n\n\n\nmonitorinput()\n{\n inputcounter--;\n if (inputcounter <= 0)\n {\n printf(\"Enter int to continue \");\n scanf(\"%d\", &inputcounter);\n }\n}\n\n\ndouble normalheight(double x, double mu, double var)\n{\n double res;\n res = (1.0/sqrt(2.0*pi*var))*exp(-(x-mu)*(x-mu)/(2.0*var));\n return(res);\n}\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! simpson\n! -------\n!\n! Computes the area under the function using simpsons rule for the set of\n! points given.\n!\n! Parameters: x -> array of pairs of points.\n! points = no. of points.\n! a = lower value\n! v = upper value\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\n\ndouble simpson (double *x, int points, double a, double b)\n{\n int j, coeff;\n double res, h;\n if (2*(points/2) == points)\n {\n printf(\"FATAL ERROR: Even no. of points for SIMPSON.\\n\");\n monitorinput();\n }\n h = (b-a) / ((double)points-1.0);\n res = 0.0;\n for (j = 1; j<=points; j++)\n {\n if ((j == points) || (j==1 ))\n {\n coeff = 1;\n }\n else if (j == 2)\n {\n coeff = 4;\n }\n else if (coeff == 2) coeff = 4; else coeff = 2;\n/* %if trace level > 0 %then printstring(\"Coeff, x(j) \") %and write(coeff, 3) %and print(x(j), 2, 4) %and newline*/\n res = res + (double)coeff*x[j];\n }\n return((h/3.0) * res);\n}\n\n\n\n\nint odd(int i)\n{\n int x;\n x = i/2;\n if ((double)(i)/2.0 - (double)x == 0.0) return(false); else return(true);\n}\n\n\n\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! solve quadratic\n! ---------------\n!\n! Returns the roots of quadratic of parameters given.\n!\n! Parameters: a, b, c = parameters of quadratic.\n! root1, root2 = roots of quadratic.\n!\n! Returns : true => real roots.\n! false => no real root.\n!\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\nint solvequadratic(double a, double b, double c, double *r1, double *r2)\n{\n double x;\n x = b*b - 4.0*a*c;\n if (x < 0.0) return(false);\n *r1 = (-b + sqrt(x))/(2.0*a);\n *r2 = (-b - sqrt(x))/(2.0*a);\n return(true);\n}\n\n \n\n\n\nint skiptoendofline(FILE *fptr)\n{\n int status;\n char ch;\n do\n {\n status = fscanf(fptr, \"%c\", &ch);\n if (status==EOF) break;\n/* printf(\"skiptoendofline ch %c\\n\", ch);*/\n }\n while (ch!='\\n');\n return(status);\n}\n\n\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1\n!\n! aitken\n! ------\n!\n! Uses Aitken's formula to predict the asymptote from the three last points\n! in the array given.\n!\n! Parameters: x-> array of points.\n! t = max. point in array.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\ndouble aitken (double *a, int t)\n{\n double x;\n x = a[t-2] - 2.0*a[t-1] + a[t];\n if (x == 0) return(a[t]);\n return(-((a[t-1] - a[t])*(a[t-1] - a[t]))/x + a[t]);\n}\n\nint factorial(int i)\n{\n int res;\n res = 1; \n for (;;)\n {\n if (i==0) break;\n res = res*i;\n i--;\n }\n return(res);\n}\n\n\n\n\ndouble doublefactorial(double x)\n{\n double res;\n x = floor(x);\n res = 1.0; \n for (;;)\n {\n if (x==0.0) break;\n res = res*x;\n x = x - 1.0;\n }\n return(res);\n}\n\n\n\ndouble logdoublefactorial(double x)\n{\n double res;\n x = floor(x);\n res = 0.0;\n for (;;)\n {\n if (x==0.0) break;\n res = res + log(x);\n x = x - 1.0;\n }\n return(res);\n}\n\n\n\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! gammaalpha\n! ----------\n!\n! Returns the value of the parameter alpha of the gamma function.\n!\n! \n! Parameters: beta = parameter of gamma func.\n\n! epsilon = sqrt(E(a*a))\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\ndouble gammaalpha( beta, epsilon)\ndouble beta, epsilon;\n{\n double res;\n res = sqrt(beta*(beta + 1.0))/epsilon;\n return(res);\n}\n\n\n\n\ndouble asymptote_gamma(double z)\n{\n double res;\n res = (z - 0.5)*log(z) -z +0.5*log(2.0*pi) + 1.0/(12.0*z) \n - 1.0/(360.0*z*z*z) + 1.0/(1260.0*z*z*z*z*z) - 1.0/(1680.0*z*z*z*z*z*z*z);\n return(exp(res));\n}\n \n \n \ndouble series_gamma(double z)\n/* return gamma(z) using series expansion 6.1.34 of Abramowitz and Stegun */\n{\n #define maxc 26\n double c[maxc+1], res;\n int i;\n if (z > 2.0) return(asymptote_gamma(z));\n c[1] = 1.0;\n c[2] = 0.5772156649015329;\n c[3] =-0.6558780715202538;\n c[4] =-0.0420026350340952;\n c[5] = 0.1665386113822915;\n c[6] =-0.0421977345555443;\n c[7] =-0.0096219715278770;\n c[8] = 0.0072189432466630;\n c[9] =-0.0011651675918591;\n c[10]=-0.0002152416741149;\n c[11]= 0.0001280502823882;\n c[12]=-0.0000201348547807;\n c[13]=-0.0000012504934821;\n c[14]= 0.0000011330272320;\n c[15]=-0.0000002056338417;\n c[16]= 0.0000000061160950;\n c[17]= 0.0000000050020075;\n c[18]=-0.0000000011812746;\n c[19]= 0.0000000001043427;\n c[20]= 0.0000000000077823;\n c[21]=-0.0000000000036968;\n c[22]= 0.0000000000005100;\n c[23]=-0.0000000000000206;\n c[24]=-0.0000000000000054;\n c[25]= 0.0000000000000014;\n c[26]= 0.0000000000000001;\n res = 0.0;\n for (i=1; i<=26; i++)\n {\n res += c[i]*pow(z, (double)i);\n/* printf(\"gamma(z) %15.12f\\n\", 1.0/res); */\n }\n return(1.0/res);\n}\n\n\n\n\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! gammaht\n! -------\n!\n! Returns the height at point a of a gamma distribution.\n!\n! Parameters: epsilon, beta = gamma parameters.\n! a = value to evaluate.\n!\n! Returns gamma fn.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\ndouble gammaht(double epsilon, double beta, double a)\n{\n double gammabeta, res, a1, a2, a3, alpha;\n if (a==0.0)\n {\n printf(\"Illegal value (0.0) for gammaht()\\n\");\n monitorinput();\n }\n if (beta < 0.0) gabort(\"gammaht: invalid beta\\n\", beta);\n alpha = gammaalpha(beta, epsilon);\n gammabeta = series_gamma(beta);\n a1 = pow(alpha, beta);\n a2 = exp(-alpha*a);\n a3 = pow(a, beta - 1.0);\n res = a1*a2*a3/gammabeta;\n return(res);\n}\n\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!\n! half points\n! -----------\n!\n! This routine is called to check that the simpson numerical integration\n! is converging satisfactorily. It halves the number of points in\n! the array specified.\n!\n\n! Parameters: a -> array of points.\n! points -> no. of points.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\nhalfpoints(double *a, int *points)\n{\n int ptr1, ptr2, newpoints;\n if (odd(*points)==false)\n {\n printf(\"Half points: ERROR: no. of points for simpson must be odd.35\\n\");\n monitorinput();\n }\n ptr1 = 1;\n ptr2 = 1;\n do\n {\n a[ptr1] = a[ptr2];\n newpoints = ptr1;\n ptr1++;\n ptr2 = ptr2 + 2;\n }\n while (ptr2 <= *points);\n *points = newpoints;\n}\n\n\n\nsetuppoints(int pts, double *points, double lower, double upper, fun1 fn)\n{\n int i;\n double interval, x, a;\n interval = (upper - lower)/((double)pts - 1.0);\n x = lower;\n for (i = 1; i<=pts; i++)\n {\n a = fn(x);\n points[i] = a;\n x = x + interval;\n }\n\n}\n\n\n/*\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1\n!\n! numerical integ\n! ---------------\n!\n! Numerically integrates the function fn and returns the result in res.\n! Integrates over a number of ranges with different numbers of points per\n! range. Points must be a number like 65, 129, 257, 513... in each\n! range. Halves number of points to do integration 3 times as a check on\n! convergence\n!\n! Parameters:\n!\n!\n! resvec: contains vector of result for different numbers of points\n! start, finish: values limiting the function\n! fn(x): is the function to integrate\n! ranges: no. of ranges of points to evaluate.\n! points per range: no of points in each range.\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n*/\n\ndouble numericalinteg(double *resvec, double start, double finish, fun1 fn, int ranges,\n int *pointsperrange)\n{\n double lower, upper, r;\n double res[maxranges+2][4];\n/* The first dimension is contains the integral for each range, the\n last element containing the total. The second dimension contains\n results for each halving of the points.\n*/\n double points[maxsimpsonpoints+1];\n int i, j, k, fac, p;\n static int tmoutfileflag = 0; \n if (tmoutfileflag==0)\n {\n/* tmoutfile = fopen(\"numericalinteg.out\", \"w\");*/\n tmoutfileflag = 1;\n }\n/* printf(\"Start %f, finish %f, ranges %d\\n\", start, finish, ranges);*/\n upper = start;\n for (i = 1; i<= ranges; i++)\n {\n lower = upper;\n upper = lower + (finish - start)/(double)ranges;\n p = pointsperrange[i];\n if (p > maxsimpsonpoints) gabort(\"too many points for simpson\",p);\n setuppoints(p, points, lower, upper, fn);\n for (j = 1; j<=3; j++)\n {\n r = simpson(points, p, lower, upper);\n res[i][j] = r;\n if (j != 3) halfpoints(points, &p);\n }\n }\n for (i = 1; i<=3; i++)\n {\n res[ranges+1][i] = 0.0;\n for (j = 1; j<=ranges; j++)\n res[ranges+1][i] = res[ranges+1][i] + res[j][i];\n resvec[i] = res[ranges+1][i];\n }\n/* fprintf(tmoutfile, \"Results of numerical integration\\n\");\n for (i=1; i<=ranges; i++) fprintf(tmoutfile, \" Pts Range %d\", i);\n fprintf(tmoutfile, \" All\");\n fprintf(tmoutfile, \"\\n\");\n*/\n fac = 1;\n/* for (i = 1; i<=3; i++)\n {\n for (j = 1; j<=ranges+1; j++)\n {\n if (j!=ranges+1) fprintf(tmoutfile, \"%4d\", (pointsperrange[j]-1)/fac + 1);\n fprintf(tmoutfile, \"%10.4f\", res[j][i]);\n }\n fac = fac*2;\n fprintf(tmoutfile, \"\\n\");\n }\n*/\n return(res[ranges+1][1]);\n}\n\n\n\nFILE *openforread(char *str)\n{\n FILE *f;\n f = fopen(str, \"r\");\n if (f==0)\n {\n printf(\"ERROR: File %s not found.\\n\", str);\n exit(0);\n }\n else //printf(\"Opened file %s for read.\\n\", str);\n return(f);\n}\n\nFILE *openforwrite(char *str, char *mode)\n{\n FILE *f;\n f = fopen(str, mode);\n if (f==0)\n {\n printf(\"ERROR: Unable to open file %s for write.\\n\", str);\n exit(0);\n }\n else //printf(\"Opened file %s for write, \", str);\n if (mode[0]=='a') printf(\"append mode.\\n\");\n else if (mode[0]=='w') printf(\"overwrite mode.\\n\");\n else gabort(\"Invalid mode given in openforwrite\\n\", 0);\n return(f);\n}\n\n\nFILE *openforreadsilent(char *str)\n{\n FILE *f;\n f = fopen(str, \"r\");\n if (f==0)\n {\n printf(\"ERROR: File %s not found.\\n\", str);\n exit(0);\n }\n return(f);\n}\n\nFILE *openforwritesilent(char *str, char *mode)\n{\n FILE *f;\n f = fopen(str, mode);\n if (f==0)\n {\n printf(\"ERROR: Unable to open file %s for write.\\n\", str);\n exit(0);\n }\n if (mode[0]=='a')\n {\n }\n else if (mode[0]=='w')\n {\n }\n else gabort(\"Invalid mode given in openforwrite\\n\", 0);\n return(f);\n}\n\n\n \nprintmsefile(f, s, r)\nFILE *f;\nchar *s;\nstruct acc *r;\n{\n\n fprintf(f, \"%s %f +/- %f\\n\", s, accmean(r), se(r));\n}\n\n\n\n\nquadratic_regression(double n, double sumx, double sumx2, double sumy, double sumx3,\n double sumxy, double sumx4, double sumx2y, double *b1, double *b2, double *b3)\n{\n/* Solve system of 3 simultaneous equations:\n\na*b1 + b*b2 + c*b3 = d (1)\ne*b1 + f*b2 + g*b3 = h (2)\ni*b1 + j*b2 + k*b3 = l (3)\n\nThe actual parameters are appropriate for solving a quadratic regression -\n\ny = b3*x^2 + b2*x + b3\n\nSee assignments below.\n\n*/\n double a, b, c, d, e, f, g, h, i, j, k, l;\n double z1, z2, z3, z4, z5, z6;\n a = n;\n b = sumx;\n c = sumx2;\n d = sumy;\n e = b;\n f = c;\n g = sumx3;\n h = sumxy;\n i = c;\n j = g;\n k = sumx4;\n l = sumx2y;\n/* printf(\"\\n%lf %lf %lf %lf\\n\", a, b, c, d);\n printf(\"%lf %lf %lf %lf\\n\", e, f, g, h);\n printf(\"%lf %lf %lf %lf\\n\\n\", i, j, k, l);\n*/\n\n/* (1) - (2) -> b1*z1 + b2*z2 = z3 (4) */\n z1 = a/c - e/g;\n z2 = b/c - f/g;\n z3 = d/c - h/g;\n\n/* (1) - (3) -> b1*z4 + b2*z5 = z6 (5) */\n z4 = a/c - i/k;\n z5 = b/c - j/k;\n z6 = d/c - l/k;\n\n\n/* (4) - (5) */\n\n *b1 = (z3/z2 - z6/z5)/(z1/z2 - z4/z5);\n\n *b3 = ((d - a*(*b1))/b - (h - e**b1)/f) / (c/b - g/f);\n \n *b2 = (d - c*(*b3) - a*(*b1))/b;\n}\n\n\n\nint findtext(char *s, FILE *inptr)\n{\n int len, i, curchar, dum;\n char c;\n curchar = 0;\n len = 0;\n for (i=0; i<=100; i++)\n {\n if (s[i] == '\\0') break;\n len++;\n }\n for (;;)\n {\n c = getc(inptr);\n if (c == EOF) return(false);\n if (c==s[curchar])\n {\n curchar++;\n if (curchar==len) return(true);\n }\n else curchar = 0;\n }\n}\n\n/* FIND1DMAX */\n/* Finds the maximum of 3 points using a quadratic approximation */\n\nfind1dmax(double *xvec, double *yvec, double *xmax, double *ymax)\n{\n int i;\n double a, b, c, x1, x2, x3, y1, y2, y3, temp;\n double num, denom;\n/* for (i=1; i<=3; i++)\n {\n printf(\"xvec[%1d] %lf yvec[%1d] %lf\\n\", i, xvec[i], i, yvec[i]);\n }\n*/\n x1 = xvec[1];\n x2 = xvec[2];\n x3 = xvec[3];\n y1 = yvec[1];\n y2 = yvec[2];\n y3 = yvec[3];\n if (y1==y3) y1+= 0.000000000000001;\n if (y3==y2) y2+= 0.0000000000000001;\n/* printf(\"x1 %f x2 %f x3 %f y1 %f y2 %f y3 %f\\n\", x1, x2, x3, y1, y2, y3);*/\n num = (y1 - y3)*(x1 - x2)/(x1 - x3) - y1 + y2;\n denom = (x1*x1 - x3*x3)*(x1 - x2)/(x1 - x3) - (x1*x1 - x2*x2);\n a = num/denom;\n num = y1 - y2 - a*(x1*x1 - x2*x2);\n b = num/(x1 - x2);\n c = y1 - a*x1*x1 - b*x1;\n temp = -b/(2.0*a);\n *xmax = temp;\n *ymax = a*temp*temp + b*temp + c;\n}\n\n\n\n/* FIND2DMAX */\n/* Finds the maximum of a 3x3 grid using a sequential quadratic approximation */\n\ndouble find2dmax(double *xvec, double *yvec, double zmatrix[4][4], double *xmax, double *ymax)\n{\n int i, j;\n double vec[4], vec1[4], temp, max, max1, max2;\n/* for (i=1; i<=3; i++)\n {\n for (j=1; j<=3; j++)\n {\n if (zmatrix[i][j]==undefined) return(undefined);\n }\n }\n*/\n/* find the maximum for columns */\n for (i=1; i<=3; i++)\n {\n for (j=1; j<=3; j++)\n {\n vec[j] = zmatrix[i][j];\n }\n find1dmax(yvec, vec, &temp, &max);\n/* printf(\"Find1smax: zmax %lf ymax %lf\\n\", max, temp);*/\n vec1[i] = max;\n }\n find1dmax(xvec, vec1, xmax, &max1);\n/* printf(\"Columns: max %lf xmax %lf\\n\", max1, *xmax);*/\n/* find the maximum for rows */\n for (i=1; i<=3; i++)\n {\n for (j=1; j<=3; j++)\n {\n vec[j] = zmatrix[j][i];\n }\n find1dmax(xvec, vec, &temp, &max);\n/* printf(\"Find1dmax: zmax %lf ymax %lf\\n\", max, temp);*/\n vec1[i] = max;\n }\n find1dmax(yvec, vec1, ymax, &max2);\n/* printf(\"Rows: max %lf ymax %lf\\n\", max2, *ymax);*/\n max = (max1 + max2)/2.0;\n return(max);\n}\n\n\nint bnldev(double pp, int n)\n{\n int j, bnl;\n double p;\n p = (pp < 0.5 ? pp : 1.0 - pp);\n bnl = 0;\n for (j=1; j<=n; j++)\n if (uniform() < p) ++bnl;\n if (p!=pp) bnl = n - bnl;\n return bnl;\n}\n\n\nvoid metropolis(double y[], int ndim, double(*func)(double []),\n int limit, double delta[], double prevres, double *temperature)\n{\n #define step_change 0.2\n int i, j, param, accept;\n double step, res, diff, u;\n param = 0;\n *temperature = 1.0;\n for (i=1; i<=limit; i++)\n {\n/* printf(\"%d \", i);*/\n param++;\n if (param > ndim) param = 1;\n step = normal(0.0, delta[param]);\n/* printf(\"param %d delta[param] %lf, step %lf\\n\", param, delta[param], step);*/\n y[param] += step;\n res = (*func)(y);\n if (res > prevres)\n {\n diff = prevres - res;\n u = uniform();\n/* printf(\"diff %lf, exp(diff) %lf, u %lf\\n\", diff, exp(diff), u);*/\n if (u < pow(exp(diff), 1.0/(*temperature)))\n {\n accept = true;\n/* printf(\"Accepted\\n\");*/\n }\n else\n {\n accept = false;\n/* printf(\"Rejected\\n\");*/\n }\n }\n else\n {\n accept = true;\n/* printf(\"Accepted unconditionally\\n\");*/\n }\n if (accept == true) /* Note assume to be minimizing not maximizing */\n {\n prevres = res; /* accept the change */\n delta[param] *= (1.0 + step_change); /* Increase the step size */\n }\n else\n {\n y[param] -=step; /* reject the change */\n delta[param] *= (1.0 - step_change); /* Decrease the step size */\n }\n/* printf(\"Dump of delta vector: \");\n for (j=1; j<=ndim; j++)\n {\n printf(\"%lf \", delta[j]);\n }\n printf(\"\\n\"); monitorinput();\n*/\n *temperature -= 2.0/(double)limit;\n if (*temperature < 0.001) *temperature = 0.001;\n }\n}\n\n\n/* A slower way of generating poissons that the tabular method in poisson */\nint genpoisson(double xm)\n{\n static double sq, alxm, g, oldm = (-1.0);\n double em, t, y;\n// if (xm>300) gabort(\"genpoisson: xm too large\", 0);\n if (xm>=200.0) /* Use normal generator for very high xm */\n {\n return normal(0.0, sqrt(xm)) + xm;\n }\n if (xm!=oldm)\n {\n oldm = xm;\n g = exp(-xm);\n }\n em = -1;\n t = 1.0;\n do\n {\n ++em;\n t *= uniform();\n }\n while (t > g);\n return em;\n}\n\n\n\nvoid qsortreals (double *a, int from, int to)\n {\n int l, v;\n double d;\n if (from >= to) return;\n l = from;\n v = to;\n d = a[v];\n for (;;)\n {\n while ((l < v) && (a[l] <= d))\n {\n l = l + 1 ;\n }\n if (l==v) break;\n a[v] = a[l];\n while ((v > l) && (a[v] >= d))\n {\n v = v - 1;\n }\n if (v==l) break;\n a[l] = a[v];\n }\n\n/* ! now l=v*/\n a[v] = d;\n l = l-1;\n v = v+1;\n qsortreals(a, from, l);\n qsortreals(a, v, to);\n}\n\n\n\n#define maxofrs 100\n\nFILE *openfilecheck2dir(char *str)\n/*\n Attempts to open file str, if fails first time attempts to open\n../str or ../../str\n*/\n{\n FILE *f;\n static char s[maxofrs];\n int i;\n f = fopen(str, \"r\");\n if (f==0)\n {\n s[0] = '.';\n s[1] = '.';\n s[2] = '/';\n i=0;\n for (;;)\n {\n if (i+3 > maxofrs) gabort(\"String too long\", i);\n s[i+3] = str[i];\n if (str[i] == '\\0') break;\n i++;\n }\n f = fopen(s, \"r\");\n if (f==0)\n {\n s[0] = '.';\n s[1] = '.';\n s[2] = '/';\n s[3] = '.';\n s[4] = '.';\n s[5] = '/';\n i=0;\n for (;;)\n {\n if (i+6 > maxofrs) gabort(\"String too long\", i);\n s[i+6] = str[i];\n if (str[i] == '\\0') break;\n i++;\n }\n f = fopen(s, \"r\");\n if (f==0)\n {\n printf(\"ERROR: File %s not found.\\n\", str);\n exit(0);\n }\n else printf(\"Opened file %s for read.\\n\", s);\n }\n else printf(\"Opened file %s for read.\\n\", s);\n }\n else printf(\"Opened file %s for read.\\n\", str);\n return(f);\n}\n\n\n\nfloat rtsafe(void (*funcd)(float, float *, float *), float x1, float x2, float xacc)\n{\n #define MAXIT 100\n int j;\n float df, dx, dxold, f, fh, fl;\n float temp, xh, xl, rts;\n (*funcd)(x1, &fl, &df);\n (*funcd)(x2, &fh, &df);\n if ((fl > 0.0 && fh > 0.0) || (fl < 0.0 && fh < 0.0))\n gabort(\"Rtsafe: roots must be bracketed\", 0);\n if (fl == 0.0) return(x1);\n if (fh == 0.0) return(x2);\n if (fl < 0.0)\n {\n xl = x1;\n xh = x2;\n }\n else\n {\n xh = x1;\n xl = x2;\n }\n rts = 0.5*(x1+x2);\n dxold = fabs(x2-x1);\n dx = dxold;\n (*funcd)(rts, &f, &df);\n for (j=1; j<=MAXIT; j++)\n {\n if ((((rts-xh)*df-f)*((rts-xl)*df-f) >=0.0)\n || (fabs(2.0*f) > fabs(dxold*df)))\n {\n dxold = dx;\n dx = 0.5*(xh-xl);\n rts = xl +dx;\n if (xl==rts) return rts;\n }\n else\n {\n dxold = dx;\n dx = f/df;\n temp = rts;\n rts -= dx;\n if (temp==rts) return (rts);\n }\n if (fabs(dx) < xacc) return rts;\n (*funcd)(rts, &f, &df);\n if (f < 0.0)\n xl = rts;\n else\n xh = rts;\n }\n printf(\"warning: rtsafe: Maximum interations exceeded\\n\"); monitorinput();\n return (rts);\n}\n\n\n/* Algorith to generate bivariate normal deviates provided by Ian\n White\n*/\n\nbivariatenormal(double *z1, double *z2, double var1, double var2, double cov)\n{\n double s;\n quicknormal(z1, z2); /* uncorrelated normal deviates mean 0 SD 1 */\n *z1 *= sqrt(var1); /* Scale Z1 according to the standard deviation */\n s = var2 - cov*cov/var1;\n if (s<0) gabort(\"Invalid parameters for bivnormal\", s);\n *z2 = (cov/var1)*(*z1) + sqrt(s)*(*z2);\n}\n\n\nget_silent_mode(int argc, char *argv[], int *silent_mode)\n{\n int n_command_line_param, i;\n *silent_mode = 0;\n n_command_line_param = argc;\n// printf(\"n_command_line_param %d\\n\", n_command_line_param);\n for (i=1; i 99) \n gabort(\"makefilename: file index too large\", ind);\n if (ind > 9)\n {\n i1 = ind/10;\n ch = i1 + '0';\n outfilename[len] = ch;\n// printf(\"Char 1 ind %d i1 %d ch %c\\n\", ind, i1, ch); monitorinput();\n i1 = ind - (ind/10)*10;\n ch = i1 + '0';\n// printf(\"Char 2 ind %d i1 %d ch %c\\n\", ind, i1, ch); monitorinput();\n outfilename[len+1] = ch;\n outfilename[len+2] = '\\0';\n }\n else\n {\n ch = ind + '0';\n// printf(\"Char 1 ind %d i1 %d ch %c\\n\", ind, i1, ch); monitorinput();\n outfilename[len] = ch;\n outfilename[len+1] = '\\0';\n }\n// printf(\"makefilename: results %s\\n\", outfilename);\n}\n\n\n// --------------------------------------------------------------------\n// Routine for grid searching a function f that takes integer values as\n// it's paramters\n// --------------------------------------------------------------------\n\ndouble fill_out_grid(double **grid, int x0, int x1, int y0, int y1,\n int step_size_x, int step_size_y,\n double (*f)(int, int), int *max_x, int *max_y, int *nfunc)\n{\n double max_fun, f_result;\n int i, j, evaluated;\n *max_x = -1;\n *max_y = -1;\n max_fun = undefined;\n i = x0;\n for (;;)\n {\n j = y0;\n for (;;)\n {\n evaluated = 0;\n if (grid[i][j]==undefined)\n {\n f_result = (*f)(i, j);\n (*nfunc)++;\n grid[i][j] = f_result;\n evaluated = 1;\n }\n else f_result = grid[i][j];\n// printf(\"i %d j %d f_result %lf \", i, j, f_result);\n// if (evaluated == 1) printf(\"evaluated\\n\");\n// else printf(\"not evaluated\\n\");\n if ((f_result > max_fun)||(max_fun==undefined))\n {\n max_fun = f_result;\n *max_x = i;\n *max_y = j;\n }\n if (j==y1) break;\n j += step_size_y;\n if (j > y1) j = y1;\n }\n if (i==x1) break;\n i += step_size_x;\n if (i > x1) i = x1;\n }\n return max_fun;\n}\n\n\nint_to_string(int v, char *str, int max_len)\n{\n int divisor = 10000000, i1, ind = 0, digit_encountered = 0;\n char ch;\n if (v > divisor) gabort(\"int_to_string: integer parameter to large\", v);\n for (;;)\n {\n i1 = v/divisor;\n// printf(\"i1 %d divisor %d\\n\", i1, divisor);\n if (i1 >= 0)\n {\n ch = i1 + '0';\n if (ch!='0') digit_encountered = 1;\n// printf(\"ch %c\\n\", ch);\n if (digit_encountered)\n {\n str[ind] = ch;\n ind++;\n if (ind == max_len) gabort(\"int_to_string: string too long\", ind);\n }\n v = v - i1*divisor;\n }\n divisor /= 10;\n if (divisor == 1) break;\n// monitorinput();\n }\n ch = v + '0';\n// printf(\"ch %c\\n\", ch);\n str[ind] = ch;\n ind++;\n if (ind == max_len) gabort(\"int_to_string: string too long\", ind);\n str[ind] = '\\0';\n}\n\n\n// bilinear_interpolation:\n// First 4 parameters are positions on x and y axes\n// Second 4 are function values\n// x and y are positions to be evaluated.\n\ndouble bilinear_interpolation(double x1, double x2, double y1, double y2,\n double x1y1, double x1y2, double x2y1, double x2y2,\n double x, double y)\n{\n double res;\n res = (x2 - x)*(y2 - y)*x1y1 +\n (x - x1)*(y2 - y)*x2y1 +\n (x2 - x)*(y - y1)*x1y2 +\n (x - x1)*(y - y1)*x2y2;\n\n res /= ((x2 - x1)*(y2 - y1));\n return res;\n}\n\n// --------------------\n// kimura_fixation_prob\n// --------------------\n// Returns fixation probability of an additive mutation, assuming that s\n// is small in a diploid population\n//\n// Parameters\n// ---------\n// s - selection coefficient, difference between the homozygotes.\n// N - Population effective size.\n//\n\ndouble kimura_fixation_prob(double s, int N)\n{\n double num, denom;\n if ((s < 0.0)&&((double)N*s > -0.0000001)) // Trap numerical problems\n {\n num = 1.0;\n denom = 2.0*(double)N;\n }\n else if ((s > 0.0)&&((double)N*s < 0.0000001))\n {\n num = 1.0;\n denom = 2.0*(double)N;\n }\n else\n {\n num = 1 - exp(-s);\n denom = 1 - exp(-2*(double)N*s);\n }\n// printf(\"s %14.14lf N %d num %lf denom %lf num/denom %lf\\n\",\n/// s, N, num, denom, num/denom);\n// monitorinput();\n return num/denom;\n}\n\n// --------------------\n// kimura_fixation_prob\n// --------------------\n// Returns fixation probability of an additive mutation, assuming that s\n// is small in a diploid population\n//\n// Parameters\n// ---------\n// s - selection coefficient, difference between the homozygotes.\n// N - Population effective size.\n//\n\ndouble kimura_fixation_prob_X_loci(double s, int N)\n{\n double num, denom;\n if ((s < 0.0)&&((double)N*s > -0.0000001)) // Trap numerical problems\n {\n num = 1.0;\n denom = 2.0*(double)N;\n }\n else if ((s > 0.0)&&((double)N*s < 0.0000001))\n {\n num = 1.0;\n denom = 2.0*(double)N;\n }\n else\n {\n num = 1 - exp(-s);\n denom = 1 - exp(-2*(double)N*s);\n }\n// printf(\"s %14.14lf N %d num %lf denom %lf num/denom %lf\\n\",\n/// s, N, num, denom, num/denom);\n// monitorinput();\n return num/denom;\n}\n\n\n//----------------------------------------\n// normal_cumulative_probability_function\n// ---------------------------------------\n//\n// Returns the area under the normal pdf from -infinity to x.\n// From algorithm described in Abramowitz and Stegun.\n\ndouble normal_cumulative_probability_function(const double x)\n{\n const double b1 = 0.319381530;\n const double b2 = -0.356563782;\n const double b3 = 1.781477937;\n const double b4 = -1.821255978;\n const double b5 = 1.330274429;\n const double p = 0.2316419;\n const double c = 0.39894228;\n\n if(x >= 0.0) {\n double t = 1.0 / ( 1.0 + p * x );\n return (1.0 - c * exp( -x * x / 2.0 ) * t *\n ( t *( t * ( t * ( t * b5 + b4 ) + b3 ) + b2 ) + b1 ));\n }\n else {\n double t = 1.0 / ( 1.0 - p * x );\n return ( c * exp( -x * x / 2.0 ) * t *\n ( t *( t * ( t * ( t * b5 + b4 ) + b3 ) + b2 ) + b1 ));\n }\n}\n\n//----------------------------------------\n// dump_matrix\n//----------------------------------------\n//\n// Prints out the matrix X with 1..rows, 1..cols rows and columns, respectively.\n//\n// s -> string to print\n// X -> matrix, usually allocated using dmatrix(), dimension rows, cols\n// rows = rows, 1 relative\n// cols = cols, 1 relative\n\ndump_matrix(char *s, double **X, int rows, int cols)\n{\n int i, j;\n printf (\"%s\\n\", s);\n for (i = 1; i <=rows; i++)\n {\n for (j = 1; j <= cols; j++)\n {\n printf(\"%lf \", X[i][j]);\n }\n printf(\"\\n\");\n }\n}\n\n//----------------------------------------\n// compute_matrix_transpose\n//----------------------------------------\n//\n// Generates the transpose of X.\n//\n// X -> matrix, usually allocated using dmatrix(), dimension rows, cols\n// rows = rows of X, 1 relative\n// cols = cols of X, 1 relative\n// XT -> result matrix, allocated using dmatrix(), dimension cols, rows\n\ncompute_matrix_transpose(double **X, double **XT, int rows, int cols)\n{\n int i, j;\n for (i=1; i<=rows; i++)\n {\n for (j=1; j<=cols; j++)\n {\n XT[j][i] = X[i][j];\n }\n }\n}\n\n//----------------------------------------\n// multiply_matrices\n//----------------------------------------\n//\n// Carry out matrix operation XY, putting result in RES.\n//\n// RES -> result matrix dimension rows_X, cols_X, usually allocated using\n// dmatrix()\n// X -> matrix dimension rows_X, cols_X, usually allocated using dmatrix()\n// Y -> matrix dimension rows_Y, cols_Y, usually allocated using dmatrix()\n// rows_X = rows of X, 1 relative\n// cols_X = cols of X, 1 relative\n// rows_Y = rows of Y, 1 relative\n// cols_Y = cols of Y, 1 relative\n\nmultiply_matrices(double **RES, double **X, double **Y, int rows_X, int cols_X,\n int rows_Y, int cols_Y)\n// Matrix X has dimension rows_X, cols_X and Y has dimension rows_Y, cols_Y. The\n// result has dimension rows_X, cols_Y.\n{\n int i, j, k;\n double element;\n if (cols_X != rows_Y)\n {\n gabort(\"multiply_matrices: cols_X != rows_Y\", 0);\n }\n// printf(\"multiply_matrices: rows_X %d cols_X %d\\n\", rows_X, cols_X);\n// dump_matrix(\"multiply_matrices: Matrix X\", X, rows_X, cols_X);\n// monitorinput();\n// printf(\"multiply_matrices: rows_Y %d cols_Y %d\\n\", rows_Y, cols_Y);\n// dump_matrix(\"multiply_matrices: Matrix Y\", Y, rows_Y, cols_Y);\n// monitorinput();\n for (i=1; i<=rows_X; i++)\n {\n for (j=1; j<=cols_Y; j++)\n {\n element = 0.0;\n for (k=1; k<=cols_X; k++)\n {\n// printf(\"X[%d][%d] %lf X[%d][%d] %lf\\n\",\n// i, k, X[i][k], k, j, Y[k][j]);\n element += X[i][k]*Y[k][j];\n// printf(\"i %d j %d k %d element %lf\\n\", i, j, k, element);\n// monitorinput();\n }\n// printf(\"RES[%d][%d] %lf\\n\", i, j, element); monitorinput();\n RES[i][j] = element;\n }\n }\n}\n\n// ----------------------------------------------\n// normal_approx_to_binomial\n// ----------------------------------------------\n//\n// Uses the normal approximation to calculate the probability of i successes\n// from n trials if the probabilituy of one sucess is p\n\ndouble normal_approx_to_binomial(int i, int n, double p)\n{\n double m, s, z_upper, z_lower, area_lower, area_upper;\n m = p*(double)n;\n s = sqrt((1.0-p)*p*(double)n);\n// printf(\"m %lf s %lf\\n\", m, s);\n z_lower = ((double)i - 0.5 - m)/s;\n area_lower = normal_cumulative_probability_function(z_lower);\n z_upper = ((double)i + 0.5 - m)/s;\n area_upper = normal_cumulative_probability_function(z_upper);\n// printf(\"z_lower %lf area_lower %lf z_upper %lf area_upper %lf\\n\",\n// z_lower, area_lower, z_upper, area_upper);\n return(area_upper - area_lower);\n}\n\n// ----------------------------------------------\n\n// loadparam\n// paramvec = vector with 2 elements: element 0 = 0 => parameter not variable\n// element 0 = 1 => parameter variable\n// element 1 location to get parameter value\n// curpos = index - 1 from which to load parameter\n// p: matrix into which parameter loaded\n//\n\nloadparam(double *paramvec, int *curpos, double **p)\n{\n if (paramvec[0]!=0.0)\n {\n *curpos = *curpos + 1;\n p[1][*curpos] = paramvec[1];\n }\n}\n\n// ----------------------------------------------\n// unloadparam\n// paramvec = vector with 2 elements: element 0 = 0 => parameter not variable\n// element 0 = 1 => parameter variable\n// curpos = index -1 in which to unload parameter\n// x = vector containing parameter value\n\nunloadparam(double *paramvec, int *curpos, double x[])\n{\n if (paramvec[0]!=0.0)\n {\n *curpos = *curpos + 1;\n paramvec[1] = x[*curpos];\n }\n}\n", "meta": {"hexsha": "dc91be14d9274a12590135953b856d09627d866b", "size": 52020, "ext": "c", "lang": "C", "max_stars_repo_path": "genlib.c", "max_stars_repo_name": "kousathanas/simsfs_fast", "max_stars_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "genlib.c", "max_issues_repo_name": "kousathanas/simsfs_fast", "max_issues_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "genlib.c", "max_forks_repo_name": "kousathanas/simsfs_fast", "max_forks_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6567944251, "max_line_length": 120, "alphanum_fraction": 0.4868127643, "num_tokens": 16165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.40134981033755524}} {"text": "/*****************************************************************************\n * *\n * Copyright 2018 Rice University *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); *\n * you may not use this file except in compliance with the License. *\n * You may obtain a copy of the License at *\n * *\n * http://www.apache.org/licenses/LICENSE-2.0 *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * *\n *****************************************************************************/\n#ifndef LDA_DOC_WORD_TOPIC_JOIN_H\n#define LDA_DOC_WORD_TOPIC_JOIN_H\n\n#include \"JoinComp.h\"\n#include \"Lambda.h\"\n#include \"LDADocWordTopicAssignment.h\"\n#include \"LDA/LDATopicWordProb.h\"\n#include \"LambdaCreationFunctions.h\"\n#include \"LDADocument.h\"\n#include \"IntDoubleVectorPair.h\"\n#include \"PDBVector.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* This class implements the join between documents, doc-topic probability and word-topic probability */\nusing namespace pdb;\n\nclass LDADocWordTopicJoin : public JoinComp {\n\nprivate:\n Handle> myMem;\n unsigned numWords;\n\npublic:\n ENABLE_DEEP_COPY\n\n LDADocWordTopicJoin() {}\n\n LDADocWordTopicJoin(unsigned numWords) : numWords(numWords) {\n\n\t/* Set up the random number generator */\n /* Set up the gsl_rng *src */\n gsl_rng* src = gsl_rng_alloc(gsl_rng_mt19937);\n std::random_device rd;\n std::mt19937 gen(rd());\n gsl_rng_set(src, gen());\n\n /* Allocate space needed for myRand */\n int spaceNeeded = sizeof(gsl_rng) + src->type->size;\n myMem = makeObject>(spaceNeeded, spaceNeeded);\n\n /* Copy src over */\n memcpy(myMem->c_ptr(), src, sizeof(gsl_rng));\n memcpy(myMem->c_ptr() + sizeof(gsl_rng), src->state, src->type->size);\n\n gsl_rng_free(src);\n }\n\n /* Join condition */\n Lambda getSelection(Handle doc,\n Handle DocTopicProb,\n Handle WordTopicProb) override {\n return (makeLambdaFromMethod(doc, getDoc) ==\n makeLambdaFromMethod(DocTopicProb, getUnsigned)) &&\n (makeLambdaFromMethod(doc, getWord) == makeLambdaFromMethod(WordTopicProb, getKey));\n }\n\n Lambda> getProjection(\n Handle doc,\n Handle DocTopicProb,\n Handle WordTopicProb) override {\n\n return makeLambda(\n doc,\n DocTopicProb,\n WordTopicProb,\n [&](Handle& doc,\n Handle& DocTopicProb,\n Handle& WordTopicProb) {\n int size = (DocTopicProb->getVector()).size();\n\n /* Compute the posterior probailities of the word coming from each topic */\n double* myProb = new double[size];\n double* topicProbs = DocTopicProb->getVector().c_ptr();\n double* wordProbs = WordTopicProb->getVector().c_ptr();\n for (int i = 0; i < size; ++i) {\n myProb[i] = topicProbs[i] * wordProbs[i];\n }\n\n unsigned* topics = new unsigned[size]{0};\n\n /* Sample the topics (multinomial sampling) */\n gsl_rng* rng = getRng();\n\n unsigned counts = doc->getCount();\n double* random_values = new double[counts];\n\n double sum = 0.0;\n for (int i = 0; i < size; ++i) {\n sum += myProb[i];\n }\n\n for (int i = 0; i < counts; ++i) {\n random_values[i] = gsl_rng_uniform(rng) * sum;\n }\n\n std::sort(random_values, random_values + counts);\n\n int j = 0;\n double accumuProb = 0.0;\n for (int i = 0; i < size; i++) {\n accumuProb += myProb[i];\n while ((j < counts) && (random_values[j] < accumuProb)) {\n topics[i]++;\n j++;\n }\n }\n\n /* Get the container for the return value */\n Handle retVal = makeObject();\n retVal->setup();\n LDADocWordTopicAssignment& myGuy = *retVal;\n\n unsigned myDoc = doc->getDoc();\n unsigned myWord = doc->getWord();\n\n /* Create the doc assignment and topic assignment from the sampled topics, and put them in the return value */\n for (int i = 0; i < size; ++i) {\n if (topics[i] != 0) {\n Handle whichDoc =\n makeObject(size, myDoc, i, topics[i]);\n Handle whichTopic =\n makeObject(numWords, i, myWord, topics[i]);\n myGuy.push_back(whichDoc);\n myGuy.push_back(whichTopic);\n }\n }\n\n delete[] myProb;\n delete[] topics;\n delete[] random_values;\n\n return retVal;\n });\n }\n\n /* Get the GSL RNG from myMem */\n gsl_rng* getRng() {\n gsl_rng* dst = (gsl_rng*)myMem->c_ptr();\n dst->state = (void*)(myMem->c_ptr() + sizeof(gsl_rng));\n dst->type = gsl_rng_mt19937;\n return dst;\n }\n};\n\n#endif\n", "meta": {"hexsha": "6a9a1b7b3a7d058d612d4f3413b7e1d87fa5992e", "size": 6770, "ext": "h", "lang": "C", "max_stars_repo_path": "pdb/src/sharedLibraries/headers/LDA/LDADocWordTopicJoin.h", "max_stars_repo_name": "dimitrijejankov/pdb", "max_stars_repo_head_hexsha": "395b5ebd48c2c1b14a56bf24aeea726b36559074", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2018-06-14T03:19:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T02:45:12.000Z", "max_issues_repo_path": "pdb/src/sharedLibraries/headers/LDA/LDADocWordTopicJoin.h", "max_issues_repo_name": "dimitrijejankov/pdb", "max_issues_repo_head_hexsha": "395b5ebd48c2c1b14a56bf24aeea726b36559074", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-07-03T21:50:14.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-01T15:36:07.000Z", "max_forks_repo_path": "pdb/src/sharedLibraries/headers/LDA/LDADocWordTopicJoin.h", "max_forks_repo_name": "dimitrijejankov/pdb", "max_forks_repo_head_hexsha": "395b5ebd48c2c1b14a56bf24aeea726b36559074", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-06-14T03:39:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-03T00:58:24.000Z", "avg_line_length": 39.3604651163, "max_line_length": 126, "alphanum_fraction": 0.4967503693, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.40131797153104715}} {"text": "/**\n *\n * @file core_dtsqrt.c\n *\n * PLASMA core_blas kernel\n * PLASMA is a software package provided by Univ. of Tennessee,\n * Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @author Mathieu Faverge\n * @author Jakub Kurzak\n * @date 2010-11-15\n * @generated d Tue Jan 7 11:44:45 2014\n *\n **/\n#include \n#include \"common.h\"\n#undef COMPLEX\n#define REAL\n\n/***************************************************************************//**\n *\n * @ingroup CORE_double\n *\n * CORE_dtsqrt computes a QR factorization of a rectangular matrix\n * formed by coupling a complex N-by-N upper triangular tile A1\n * on top of a complex M-by-N tile A2:\n *\n * | A1 | = Q * R\n * | A2 |\n *\n *******************************************************************************\n *\n * @param[in] M\n * The number of columns of the tile A2. M >= 0.\n *\n * @param[in] N\n * The number of rows of the tile A1.\n * The number of columns of the tiles A1 and A2. N >= 0.\n *\n * @param[in] IB\n * The inner-blocking size. IB >= 0.\n *\n * @param[in,out] A1\n * On entry, the N-by-N tile A1.\n * On exit, the elements on and above the diagonal of the array\n * contain the N-by-N upper trapezoidal tile R;\n * the elements below the diagonal are not referenced.\n *\n * @param[in] LDA1\n * The leading dimension of the array A1. LDA1 >= max(1,N).\n *\n * @param[in,out] A2\n * On entry, the M-by-N tile A2.\n * On exit, all the elements with the array TAU, represent\n * the unitary tile Q as a product of elementary reflectors\n * (see Further Details).\n *\n * @param[in] LDA2\n * The leading dimension of the tile A2. LDA2 >= max(1,M).\n *\n * @param[out] T\n * The IB-by-N triangular factor T of the block reflector.\n * T is upper triangular by block (economic storage);\n * The rest of the array is not referenced.\n *\n * @param[in] LDT\n * The leading dimension of the array T. LDT >= IB.\n *\n * @param[out] TAU\n * The scalar factors of the elementary reflectors (see Further\n * Details).\n *\n * @param[out] WORK\n *\n *******************************************************************************\n *\n * @return\n * \\retval PLASMA_SUCCESS successful exit\n * \\retval <0 if -i, the i-th argument had an illegal value\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dtsqrt = PCORE_dtsqrt\n#define CORE_dtsqrt PCORE_dtsqrt\n#define CORE_dtsmqr PCORE_dtsmqr\nint CORE_dtsmqr(PLASMA_enum side, PLASMA_enum trans,\n int M1, int N1, int M2, int N2, int K, int IB,\n double *A1, int LDA1,\n double *A2, int LDA2,\n const double *V, int LDV,\n const double *T, int LDT,\n double *WORK, int LDWORK);\n#endif\n\nint CORE_dtsqrt(int M, int N, int IB,\n double *A1, int LDA1,\n double *A2, int LDA2,\n double *T, int LDT,\n double *TAU, double *WORK)\n{\n static double zone = 1.0;\n static double zzero = 0.0;\n\n double alpha;\n int i, ii, sb;\n\n /* Check input arguments */\n if (M < 0) {\n coreblas_error(1, \"Illegal value of M\");\n return -1;\n }\n if (N < 0) {\n coreblas_error(2, \"Illegal value of N\");\n return -2;\n }\n if (IB < 0) {\n coreblas_error(3, \"Illegal value of IB\");\n return -3;\n }\n if ((LDA2 < max(1,M)) && (M > 0)) {\n coreblas_error(8, \"Illegal value of LDA2\");\n return -8;\n }\n\n /* Quick return */\n if ((M == 0) || (N == 0) || (IB == 0))\n return PLASMA_SUCCESS;\n\n for(ii = 0; ii < N; ii += IB) {\n sb = min(N-ii, IB);\n for(i = 0; i < sb; i++) {\n /*\n * Generate elementary reflector H( II*IB+I ) to annihilate\n * A( II*IB+I:M, II*IB+I )\n */\n LAPACKE_dlarfg_work(M+1, &A1[LDA1*(ii+i)+ii+i], &A2[LDA2*(ii+i)], 1, &TAU[ii+i]);\n\n if (ii+i+1 < N) {\n /*\n * Apply H( II*IB+I ) to A( II*IB+I:M, II*IB+I+1:II*IB+IB ) from the left\n */\n alpha = -(TAU[ii+i]);\n cblas_dcopy(\n sb-i-1,\n &A1[LDA1*(ii+i+1)+(ii+i)], LDA1,\n WORK, 1);\n#ifdef COMPLEX\n LAPACKE_dlacgv_work(sb-i-1, WORK, 1);\n#endif\n cblas_dgemv(\n CblasColMajor, (CBLAS_TRANSPOSE)PlasmaTrans,\n M, sb-i-1,\n (zone), &A2[LDA2*(ii+i+1)], LDA2,\n &A2[LDA2*(ii+i)], 1,\n (zone), WORK, 1);\n#ifdef COMPLEX\n LAPACKE_dlacgv_work(sb-i-1, WORK, 1 );\n#endif\n cblas_daxpy(\n sb-i-1, (alpha),\n WORK, 1,\n &A1[LDA1*(ii+i+1)+ii+i], LDA1);\n#ifdef COMPLEX\n LAPACKE_dlacgv_work(sb-i-1, WORK, 1 );\n#endif\n cblas_dger(\n CblasColMajor, M, sb-i-1, (alpha),\n &A2[LDA2*(ii+i)], 1,\n WORK, 1,\n &A2[LDA2*(ii+i+1)], LDA2);\n }\n /*\n * Calculate T\n */\n alpha = -TAU[ii+i];\n cblas_dgemv(\n CblasColMajor, (CBLAS_TRANSPOSE)PlasmaTrans, M, i,\n (alpha), &A2[LDA2*ii], LDA2,\n &A2[LDA2*(ii+i)], 1,\n (zzero), &T[LDT*(ii+i)], 1);\n\n cblas_dtrmv(\n CblasColMajor, (CBLAS_UPLO)PlasmaUpper,\n (CBLAS_TRANSPOSE)PlasmaNoTrans, (CBLAS_DIAG)PlasmaNonUnit, i,\n &T[LDT*ii], LDT,\n &T[LDT*(ii+i)], 1);\n\n T[LDT*(ii+i)+i] = TAU[ii+i];\n }\n if (N > ii+sb) {\n CORE_dtsmqr(\n PlasmaLeft, PlasmaTrans,\n sb, N-(ii+sb), M, N-(ii+sb), IB, IB,\n &A1[LDA1*(ii+sb)+ii], LDA1,\n &A2[LDA2*(ii+sb)], LDA2,\n &A2[LDA2*ii], LDA2,\n &T[LDT*ii], LDT,\n WORK, sb);\n }\n }\n return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "64745cdffbcd95033198ad3db5a4909eaa97cb84", "size": 6258, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_dtsqrt.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas/core_dtsqrt.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas/core_dtsqrt.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5268292683, "max_line_length": 93, "alphanum_fraction": 0.4659635666, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.40101791712441026}} {"text": "/*\n * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer\n *\n * Yan-Rong Li, liyanrong@mail.ihep.ac.cn\n * Jun 30, 2016\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"dnestvars.h\"\n\n\n/*! \\file dnestpostprocess.c\n * \\brief post process the sample generated by dnest. \n */ \n\nint cmp_sample(const void *pa, const void *pb);\ntypedef struct\n{\n double logl, tiebreaker;\n int id;\n}SampleType;\n\n/*\n * This function calculates log(exp(x1) - exp(x2)).\n */\ndouble logdiffexp(double x1, double x2) // x1 is larger\n{\n double biggest = x1;\n double xx1 = x1 - biggest, xx2 = x2 - biggest;\n return log(exp(xx1) - exp(xx2)) + biggest;\n}\n/*\n * This functions calculates log(exp(x1)+...+exp(xn)).\n */\ndouble logsumexp(double *x, int n)\n{\n int j;\n double sum, max;\n \n max = x[0];\n for(j = 0; j < n; j++)\n {\n max = fmax(max, x[j]);\n }\n sum = 0.0;\n for(j=0; j< n; j++)\n {\n sum += exp( x[j] - max);\n }\n return log(sum) + max;\n}\n\nvoid postprocess(double temperature)\n{\n printf(\"# Starts postprocess.\\n\");\n FILE *fp, *fp_sample;\n \n double **levels_orig, **sample_info, *logl;\n int *sandwhich;\n double *psample;\n int i, j;\n int num_levels, num_samples;\n char buf[BUF_MAX_LENGTH];\n int moreSample = 1;\n \n // read number of levels and samples\n fp = fopen(options.sampler_state_file, \"r\");\n if(fp == NULL)\n {\n fprintf(stderr, \"# Error: Cannot open file %s.\\n\", options.sampler_state_file);\n exit(0);\n }\n fscanf(fp, \"%d %d\\n\", &num_levels, &num_samples);\n fclose(fp);\n \n // allocate memory for levels\n levels_orig = malloc(num_levels * sizeof(double *));\n for(i=0; i< num_levels; i++)\n {\n levels_orig[i] = malloc(3 * sizeof(double));\n }\n \n // allocate memory for sample_info\n sample_info = malloc(num_samples * sizeof(double *));\n for(i=0; i< num_samples; i++)\n {\n sample_info[i] = malloc(3 * sizeof(double));\n }\n \n // allocate memory for samples\n logl = (void *)malloc(num_samples * sizeof(double));\n sandwhich = malloc(num_samples * sizeof(int));\n psample = (double *)malloc(dnest_size_of_modeltype);\n \n // read levels\n fp = fopen(options.levels_file, \"r\");\n if(fp == NULL)\n {\n fprintf(stderr, \"# Error: Cannot open file %s.\\n\", options.levels_file);\n exit(0);\n }\n fgets(buf, BUF_MAX_LENGTH, fp);\n for(i=0; i < num_levels; i++)\n {\n if(feof(fp) != 0)\n {\n fprintf(stderr, \"# Error: file %s ends at %d.\\n\", options.levels_file, i);\n exit(0);\n }\n\n fgets(buf, BUF_MAX_LENGTH, fp);\n \n if(sscanf(buf, \"%lf %lf %lf\", &levels_orig[i][0], &levels_orig[i][1], &levels_orig[i][2]) < 3)\n {\n fprintf(stderr, \"# Error: Cannot read file %s.\\n\", options.levels_file);\n exit(0);\n }\n buf[0]='\\0'; // clear up buf\n }\n fclose(fp);\n \n // read sample_info\n if(dnest_flag_sample_info == 0) //no need to recalculate\n {\n fp = fopen(options.sample_info_file, \"r\");\n if(fp == NULL)\n {\n fprintf(stderr, \"# Error: Cannot open file %s.\\n\", options.sample_info_file);\n exit(0);\n }\n fgets(buf, BUF_MAX_LENGTH, fp);\n for(i=0; i < num_samples; i++)\n {\n if(feof(fp) != 0)\n {\n fprintf(stderr, \"# Error: file %s ends at %d.\\n\", options.sample_info_file, i);\n exit(0);\n }\n fgets(buf, BUF_MAX_LENGTH, fp);\n if(sscanf(buf, \"%lf %lf %lf\", &sample_info[i][0], &sample_info[i][1], &sample_info[i][2]) < 3)\n {\n fprintf(stderr, \"# Error: Cannot read file %s.\\n\", options.sample_info_file);\n exit(0);\n }\n buf[0]='\\0'; // clear buf\n\n /* reset level assignment for levels larger than the maximum level numbers */\n if(sample_info[i][0] > num_levels -1)\n sample_info[i][0] = num_levels - 1;\n }\n fclose(fp);\n }\n else //sample_info file doest not exist, need to recalculate.\n {\n fp = fopen(options.sample_info_file, \"w\");\n if(fp == NULL)\n {\n fprintf(stderr, \"# Error: Cannot open file %s.\\n\", options.sample_info_file);\n exit(0);\n }\n printf(\"# Dnest starts to recalculate the sample info.\\n\");\n fprintf(fp, \"# level assignment, log likelihood, tiebreaker, ID.\\n\");\n\n //read sample\n fp_sample = fopen(options.sample_file, \"r\");\n if(fp_sample == NULL)\n {\n fprintf(stderr, \"# Error: Cannot open file %s.\\n\", options.sample_file);\n exit(0);\n }\n fgets(buf, BUF_MAX_LENGTH, fp_sample);\n\n for(i=0; i < num_samples; i++)\n {\n read_particle(fp_sample, (void *)psample);\n\n sample_info[i][1] = log_likelihoods_cal_initial((void *)psample, dnest_arg);\n sample_info[i][2] = dnest_rand();\n\n for(j=0; j=0) )\n {\n j--;\n }*/\n\n sample_info[i][0] = (double)dnest_rand_int(j); // randomly assign a level [0, j-1]\n\n fprintf(fp, \"%d %e %f %d\\n\", (int)sample_info[i][0], sample_info[i][1], sample_info[i][2], 1);\n }\n fclose(fp);\n fclose(fp_sample);\n }\n //tempering with a temperature\n for(i=0; i levels_orig[j][1] )\n sandwhich[i] = j;\n }\n //printf(\"%f %d\\n\", logl[i], sandwhich[i]);\n }\n \n double *logx_samples, *logp_samples, *logP_samples;\n double logx_min, logx_max, Umin, U;\n int num_samples_thisLevel;\n double *logx_samples_thisLevel;\n SampleType *logl_samples_thisLevel;\n \n double left, right;\n \n logx_samples = malloc(num_samples * sizeof(double));\n logp_samples = malloc(num_samples * sizeof(double));\n logP_samples = malloc(num_samples * sizeof(double));\n \n logx_samples_thisLevel = malloc(num_samples * sizeof(double));\n logl_samples_thisLevel = malloc(num_samples * sizeof(SampleType));\n \n for(i=0; ilogl > b->logl)\n return true;\n if( a->logl == b->logl && a->tiebreaker > b->tiebreaker)\n return true;\n \n return false;\n}\n", "meta": {"hexsha": "679934e06db28fb5048975237b2fe0455469db9c", "size": 12456, "ext": "c", "lang": "C", "max_stars_repo_path": "src/pycali/cdnest/dnestpostprocess.c", "max_stars_repo_name": "LiyrAstroph/PyCALI", "max_stars_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-14T01:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T09:23:59.000Z", "max_issues_repo_path": "src/pycali/cdnest/dnestpostprocess.c", "max_issues_repo_name": "LiyrAstroph/pyCALI", "max_issues_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pycali/cdnest/dnestpostprocess.c", "max_forks_repo_name": "LiyrAstroph/pyCALI", "max_forks_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-05T02:01:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-06T11:26:06.000Z", "avg_line_length": 26.9028077754, "max_line_length": 157, "alphanum_fraction": 0.621226718, "num_tokens": 3737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.40050138635914245}}