{"text": "// Copyright 2012 Jesse Windle - jesse.windle@gmail.com\r\n\r\n// This program is free software: you can redistribute it and/or\r\n// modify it under the terms of the GNU General Public License as\r\n// published by the Free Software Foundation, either version 3 of the\r\n// License, or (at your option) any later version.\r\n\r\n// This program is distributed in the hope that it will be useful, but\r\n// WITHOUT ANY WARRANTY; without even the implied warranty of\r\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n// 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\r\n This class wraps GSL's random number generator and random\r\n distribution functions into a class. We use the Mersenne Twister\r\n for random number generation since it has a large period, which is\r\n what we want for MCMC simulation.\r\n\r\n When compiling include -lgsl -lcblas -llapack .\r\n\r\n*********************************************************************/\r\n\r\n#ifndef __BASICRNG__\r\n#define __BASICRNG__\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing std::string;\r\nusing std::ofstream;\r\nusing std::ifstream;\r\n\r\n//////////////////////////////////////////////////////////////////////\r\n\t\t\t // RNG //\r\n//////////////////////////////////////////////////////////////////////\r\n\r\nclass BasicRNG {\r\n\r\n protected:\r\n\r\n gsl_rng * r;\r\n\r\n public:\r\n\r\n // Constructors and destructors.\r\n BasicRNG(unsigned long seed);\r\n\r\n virtual ~BasicRNG()\r\n { gsl_rng_free (r); }\r\n\r\n // Assignment=\r\n BasicRNG& operator=(const BasicRNG& rng);\r\n\r\n // Read / Write / Set\r\n bool read (const string& filename);\r\n bool write(const string& filename);\r\n void set(unsigned long seed);\r\n\r\n // Get rng -- be careful. Needed for other random variates.\r\n gsl_rng* getrng() { return r; }\r\n\r\n // Random variates.\r\n double unif (); // Uniform\r\n double expon_mean(double mean); // Exponential\r\n double expon_rate(double rate); // Exponential\r\n double chisq (double df); // Chisq\r\n double norm (double sd); // Normal\r\n double norm (double mean , double sd); // Normal\r\n double gamma_scale (double shape, double scale); // Gamma_Scale\r\n double gamma_rate (double shape, double rate); // Gamma_Rate\r\n double igamma(double shape, double scale); // Inv-Gamma\r\n double flat (double a=0 , double b=1 ); // Flat\r\n double beta (double a=1.0, double b=1.0); // Beta\r\n\r\n int bern (double p); // Bernoulli\r\n\r\n // CDF\r\n static double p_norm (double x, int use_log=0);\r\n static double p_gamma_rate(double x, double shape, double rate, int use_log=0);\r\n\r\n // Density\r\n static double d_beta(double x, double a, double b);\r\n\r\n // Utility\r\n static double Gamma (double x, int use_log=0);\r\n\r\n}; // BasicRNG\r\n\r\n#endif\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n\t\t\t\t // APPENDIX //\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n// If you make everything inline within the same translation unit then that\r\n// function will not be callable from anohter translation unit. You can see\r\n// that the function is missing by using the nm command.\r\n", "meta": {"hexsha": "7f4e4d2325ee598eba308e62c0838fc9f64856cb", "size": 3611, "ext": "h", "lang": "C", "max_stars_repo_path": "src/polyagamma/GRNG.h", "max_stars_repo_name": "TeoGiane/SPMIX", "max_stars_repo_head_hexsha": "d63dff8af7523fc1e8e11d2c2906daa16aaff4dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-22T09:35:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T09:35:09.000Z", "max_issues_repo_path": "src/polyagamma/GRNG.h", "max_issues_repo_name": "TeoGiane/SPMIX", "max_issues_repo_head_hexsha": "d63dff8af7523fc1e8e11d2c2906daa16aaff4dc", "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/polyagamma/GRNG.h", "max_forks_repo_name": "TeoGiane/SPMIX", "max_forks_repo_head_hexsha": "d63dff8af7523fc1e8e11d2c2906daa16aaff4dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-18T21:31:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-18T21:31:01.000Z", "avg_line_length": 32.2410714286, "max_line_length": 82, "alphanum_fraction": 0.5768485184, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.10230471199815194, "lm_q1q2_score": 0.04597498404300801}}
{"text": "/*\n * specialfunctionsmodule.h\n *\n * This file is part of NEST.\n *\n * Copyright (C) 2004 The NEST Initiative\n *\n * NEST 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 * NEST 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 NEST. If not, see .\n *\n */\n\n#ifndef SPECIALFUNCTIONSMODULE_H\n#define SPECIALFUNCTIONSMODULE_H\n/*\n SLI Module implementing functions from the GNU Science Library.\n The GSL is available from sources.redhat.com/gsl.\n*/\n\n/*\n NOTE: Special functions are available only if the GSL is installed.\n If no GSL is available, calling special functions will result\n in a SLI error message. HEP 2002-09-19.\n*/\n\n// Generated includes:\n#include \"config.h\"\n\n// Includes from sli:\n#include \"slifunction.h\"\n#include \"slimodule.h\"\n\n#ifdef HAVE_GSL\n// External include:\n#include \n#endif\n\n// NOTE: all gsl headers are included in specialfunctionsmodule.cc\n\nclass SpecialFunctionsModule : public SLIModule\n{\n\n // Part 1: Methods pertaining to the module ----------------------\n\npublic:\n SpecialFunctionsModule( void ){};\n // ~SpecialFunctionsModule(void);\n\n // The Module is registered by a call to this Function:\n void init( SLIInterpreter* );\n\n // This function will return the name of our module:\n const std::string name( void ) const;\n\n\n // Part 2: Classes for the implemented functions -----------------\n\n\npublic:\n /**\n * Classes which implement the GSL Funktions.\n * These must be public, since we want to export\n * objects of these.\n */\n class GammaIncFunction : public SLIFunction\n {\n public:\n GammaIncFunction()\n {\n }\n void execute( SLIInterpreter* ) const;\n };\n class LambertW0Function : public SLIFunction\n {\n public:\n LambertW0Function()\n {\n }\n void execute( SLIInterpreter* ) const;\n };\n class LambertWm1Function : public SLIFunction\n {\n public:\n LambertWm1Function()\n {\n }\n void execute( SLIInterpreter* ) const;\n };\n\n class ErfFunction : public SLIFunction\n {\n public:\n ErfFunction()\n {\n }\n void execute( SLIInterpreter* ) const;\n };\n\n class ErfcFunction : public SLIFunction\n {\n public:\n ErfcFunction()\n {\n }\n void execute( SLIInterpreter* ) const;\n };\n\n class GaussDiskConvFunction : public SLIFunction\n {\n public:\n void execute( SLIInterpreter* ) const;\n\n // need constructor and destructor to set up integration workspace\n GaussDiskConvFunction( void );\n ~GaussDiskConvFunction( void );\n\n private:\n // quadrature parameters, see GSL Reference\n static const int MAX_QUAD_SIZE;\n static const double QUAD_ERR_LIM;\n static const double QUAD_ERR_SCALE;\n\n// integration workspace\n#ifdef HAVE_GSL\n gsl_integration_workspace* w_;\n\n /**\n * Integrand function.\n * @note This function must be static with C linkage so that it can\n * be passed to the GSL. Alternatively, one could define it\n * outside the class.\n */\n static double f_( double, void* );\n static gsl_function F_; // GSL wrapper struct for it\n#endif\n };\n\n // Part 3: One instatiation of each new function class -----------\n\npublic:\n const GammaIncFunction gammaincfunction;\n const LambertW0Function lambertw0function;\n const LambertWm1Function lambertwm1function;\n const ErfFunction erffunction;\n const ErfcFunction erfcfunction;\n const GaussDiskConvFunction gaussdiskconvfunction;\n\n // Part 3b: Internal variables\nprivate:\n};\n\n\n// Part 4: Documentation for all functions -------------------------\n\n/* BeginDocumentation\n\nName: Gammainc - incomplete gamma function\n\nSynopsis: x a Gammainc -> result\n\nDescription: Computes the incomplete Gamma function\n int(t^(a-1)*exp(-t), t=0..x) / Gamma(a)\n\nParameters: x (double): upper limit of integration\n a (double): order of Gamma function\n\nExamples: 2.2 1.5 Gammainc -> 0.778615\n\nAuthor: H E Plesser\n\nFirstVersion: 2001-07-26\n\nRemarks: This is the incomplete Gamma function P(a,x) defined as no. 6.5.1\n in Abramowitz&Stegun. Requires the GSL.\n\nReferences: http://sources.redhat.com/gsl/ref\n*/\n\n/* BeginDocumentation\n\nName: Erf - error function\n\nSynopsis: x Erf -> result\n\nDescription: Computes the error function\n erf(x) = 2/sqrt(pi) int_0^x dt exp(-t^2)\n\nParameters: x (double): error function argument\n\nExamples: 0.5 erf -> 0.5205\n\nAuthor: H E Plesser\n\nFirstVersion: 2001-07-30\n\nRemarks: Requires the GSL.\n\nReferences: http://sources.redhat.com/gsl/ref\n\nSeeAlso: Erfc\n*/\n\n/* BeginDocumentation\n\nName: Erfc - complementary error function\n\nSynopsis: x Erfc -> result\n\nDescription: Computes the error function\n erfc(x) = 1 - erf(x) = 2/sqrt(pi) int_x^inf dt exp(-t^2)\n\nParameters: x (double): error function argument\n\nExamples: 0.5 erfc -> 0.4795\n\nAuthor: H E Plesser\n\nFirstVersion: 2001-07-30\n\nRemarks: Requires the GSL.\n\nReferences: http://sources.redhat.com/gsl/ref\n\nSeeAlso: Erf\n*/\n\n/* BeginDocumentation\n\nName:GaussDiskConv - Convolution of a Gaussian with an excentric disk\n\nSynopsis:R r0 GaussDiskConv -> result\n\nDescription:Computes the convolution of an excentric normalized Gaussian\nwith a disk\n\n C[R, r0] = IInt[ disk(rvec; R) * Gauss(rvec - r_0vec) d^2rvec ]\n = 2 Int[ r Exp[-r0^2-r^2] I_0[2 r r_0] dr, r=0..R]\n\nParameters:R radius of the disk, centered at origin\nr0 distance of Gaussian center from origin\n\nExamples:SLI ] 3.2 2.3 GaussDiskConv =\n0.873191\n\nAuthor:H E Plesser\n\nFirstVersion: 2002-07-12\n\nRemarks:This integral is needed to compute the response of a DOG model to\n excentric light spots, see [1]. For technicalities, see [2]. Requires GSL.\n\nReferences: [1] G. T. Einevoll and P. Heggelund, Vis Neurosci 17:871-885 (2000).\n [2] Hans E. Plesser, Convolution of an Excentric Gaussian with a Disk,\n Technical Report, arken.nlh.no/~itfhep, 2002\n\n*/\n\n#endif\n", "meta": {"hexsha": "d1bc798c4aaa9d2f2a616a101dcd5ea63a0c6cd8", "size": 6323, "ext": "h", "lang": "C", "max_stars_repo_path": "NEST-14.0-FPGA/sli/specialfunctionsmodule.h", "max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z", "max_issues_repo_path": "NEST-14.0-FPGA/sli/specialfunctionsmodule.h", "max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster", "max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z", "max_forks_repo_path": "NEST-14.0-FPGA/sli/specialfunctionsmodule.h", "max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z", "avg_line_length": 23.5055762082, "max_line_length": 80, "alphanum_fraction": 0.6925510043, "num_tokens": 1682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.08389037953940537, "lm_q1q2_score": 0.03965359625569376}}
{"text": "/* bcls.c\n $Revision: 282 $ $Date: 2006-12-17 17:38:00 -0800 (Sun, 17 Dec 2006) $\n\n ---------------------------------------------------------------------\n This file is part of BCLS (Bound-Constrained Least Squares).\n\n Copyright (C) 2006 Michael P. Friedlander, Department of Computer\n Science, University of British Columbia, Canada. All rights\n reserved. E-mail: .\n\n BCLS is free software; you can redistribute it and/or modify it\n under the terms of the GNU Lesser General Public License as\n published by the Free Software Foundation; either version 2.1 of the\n License, or (at your option) any later version.\n\n BCLS is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General\n Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with BCLS; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n ---------------------------------------------------------------------\n*/\n/*!\n \\file\n BCLS user-callable library routines.\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"bcls.h\"\n#include \"bclib.h\"\n#include \"bcsolver.h\"\n#include \"bcversion.h\"\n\n/*!\n\n \\brief Malloc wrapper. Private to this file.\n\n Pointer to the newly allocated memory,\n or NULL if malloc returned an eror.\n \n \\param[in] len Number of elements needed\n \\param[in] size Memory needed for each element.\n \\param[in] who Short character description of the memory needed.\n \n \\return Pointer to the newly allocated memory.\n\n*/\nstatic void *\nxmalloc (int len, size_t size, char * who)\n{\n register void *value = malloc(len * size);\n if (value == NULL)\n\tfprintf( stderr, \"Not enough memory to allocate %s.\\n\", who );\n return value;\n}\n\n/*!\n\n \\brief Create a BCLS problem instance.\n\n This routine create a BCLS problem. It *must* be called before any\n other BCLS routine. It will create and initialize a new BCLS\n problem with enough space to accomodate the specified problem. The\n problem is then initialized using bcls_init_prob.\n\n In order to re-initialize the BCLS problem instance, but not\n deallocate memory that's already sufficient for an equal or smaller\n size problem, use bcls_init_prob.\n\n \\param[in] mmax Maximum number of rows in any A.\n \\param[in] nmax Maximum number of columns in any A.\n\n \\return Return a pointer to a new BCLS problem. If the return is\n NULL, then the initialization failed.\n\n*/\nBCLS *\nbcls_create_prob( int mmax, int nmax )\n{\n int mnmax = imax( nmax, mmax );\n\n assert( mmax > 0 && nmax > 0 );\n \n // Allocate the problem.\n BCLS *ls = (BCLS *)xmalloc(1, sizeof(BCLS), \"ls\" );\n\n // Check if the problem has been successfully allocated.\n if (ls == NULL) {\n\tfprintf( stderr, \"XXX Could not allocate a BCLS problem.\\n\");\n\treturn ls;\n }\n\n // -----------------------------------------------------------------\n // Allocate workspace vectors large enough to accomdate the problem.\n // -----------------------------------------------------------------\n\n // Record the maximum alloted workspace.\n ls->mmax = mmax;\n ls->nmax = nmax;\n\n // Residual: r(m+n).\n ls->r = (double *)xmalloc( mmax+nmax, sizeof(double), \"r\" );\n if (ls->r == NULL) goto error;\n\n // Gradient: g(n).\n ls->g = (double *)xmalloc( nmax, sizeof(double), \"g\" );\n if (ls->g == NULL) goto error;\n\n // Search direction, full space: dx(n).\n ls->dx = (double *)xmalloc( nmax, sizeof(double), \"dx\" );\n if (ls->dx == NULL) goto error;\n\n // Search direction, subspace: dxFree(n).\n ls->dxFree = (double *)xmalloc( nmax, sizeof(double), \"dxFree\" );\n if (ls->dxFree == NULL) goto error;\n\n // Step to each breakpoint: aBreak(n).\n ls->aBreak = (double *)xmalloc( nmax, sizeof(double), \"aBreak\" );\n if (ls->aBreak == NULL) goto error;\n\n // Indices of each breakpoint: iBreak(n).\n ls->iBreak = (int *)xmalloc( nmax, sizeof(int), \"iBreak\" );\n if (ls->iBreak == NULL) goto error;\n\n // Variable indices: ix(n).\n ls->ix = (int *)xmalloc( nmax, sizeof(int), \"ix\" );\n if (ls->ix == NULL) goto error;\n\n // Workspace: wrk_v( max(n, m) ).\n ls->wrk_u = (double *)xmalloc( mnmax, sizeof(double), \"wrk_u\" );\n if (ls->wrk_u == NULL) goto error;\n\n // Workspace: wrk_v( max(n, m) ).\n ls->wrk_v = (double *)xmalloc( mnmax, sizeof(double), \"wrk_v\" );\n if (ls->wrk_v == NULL) goto error;\n\n // Workspace: wrk_w( max(n, m) ).\n ls->wrk_w = (double *)xmalloc( mnmax, sizeof(double), \"wrk_w\" );\n if (ls->wrk_w == NULL) goto error;\n\n // -----------------------------------------------------------------\n // Initialize this new problem instance.\n // -----------------------------------------------------------------\n bcls_init_prob( ls );\n\n // -----------------------------------------------------------------\n // Exits.\n // -----------------------------------------------------------------\n\n // Successfull exit.\n return ls;\n\n error:\n // Unsuccessful exit.\n bcls_free_prob( ls );\n return ls;\n}\n\n/*!\n\n \\brief Initialize a BCLS problem.\n \n Initialize a BCLS problem. You can call this routine to \"reset\" a\n BCLS problem, i.e., reset all parameter values. Note that it is\n automatically called by bcls_create_prob.\n\n \\param[in,out] ls BCLS problem context.\n\n*/\nvoid\nbcls_init_prob( BCLS *ls )\n{\n // Some quick error checking.\n assert( ls->mmax > 0 && ls->nmax > 0 );\n\n // Check if the problem has been successfully allocated.\n if (ls == NULL) {\n\tfprintf( stderr, \"XXX The BCLS problem is NULL.\\n\");\n\treturn;\n }\n \n // Initialize the problem structure.\n ls->print_info = NULL;\n ls->print_hook = NULL;\n ls->fault_info = NULL;\n ls->fault_hook = NULL;\n ls->Aprod = NULL;\n ls->Usolve = NULL;\n ls->CallBack = NULL;\n ls->UsrWrk = NULL;\n ls->anorm = NULL;\n ls->print_level = 1;\n ls->proj_search = BCLS_PROJ_SEARCH_EXACT;\n ls->newton_step = BCLS_NEWTON_STEP_LSQR;\n ls->minor_file = NULL;\n ls->itnMaj = 0;\n ls->itnMajLim = 5 * (ls->nmax);\n ls->itnMin = 0;\n ls->itnMinLim = 10 * (ls->nmax);\n ls->nAprodT = 0;\n ls->nAprodF = 0;\n ls->nAprod1 = 0;\n ls->nUsolve = 0;\n ls->m = 0;\n ls->n = 0;\n ls->unconstrained = 0;\n ls->damp = 0.0;\n ls->damp_min = 1.0e-4;\n ls->exit = BCLS_EXIT_UNDEF;\n ls->soln_rNorm = -1.0;\n ls->soln_dInf = 0.0;\n ls->soln_jInf = -1;\n ls->soln_stat = BCLS_SOLN_UNDEF;\n ls->optTol = 1.0e-6;\n ls->conlim = 1.0 / ( 10.0 * sqrt( DBL_EPSILON ) );\n ls->mu = 1.0e-2;\n ls->backtrack = 1.0e-1;\n ls->backtrack_limit = 10;\n\n // Initialize timers.\n bcls_timer( &(ls->stopwatch[BCLS_TIMER_TOTAL] ), BCLS_TIMER_INIT );\n ls->stopwatch[BCLS_TIMER_TOTAL].name = \"Total time\";\n\n bcls_timer( &(ls->stopwatch[BCLS_TIMER_APROD] ), BCLS_TIMER_INIT );\n ls->stopwatch[BCLS_TIMER_APROD].name = \"Total time for Aprod\";\n\n bcls_timer( &(ls->stopwatch[BCLS_TIMER_USOLVE] ), BCLS_TIMER_INIT );\n ls->stopwatch[BCLS_TIMER_USOLVE].name = \"Total time for Usolve\";\n\n bcls_timer( &(ls->stopwatch[BCLS_TIMER_LSQR] ), BCLS_TIMER_INIT );\n ls->stopwatch[BCLS_TIMER_LSQR].name = \"Total time for LSQR\";\n\n // Initialize constants.\n ls->eps = DBL_EPSILON;\n ls->eps2 = pow( DBL_EPSILON, 0.50 );\n ls->eps3 = pow( DBL_EPSILON, 0.75 );\n ls->epsx = ls->eps3;\n ls->epsfixed = DBL_EPSILON;\n ls->BigNum = BCLS_INFINITY;\n\n return;\n}\n\n/*!\n\n \\brief Free and reinitialize all resources in an existing BCLS problem.\n\n \\return\n - 0: no errors\n - 1: the BCLS problem is NULL (ie, does not exist).\n\n*/\nint\nbcls_free_prob( BCLS *ls )\n{\n // Report an error if it's already NULL.\n if (ls == NULL) return 1;\n\n // Deallocate the workspace.\n assert( ls->r != NULL ); free( ls->r );\n assert( ls->g != NULL ); free( ls->g );\n assert( ls->dx != NULL ); free( ls->dx );\n assert( ls->dxFree != NULL ); free( ls->dxFree );\n assert( ls->aBreak != NULL ); free( ls->aBreak );\n assert( ls->iBreak != NULL ); free( ls->iBreak );\n assert( ls->ix != NULL ); free( ls->ix );\n assert( ls->wrk_u != NULL ); free( ls->wrk_u );\n assert( ls->wrk_v != NULL ); free( ls->wrk_v );\n assert( ls->wrk_w != NULL ); free( ls->wrk_w );\n \n // Deallocate the BCLS problem.\n free( ls );\n \n return 0;\n}\n\n/*!\n\n \n \\brief Install a print-hook routine.\n\n This routine installs a user-defined print-hook routine.\n \n The parameter info is a transit pointer passed to the hook routine.\n \n The parameter hook is an entry point to the user-defined print-hook\n routine. This routine is called by the routine \"print\" every time an\n informative message should be output. The routine \"print\" passes to\n the hook routine the transit pointer info and the character string\n msg, which contains the message. If the hook routine returns zero,\n the routine print prints the message in an usual way. Otherwise, if\n the hook routine returns non-zero, the message is not printed.\n \n In order to uninstall the hook routine the parameter hook should be\n specified as NULL (in this case the parameter info is ignored).\n\n \\param[in,out] ls BCLS problem context.\n \\param[in] info Transit pointer passed to the hook routine.\n \\param[in] hook Pointer to the print-hook routine.\n\n*/\nvoid\nbcls_set_print_hook( BCLS *ls,\n\t\t void *info,\n\t\t int (*hook)(void *info, char *msg))\n{\n ls->print_info = info;\n ls->print_hook = hook;\n return;\n}\n\n/*!\n\n \\brief Install a fault-hook routine.\n\n This routine installs a user-defined fault-hook routine.\n\n The parameter info is a transit pointer passed to the hook routine.\n\n The parameter \"hook\" is an entry point to the user-defined\n fault-hook routine. This routine is called by the routine\n \"bcls_fault\" every time an error message should be output. The\n routine \"bcls_fault\" passes to the hook routine the transit pointer\n info and the character string msg, which contains the message. If\n the hook routine returns zero, the routine print prints the message\n in an usual way. Otherwise, if the hook routine returns non-zero,\n the message is not printed.\n\n In order to uninstall the hook routine the parameter hook should be\n specified as NULL (in this case the parameter info is ignored).\n\n \\param[in,out] ls BCLS problem context.\n \\param[in] info Transit pointer passed to the hook routine.\n \\param[in] hook Pointer to the fault-hook routine.\n\n*/\nvoid\nbcls_set_fault_hook( BCLS *ls,\n\t\t void *info,\n\t\t int (*hook)(void *info, char *msg))\n{\n ls->fault_info = info;\n ls->fault_hook = hook;\n return;\n}\n\n/*!\n\n \\brief Give BCLS access to set of column weights.\n\n Define a set of column weights. BCLS will use these to scale the\n steepest-descent steps.\n\n \\param[in,out] ls BCLS problem context.\n \\param[in] anorm Array of columns norms of A.\n\n*/\nvoid\nbcls_set_anorm( BCLS *ls,\n double anorm[] )\n{\n ls->anorm = anorm;\n return;\n}\n\n/*!\n\n \\brief Install a user-defined preconditioning routine.\n \n Replace each subproblem\n \\f[\n \\def\\minimize{\\displaystyle\\mathop{\\hbox{minimize}}}\n \\minimize_x \\| Ax - b \\|\n \\f]\n with\n \\f[\n \\def\\minimize{\\displaystyle\\mathop{\\hbox{minimize}}}\n \\minimize_y \\| AU^{-1}y - b \\|\n \\quad\\mbox{with}\\quad\n Ux = y.\n \\f]\n\n \\param[in,out] ls BCLS problem context.\n \\param[in] Usolve Pointer to the user's preconditioning routine.\n\n*/\nvoid\nbcls_set_usolve( BCLS *ls,\n int (*Usolve)( int mode, int m, int n, int nix,\n int ix[], double v[], double w[],\n void *UsrWrk ) )\n{\n assert( Usolve != NULL );\n ls->Usolve = Usolve;\n return;\n}\n\n\n/*!\n\n \\brief Compute the column norms of A.\n\n Compute the columns norms of A. Each column of A is generated by\n multiplying A by a unit vector. The two-norm squared of each\n column is stored in aprod.\n \n This routine must be called *after* bcls_create_prob. (As with any\n other BCLS routine.)\n\n \\param[in] ls BCLS problem context.\n \\param[in] m Number of rows in A.\n \\param[in] n Number of columns in A.\n \\param[in] Aprod User's matrix-product routine.\n \\param[in,out] UsrWrk Pointer to user's workspace (could be NULL).\n \\param[out] anorm Vector of column norms of A.\n \n \\return Returns any error codes returned by the user's aprod\n routine.\n\n*/\nint\nbcls_compute_anorm( BCLS *ls, int n, int m,\n int (*Aprod)\n ( int mode, int m, int n, int nix,\n int ix[], double x[], double y[], void *UsrWrk ),\n void *UsrWrk,\n double anorm[] )\n{ \n // Make sure that the problem instance has been created.\n assert( ls != NULL );\n assert( anorm != NULL );\n\n int j;\n int err;\n const int mode = 1; // Always: aj = A*ej.\n const int nix = 1; // Only one column is ever needed.\n int *ix = ls->ix;\n double *e = ls->wrk_u;\n double *aj = ls->wrk_v;\n\n bcls_dload( n, 1.0, e, 1 );\n \n for (j = 0; j < n; j++) {\n\n // Multiply A times the jth unit vector.\n ix[0] = j;\n \n // aj <- A * ej.\n err = Aprod( mode, m, n, nix, ix, e, aj, UsrWrk );\n\n // Exit if Aprod returned an error.\n if (err) break;\n\n // Compute the norm of aj and store it in anorm.\n anorm[j] = cblas_dnrm2( m, aj, 1 );\n\n // Make sure that the column norm is too small.\n anorm[j] = fmax( BCLS_MIN_COLUMN_NORM, anorm[j] );\n }\n\n return err;\n}\n\n/*!\n\n \\brief Load the problem into the BCLS data structure.\n\n The routiens loads the complete problem description into a BCLS\n problem instance. No work is really being done: only the various\n structure elements are being set to point to the right places.\n\n \\param[in,out] ls BCLS problem context.\n \\param[in] m Number of rows in A. Note: m <= mmax.\n \\param[in] n Number of columns in A. Note: n <= nmax.\n \\param[in] Aprod Hook to user's matrix-vector product routine.\n \\param[in,out] UsrWrk Transit pointer passed directly to Aprod/Usolve.\n \\param[in] damp Regularization parameter.\n \\param[in,out] x The starting point.\n \\param[in] b The RHS vector.\n \\param[in] c Defines a linear term (set to NULL if one doesn't exist).\n \\param[in] bl Lower bounds on x.\n \\param[in] bu Upper bounds on x.\n\n*/\nvoid\nbcls_set_problem_data( BCLS *ls, int m, int n,\n\t\t int (*Aprod)( int mode, int m, int n, int nix,\n\t\t\t\t int ix[], double x[], double y[],\n\t\t\t\t void *UsrWrk ),\n\t\t void *UsrWrk, double damp,\n\t\t double x[], double b[], double c[],\n\t\t double bl[], double bu[] )\n{\n assert( m <= ls->mmax );\n assert( n <= ls->nmax );\n\n assert( Aprod != NULL ); ls->Aprod = Aprod;\n assert( m >= 0 ); ls->m = m;\n assert( n >= 0 ); ls->n = n;\n ls->UsrWrk = UsrWrk;\n assert( damp >= 0.0 ); ls->damp = damp;\n assert( x != NULL ); ls->x = x;\n assert( b != NULL ); ls->b = b;\n ls->c = c;\n assert( bl != NULL ); ls->bl = bl;\n assert( bu != NULL ); ls->bu = bu;\n\n return;\n}\n\n/*!\n\n \\brief Return an exit message.\n\n \\param[in] flag The code of the error.\n\n \\return Error messsage.\n\n*/\nchar *\nbcls_exit_msg( int flag )\n{\n char *msg;\n\n if (flag==BCLS_EXIT_CNVGD) msg=\"Optimal solution found\";\n else if (flag==BCLS_EXIT_MAJOR) msg=\"Too many major iterations\";\n else if (flag==BCLS_EXIT_MINOR) msg=\"Too many minor iterations\";\n else if (flag==BCLS_EXIT_UNBND) msg=\"Found direction of infinite descent\";\n else if (flag==BCLS_EXIT_INFEA) msg=\"Bounds are inconsistent\";\n else if (flag==BCLS_EXIT_APROD) msg=\"Aprod requested immediate exit\";\n else if (flag==BCLS_EXIT_USOLVE) msg=\"Usolve requested immediate exit\";\n else if (flag==BCLS_EXIT_CALLBK) msg=\"CallBack requested immediate exit\";\n else msg=\"Undefined exit\";\n\n return msg;\n}\n\n/*!\n\n \\brief Solve the current problem instance.\n\n \\return\n - #BCLS_EXIT_CNVGD (0) - Successful exit. Found an optimal solution.\n - #BCLS_EXIT_MAJOR - Too many major iterations.\n - #BCLS_EXIT_MINOR - Too many inner iterations.\n - #BCLS_EXIT_UNBND - Found direction of infinite descent.\n - #BCLS_EXIT_INFEA - Bounds are inconsistent.\n - #BCLS_EXIT_APROD - Aprod requested immediate exit.\n - #BCLS_EXIT_USOLVE - Usolve requested immediate exit.\n\n*/\nint\nbcls_solve_prob( BCLS *ls )\n{\n int err;\n int jpInf;\n const int preconditioning = ls->Usolve != NULL;\n double pInf, timeTot;\n double bNorm; // Norm of the RHS (or 1.0, which ever is bigger).\n BCLS_timer watch;\n\n // Print the banner.\n //PRINT1(\" ----------------------------------------------------\\n\");\n //PRINT1(\" BCLS -- Bound-Constrained Least Squares, Version %s\\n\",\n // bcls_version_info() );\n //PRINT1(\" Compiled on %s\\n\", bcls_compilation_info() );\n //PRINT1(\" ----------------------------------------------------\\n\");\n\n // -----------------------------------------------------------------\n // Print parameters and diagnostic information.\n // -----------------------------------------------------------------\n bcls_print_params( ls );\n\n // Examine the bounds and print a summary about them.\n // Also check if the problem is feasible!\n err = bcls_examine_bnds( ls, ls->n, ls->bl, ls->bu );\n if (err) {\n\tls->exit = err;\n goto direct_exit;\n }\n\n // Set the return for longjmp. First call to setjmp returns 0.\n err = setjmp(ls->jmp_env);\n if (err) {\n ls->exit = err;\n goto direct_exit;\n }\n\n // Compute and print some statistics about the column scales.\n bcls_examine_column_scales( ls, ls->anorm );\n\n // Print a log header.\n // PRINT1(\"\\n %5s %5s %9s %9s %11s %9s %7s %7s %7s\\n\",\n //\t \"Major\",\"Minor\",\"Residual\",\"xNorm\",\"Optimal\",\n //\t ls->newton_step == BCLS_NEWTON_STEP_LSQR\n //\t ? \"LSQR\" : \"CGLS\",\n //\t \"nSteps\", \"Free\", \"OptFac\");\n\n // -----------------------------------------------------------------\n // Call the BCLS solver.\n // -----------------------------------------------------------------\n bcls_timer( &(ls->stopwatch[BCLS_TIMER_TOTAL]), BCLS_TIMER_START );\n\n bcls_solver( ls, ls->m, ls->n, &bNorm,\n\t\t ls->x, ls->b, ls->c, ls->bl, ls->bu, ls->r, ls->g,\n\t\t ls->dx, ls->dxFree, ls->ix,\n\t\t ls->aBreak, ls->iBreak, ls->anorm );\n\n bcls_timer( &(ls->stopwatch[BCLS_TIMER_TOTAL]), BCLS_TIMER_STOP );\n\n\n // =================================================================\n // Exits.\n // =================================================================\n direct_exit:\n // -----------------------------------------------------------------\n // Check feasibility and print a solution summary (iterations, etc.)\n // -----------------------------------------------------------------\n bcls_primal_inf( ls->n, ls->x, ls->bl, ls->bu, &pInf, &jpInf );\n\n //PRINT1(\"\\n\");\n // PRINT1(\" BCLS Exit %4d -- %s\\n\",ls->exit, bcls_exit_msg(ls->exit));\n //PRINT1(\"\\n\");\n //PRINT1(\" No. of iterations %8d %7s\", ls->itnMin, \"\");\n //PRINT1(\" Objective value %17.9e\\n\", ls->soln_obj );\n //PRINT1(\" No. of major iterations%8d %7s\", ls->itnMaj, \"\");\n //PRINT1(\" Optimality (%7d) %8.1e\\n\",\n //\t ls->soln_jInf,ls->soln_dInf);\n //PRINT1(\" No. of calls to Aprod %8d\", ls->nAprodT);\n\n //if (ls->proj_search == BCLS_PROJ_SEARCH_EXACT)\n // PRINT1(\" (%5d)\", ls->nAprod1 );\n //else\n // PRINT1(\" %5s \", \"\");\n // PRINT1(\" Norm of RHS %16.1e\\n\", bNorm);\n // if (pInf > ls->eps)\n // PRINT1(\" Feasibility (%7d) %7.1e\\n\", jpInf, pInf);\n //if (preconditioning)\n // PRINT1(\" No. of calls to Usolve %8d\\n\", ls->nUsolve);\n //PRINT1(\"\\n\");\n\n // -----------------------------------------------------------------\n // Print timing statistics.\n // -----------------------------------------------------------------\n //timeTot = fmax(ls->eps,ls->stopwatch[BCLS_TIMER_TOTAL].total);\n\n //watch = ls->stopwatch[BCLS_TIMER_TOTAL];\n //timeTot = fmax(1e-6, watch.total); // Safeguard against timeTot = 0.\n\n //PRINT1(\" %-25s %5.1f (%4.2f) secs\\n\",\n //\t watch.name, watch.total, 1.0 );\n\n //watch = ls->stopwatch[BCLS_TIMER_LSQR];\n //PRINT1(\" %-25s %5.1f (%4.2f) secs\\n\",\n //\t watch.name, watch.total, watch.total / timeTot );\n\n // watch = ls->stopwatch[BCLS_TIMER_APROD];\n //PRINT1(\" %-25s %5.1f (%4.2f) secs\\n\",\n //\t watch.name, watch.total, watch.total / timeTot );\n\n // Only print time for Usolve is user provided this routine.\n //if (preconditioning) {\n // watch = ls->stopwatch[BCLS_TIMER_USOLVE];\n //PRINT1(\" %-25s %5.1f (%4.2f) secs\\n\",\n // watch.name, watch.total, watch.total / timeTot );\n //}\n\n return (ls->exit + err);\n}\n", "meta": {"hexsha": "6c5670b51069f1e2f0f17e9110bf58bf0f353ac1", "size": 21731, "ext": "c", "lang": "C", "max_stars_repo_path": "bcls-0.1/src/bcls.c", "max_stars_repo_name": "echristakopoulou/glslim", "max_stars_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-16T01:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:45:41.000Z", "max_issues_repo_path": "bcls-0.1/src/bcls.c", "max_issues_repo_name": "echristakopoulou/glslim", "max_issues_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "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": "bcls-0.1/src/bcls.c", "max_forks_repo_name": "echristakopoulou/glslim", "max_forks_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T07:46:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T13:00:19.000Z", "avg_line_length": 31.9104258443, "max_line_length": 83, "alphanum_fraction": 0.564171, "num_tokens": 6134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.07696084363512665, "lm_q1q2_score": 0.03817979963826262}}
{"text": "#ifndef ARRAY_H\n#define ARRAY_H\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if CMK_HAS_CBLAS\n#include \n#endif\n\nnamespace CharjArray {\n class Range {\n public:\n int size, start, stop;\n Range() {}\n Range(int size_) : size(size_), start(0), stop(size) {}\n Range(int start_, int stop_) :\n size(stop_ - start_), start(start_), stop(stop_) {\n assert(stop >= start);\n }\n void pup(PUP::er& p) { \n p | size;\n p | start;\n p | stop;\n }\n };\n\n template\n class Domain {\n public:\n Range ranges[dims];\n \n Domain() {}\n\n Domain(Range ranges_[]) {\n for (int i = 0; i < dims; i++) \n\tranges[i] = ranges_[i]; \n }\n\n Domain(Range range) {\n ranges[0] = range;\n }\n\n Domain(Range range1, Range range2) {\n // TODO: fix Charj generator so it uses the array\n ranges[0] = range1;\n ranges[1] = range2;\n }\n\n int size() const {\n int total = 0;\n\n for (int i = 0; i < dims; i++)\n\tif (total == 0)\n\t total = ranges[i].size;\n\telse\n\t total *= ranges[i].size;\n\n return total;\n }\n\n void pup(PUP::er& p) { \n for (int i=0; i\n class RowMajor {\n public:\n static int access(const int i, const Domain &d) {\n return i - d.ranges[0].start;\n }\n static int access(const int i, const int j, const Domain &d) {\n return (i - d.ranges[0].start) * d.ranges[1].size + j -\n d.ranges[1].start;\n }\n // Generic access method, not used right now.\n // static int access(const int *i, const Domain &d) {\n // int off = i[0];\n // int dimoff = 1;\n // for (int j = ndims-1; j > 0; --j) {\n // dimoff *= d.ranges[j].size;\n // off += dimoff * (i[j] - d.ranges[j].start);\n // }\n // return off;\n // }\n };\n\n template\n class ColMajor {\n public:\n static int access(const int i, const Domain &d) {\n return i - d.ranges[0].start;\n }\n static int access(const int i, const int j, const Domain &d) {\n return (j - d.ranges[1].start) * d.ranges[1].size + i -\n d.ranges[0].start;\n }\n };\n\n template >\n class Array {\n private:\n Domain domain;\n type *block;\n int ref_cout;\n bool did_init;\n Array* ref_parent;\n\n public:\n Array(Domain domain_) : ref_parent(0), did_init(false) {\n init(domain_);\n }\n\n Array(type **block_) : did_init(false) {\n block = *block_;\n }\n\n Array(type& block_) : did_init(false) {\n block = &block_;\n }\n\n Array() : ref_parent(0), did_init(false) {\n\n }\n\n Array(Array* parent, Domain domain_)\n : ref_parent(parent), did_init(false) {\n domain = domain_;\n block = parent->block;\n }\n\n void init(Domain &domain_) {\n domain = domain_;\n //if (atype == ROW_MAJOR)\n block = new type[domain.size()];\n //printf(\"Array: allocating memory, size=%d, base pointer=%p\\n\",\n // domain.size(), block);\n did_init = true;\n }\n\n type* raw() { return block; }\n\n ~Array() {\n if (did_init) delete[] block;\n }\n\n /*type* operator[] (const Domain &domain) {\n return block[domain.ranges[0].size];\n }*/\n\n type& operator[] (const int i) {\n return block[atype::access(i, domain)];\n }\n\n const type& operator[] (const int i) const {\n return block[atype::access(i, domain)];\n }\n\n type& access(const int i) {\n return this->operator[](i);\n }\n\n type& access(const int i, const int j) {\n //printf(\"Array: accessing, index (%d,%d), offset=%d, base pointer=%p\\n\",\n //i, j, atype::access(i, j, domain), block);\n return block[atype::access(i, j, domain)];\n }\n\n type& access(const int i, const Range r) {\n Domain<1> d(r);\n //printf(\"Array: accessing subrange, size = %d, range (%d,%d), base pointer=%p\\n\",\n //d.size(), r.start, r.stop, block);\n type* buf = new type[d.size()];\n for (int j = 0; j < d.size(); j++) {\n //printf(\"Array: copying element (%d,%d), base pointer=%p\\n\", i, j, block);\n buf[j] = block[atype::access(i, j, domain)];\n }\n return *buf;\n }\n\n const type& access(const int i, const int j) const {\n return block[atype::access(i, j, domain)];\n }\n\n Array* operator[] (const Domain &domain) {\n return new Array(this, domain);\n }\n\n int size() const {\n return domain.size();\n }\n\n int size(int dim) const {\n return domain.ranges[dim].size;\n }\n\n void pup(PUP::er& p) { \n p | domain;\n if (p.isUnpacking()) {\n block = new type[domain.size()];\n }\n PUParray(p, block, domain.size());\n }\n\n void fill(const type &t) {\n for (int i = 0; i < domain.size(); ++i)\n\tblock[i] = t;\n }\n\n /// Do these arrays have the same shape and contents?\n bool operator==(const Array &rhs) const\n {\n for (int i = 0; i < dims; ++i)\n\tif (this->size(i) != rhs.size(i))\n\t return false;\n\n for (int i = 0; i < this->size(); ++i)\n\tif (this->block[i] != rhs.block[i])\n\t return false;\n\n return true;\n }\n bool operator!=(const Array &rhs) const\n {\n return !(*this == rhs);\n }\n };\n\n /**\n A local Matrix class for various sorts of linear-algebra work.\n\n Indexed from 0, to reflect the C-heritage of Charj.\n */\n template >\n class Matrix : public Array\n {\n public:\n Matrix() { }\n /// A square matrix\n Matrix(unsigned int n) : Array(Domain<2>(n,n)) { }\n\n /// A identity matrix\n static Matrix* ident(int n)\n {\n Matrix *ret = new Matrix(n);\n ret->fill(0);\n\n for (int i = 0; i < n; ++i)\n\tret->access(i,i) = 1;\n\n return ret;\n }\n };\n\n template >\n class Vector : public Array\n {\n public:\n Vector() { }\n Vector(unsigned int n) : Array(Range(n)) { }\n };\n\n /// Compute the inner (dot) product v1^T * v2\n // To compute v1^H * v2, call as dot(v1.C(), v2)\n template\n T dot(const Vector *pv1, const Vector *pv2)\n {\n const Vector &v1 = *pv1, &v2 = *pv2;\n assert(v1.size() == v2.size());\n // XXX: This default initialization worries me some, since it\n // won't necessarily be an additive identity for all T. - Phil\n T ret = T();\n int size = v1.size();\n for (int i = 0; i < size; ++i)\n ret += v1[i] * v2[i];\n return ret;\n }\n#if CMK_HAS_CBLAS\n template <>\n float dot, RowMajor<1> >(const Vector > *pv1,\n\t\t\t\t\t const Vector > *pv2)\n {\n const Vector > &v1 = *pv1, &v2 = *pv2;\n assert(v1.size() == v2.size());\n return cblas_sdot(v1.size(), &(v1[0]), 1, &(v2[0]), 1);\n }\n template <>\n double dot, RowMajor<1> >(const Vector > *pv1,\n\t\t\t\t\t\tconst Vector > *pv2)\n {\n const Vector > &v1 = *pv1, &v2 = *pv2;\n assert(v1.size() == v2.size());\n return cblas_ddot(v1.size(), &(v1[0]), 1, &(v2[0]), 1);\n }\n#endif\n\n /// Computer the 1-norm of the given vector\n template\n T norm1(const Vector *pv)\n {\n const Vector &v = *pv;\n // XXX: See comment about additive identity in dot(), above\n T ret = T();\n int size = v.size();\n for (int i = 0; i < size; ++i)\n ret += v[i];\n return ret;\n }\n\n /// Compute the Euclidean (2) norm of the given vector\n template\n T norm2(const Vector *pv)\n {\n const Vector &v = *pv;\n // XXX: See comment about additive identity in dot(), above\n T ret = T();\n int size = v.size();\n for (int i = 0; i < size; ++i)\n ret += v[i] * v[i];\n return sqrt(ret);\n }\n#if CMK_HAS_CBLAS\n template<>\n float norm2 >(const Vector > *pv)\n {\n const Vector > &v = *pv;\n return cblas_snrm2(v.size(), &(v[0]), 1);\n }\n template<>\n double norm2 >(const Vector > *pv)\n {\n const Vector > &v = *pv;\n return cblas_dnrm2(v.size(), &(v[0]), 1);\n }\n#endif\n\n /// Compute the infinity (max) norm of the given vector\n // Will fail on zero-length vectors\n template\n T normI(const Vector *pv)\n {\n const Vector &v = *pv;\n T ret = v[0];\n int size = v.size();\n for (int i = 1; i < size; ++i)\n ret = max(ret, v[i]);\n return ret;\n }\n\n /// Scale a vector by some constant\n template\n void scale(const T &t, Vector *pv)\n {\n const Vector &v = *pv;\n int size = v.size();\n for (int i = 0; i < size; ++i)\n v[i] = t * v[i];\n }\n#if CMK_HAS_CBLAS\n template<>\n void scale >(const float &t,\n\t\t\t\t\t Vector > *pv)\n {\n Vector > &v = *pv;\n cblas_sscal(v.size(), t, &(v[0]), 1);\n }\n template<>\n void scale >(const double &t,\n\t\t\t\t\t Vector > *pv)\n {\n Vector > &v = *pv;\n cblas_dscal(v.size(), t, &(v[0]), 1);\n }\n#endif\n\n /// Add one vector to a scaled version of another\n template\n void axpy(const T &a, const Vector *px, Vector *py)\n {\n Vector &x = *px;\n const Vector &y = *py;\n int size = x.size();\n assert(size == y.size());\n for (int i = 0; i < size; ++i)\n x[i] = a * x[i] + y[i];\n }\n#if CMK_HAS_CBLAS\n template<>\n void axpy >(const float &a,\n\t\t\t\t\t const Vector > *px,\n\t\t\t\t\t Vector > *py)\n {\n const Vector > &x = *px;\n Vector > &y = *py;\n int size = x.size();\n assert(size == y.size());\n cblas_saxpy(size, a, &(x[0]), 1, &(y[0]), 1);\n }\n template<>\n void axpy >(const double &a,\n\t\t\t\t\t const Vector > *px,\n\t\t\t\t\t Vector > *py)\n {\n const Vector > &x = *px;\n Vector > &y = *py;\n int size = x.size();\n assert(size == y.size());\n cblas_daxpy(size, a, &(x[0]), 1, &(y[0]), 1);\n }\n#endif\n}\n\n#endif\n", "meta": {"hexsha": "f3b248ce11b4b67b29cab17b3abfa0aadd09e74f", "size": 10729, "ext": "h", "lang": "C", "max_stars_repo_path": "NAMD_2.12_Source/charm-6.7.1/src/langs/charj/src/charj/libs/Array.h", "max_stars_repo_name": "scottkwarren/config-db", "max_stars_repo_head_hexsha": "fb5c3da2465e5cff0ad30950493b11d452bd686b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-17T20:07:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-17T20:07:23.000Z", "max_issues_repo_path": "NAMD_2.12_Source/charm-6.7.1/src/langs/charj/src/charj/libs/Array.h", "max_issues_repo_name": "scottkwarren/config-db", "max_issues_repo_head_hexsha": "fb5c3da2465e5cff0ad30950493b11d452bd686b", "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": "NAMD_2.12_Source/charm-6.7.1/src/langs/charj/src/charj/libs/Array.h", "max_forks_repo_name": "scottkwarren/config-db", "max_forks_repo_head_hexsha": "fb5c3da2465e5cff0ad30950493b11d452bd686b", "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.6062052506, "max_line_length": 88, "alphanum_fraction": 0.5543853108, "num_tokens": 3371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.07807816407233609, "lm_q1q2_score": 0.0366023114612971}}
{"text": "// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at\n// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights\n// reserved. See files LICENSE and NOTICE for details.\n//\n// This file is part of CEED, a collection of benchmarks, miniapps, software\n// libraries and APIs for efficient high-order finite element and spectral\n// element discretizations for exascale applications. For more information and\n// source code availability see http://github.com/ceed.\n//\n// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,\n// a collaborative effort of two U.S. Department of Energy organizations (Office\n// of Science and the National Nuclear Security Administration) responsible for\n// the planning and preparation of a capable exascale ecosystem, including\n// software, applications, hardware, advanced system engineering and early\n// testbed platforms, in support of the nation's exascale computing imperative.\n\n// libCEED + PETSc Example: CEED BPs\n//\n// This example demonstrates a simple usage of libCEED with PETSc to solve the\n// CEED BP benchmark problems, see http://ceed.exascaleproject.org/bps.\n//\n// The code uses higher level communication protocols in DMPlex.\n//\n// Build with:\n//\n// make bps [PETSC_DIR=] [CEED_DIR=]\n//\n// Sample runs:\n//\n// ./bps -problem bp1 -degree 3\n// ./bps -problem bp2 -degree 3\n// ./bps -problem bp3 -degree 3\n// ./bps -problem bp4 -degree 3\n// ./bps -problem bp5 -degree 3 -ceed /cpu/self\n// ./bps -problem bp6 -degree 3 -ceed /gpu/cuda\n//\n//TESTARGS -ceed {ceed_resource} -test -problem bp5 -degree 3 -ksp_max_it_clip 15,15\n\n/// @file\n/// CEED BPs example using PETSc with DMPlex\n/// See bpsraw.c for a \"raw\" implementation using a structured grid.\nconst char help[] = \"Solve CEED BPs using PETSc with DMPlex\\n\";\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"bps.h\"\n#include \"include/bpsproblemdata.h\"\n#include \"include/petscmacros.h\"\n#include \"include/petscutils.h\"\n#include \"include/matops.h\"\n#include \"include/structs.h\"\n#include \"include/libceedsetup.h\"\n\n#if PETSC_VERSION_LT(3,12,0)\n#ifdef PETSC_HAVE_CUDA\n#include \n// Note: With PETSc prior to version 3.12.0, providing the source path to\n// include 'cublas_v2.h' will be needed to use 'petsccuda.h'.\n#endif\n#endif\n\n// -----------------------------------------------------------------------------\n// Utilities\n// -----------------------------------------------------------------------------\n\n// Utility function, compute three factors of an integer\nstatic void Split3(PetscInt size, PetscInt m[3], bool reverse) {\n for (PetscInt d=0, size_left=size; d<3; d++) {\n PetscInt try = (PetscInt)PetscCeilReal(PetscPowReal(size_left, 1./(3 - d)));\n while (try * (size_left / try) != size_left) try++;\n m[reverse ? 2-d : d] = try;\n size_left /= try;\n }\n}\n\nstatic int Max3(const PetscInt a[3]) {\n return PetscMax(a[0], PetscMax(a[1], a[2]));\n}\n\nstatic int Min3(const PetscInt a[3]) {\n return PetscMin(a[0], PetscMin(a[1], a[2]));\n}\n\n// -----------------------------------------------------------------------------\n// Parameter structure for running problems\n// -----------------------------------------------------------------------------\ntypedef struct RunParams_ *RunParams;\nstruct RunParams_ {\n MPI_Comm comm;\n PetscBool test_mode, read_mesh, user_l_nodes, write_solution;\n char *filename, *hostname;\n PetscInt local_nodes, degree, q_extra, dim, num_comp_u, *mesh_elem;\n PetscInt ksp_max_it_clip[2];\n PetscMPIInt ranks_per_node;\n BPType bp_choice;\n PetscLogStage solve_stage;\n};\n\n// -----------------------------------------------------------------------------\n// Main body of program, called in a loop for performance benchmarking purposes\n// -----------------------------------------------------------------------------\nstatic PetscErrorCode RunWithDM(RunParams rp, DM dm,\n const char *ceed_resource) {\n PetscErrorCode ierr;\n double my_rt_start, my_rt, rt_min, rt_max;\n PetscInt xl_size, l_size, g_size;\n PetscScalar *r;\n Vec X, X_loc, rhs, rhs_loc;\n Mat mat_O;\n KSP ksp;\n UserO user_O;\n Ceed ceed;\n CeedData ceed_data;\n CeedQFunction qf_error;\n CeedOperator op_error;\n CeedVector rhs_ceed, target;\n VecType vec_type;\n PetscMemType mem_type;\n\n PetscFunctionBeginUser;\n // Set up libCEED\n CeedInit(ceed_resource, &ceed);\n CeedMemType mem_type_backend;\n CeedGetPreferredMemType(ceed, &mem_type_backend);\n\n ierr = DMGetVecType(dm, &vec_type); CHKERRQ(ierr);\n if (!vec_type) { // Not yet set by user -dm_vec_type\n switch (mem_type_backend) {\n case CEED_MEM_HOST: vec_type = VECSTANDARD; break;\n case CEED_MEM_DEVICE: {\n const char *resolved;\n CeedGetResource(ceed, &resolved);\n if (strstr(resolved, \"/gpu/cuda\")) vec_type = VECCUDA;\n else if (strstr(resolved, \"/gpu/hip/occa\"))\n vec_type = VECSTANDARD; // https://github.com/CEED/libCEED/issues/678\n else if (strstr(resolved, \"/gpu/hip\")) vec_type = VECHIP;\n else vec_type = VECSTANDARD;\n }\n }\n ierr = DMSetVecType(dm, vec_type); CHKERRQ(ierr);\n }\n\n // Create global and local solution vectors\n ierr = DMCreateGlobalVector(dm, &X); CHKERRQ(ierr);\n ierr = VecGetLocalSize(X, &l_size); CHKERRQ(ierr);\n ierr = VecGetSize(X, &g_size); CHKERRQ(ierr);\n ierr = DMCreateLocalVector(dm, &X_loc); CHKERRQ(ierr);\n ierr = VecGetSize(X_loc, &xl_size); CHKERRQ(ierr);\n ierr = VecDuplicate(X, &rhs); CHKERRQ(ierr);\n\n // Operator\n ierr = PetscMalloc1(1, &user_O); CHKERRQ(ierr);\n ierr = MatCreateShell(rp->comm, l_size, l_size, g_size, g_size,\n user_O, &mat_O); CHKERRQ(ierr);\n ierr = MatShellSetOperation(mat_O, MATOP_MULT,\n (void(*)(void))MatMult_Ceed); CHKERRQ(ierr);\n ierr = MatShellSetOperation(mat_O, MATOP_GET_DIAGONAL,\n (void(*)(void))MatGetDiag); CHKERRQ(ierr);\n ierr = MatShellSetVecType(mat_O, vec_type); CHKERRQ(ierr);\n\n // Print summary\n if (!rp->test_mode) {\n PetscInt P = rp->degree + 1, Q = P + rp->q_extra;\n\n const char *used_resource;\n CeedGetResource(ceed, &used_resource);\n\n VecType vec_type;\n ierr = VecGetType(X, &vec_type); CHKERRQ(ierr);\n\n PetscInt c_start, c_end;\n ierr = DMPlexGetHeightStratum(dm, 0, &c_start, &c_end); CHKERRQ(ierr);\n PetscMPIInt comm_size;\n ierr = MPI_Comm_size(rp->comm, &comm_size); CHKERRQ(ierr);\n ierr = PetscPrintf(rp->comm,\n \"\\n-- CEED Benchmark Problem %d -- libCEED + PETSc --\\n\"\n \" MPI:\\n\"\n \" Hostname : %s\\n\"\n \" Total ranks : %d\\n\"\n \" Ranks per compute node : %d\\n\"\n \" PETSc:\\n\"\n \" PETSc Vec Type : %s\\n\"\n \" libCEED:\\n\"\n \" libCEED Backend : %s\\n\"\n \" libCEED Backend MemType : %s\\n\"\n \" Mesh:\\n\"\n \" Number of 1D Basis Nodes (P) : %d\\n\"\n \" Number of 1D Quadrature Points (Q) : %d\\n\"\n \" Global nodes : %D\\n\"\n \" Local Elements : %D\\n\"\n \" Owned nodes : %D\\n\"\n \" DoF per node : %D\\n\",\n rp->bp_choice+1, rp->hostname, comm_size,\n rp->ranks_per_node, vec_type, used_resource,\n CeedMemTypes[mem_type_backend],\n P, Q, g_size/rp->num_comp_u, c_end - c_start, l_size/rp->num_comp_u,\n rp->num_comp_u);\n CHKERRQ(ierr);\n }\n\n // Create RHS vector\n ierr = VecDuplicate(X_loc, &rhs_loc); CHKERRQ(ierr);\n ierr = VecZeroEntries(rhs_loc); CHKERRQ(ierr);\n ierr = VecGetArrayAndMemType(rhs_loc, &r, &mem_type); CHKERRQ(ierr);\n CeedVectorCreate(ceed, xl_size, &rhs_ceed);\n CeedVectorSetArray(rhs_ceed, MemTypeP2C(mem_type), CEED_USE_POINTER, r);\n\n ierr = PetscMalloc1(1, &ceed_data); CHKERRQ(ierr);\n ierr = SetupLibceedByDegree(dm, ceed, rp->degree, rp->dim, rp->q_extra,\n rp->dim, rp->num_comp_u, g_size, xl_size, bp_options[rp->bp_choice],\n ceed_data, true, rhs_ceed, &target); CHKERRQ(ierr);\n\n // Gather RHS\n CeedVectorTakeArray(rhs_ceed, MemTypeP2C(mem_type), NULL);\n ierr = VecRestoreArrayAndMemType(rhs_loc, &r); CHKERRQ(ierr);\n ierr = VecZeroEntries(rhs); CHKERRQ(ierr);\n ierr = DMLocalToGlobal(dm, rhs_loc, ADD_VALUES, rhs); CHKERRQ(ierr);\n CeedVectorDestroy(&rhs_ceed);\n\n // Create the error QFunction\n CeedQFunctionCreateInterior(ceed, 1, bp_options[rp->bp_choice].error,\n bp_options[rp->bp_choice].error_loc, &qf_error);\n CeedQFunctionAddInput(qf_error, \"u\", rp->num_comp_u, CEED_EVAL_INTERP);\n CeedQFunctionAddInput(qf_error, \"true_soln\", rp->num_comp_u, CEED_EVAL_NONE);\n CeedQFunctionAddOutput(qf_error, \"error\", rp->num_comp_u, CEED_EVAL_NONE);\n\n // Create the error operator\n CeedOperatorCreate(ceed, qf_error, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE,\n &op_error);\n CeedOperatorSetField(op_error, \"u\", ceed_data->elem_restr_u,\n ceed_data->basis_u, CEED_VECTOR_ACTIVE);\n CeedOperatorSetField(op_error, \"true_soln\", ceed_data->elem_restr_u_i,\n CEED_BASIS_COLLOCATED, target);\n CeedOperatorSetField(op_error, \"error\", ceed_data->elem_restr_u_i,\n CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);\n\n // Set up Mat\n user_O->comm = rp->comm;\n user_O->dm = dm;\n user_O->X_loc = X_loc;\n ierr = VecDuplicate(X_loc, &user_O->Y_loc); CHKERRQ(ierr);\n user_O->x_ceed = ceed_data->x_ceed;\n user_O->y_ceed = ceed_data->y_ceed;\n user_O->op = ceed_data->op_apply;\n user_O->ceed = ceed;\n\n ierr = KSPCreate(rp->comm, &ksp); CHKERRQ(ierr);\n {\n PC pc;\n ierr = KSPGetPC(ksp, &pc); CHKERRQ(ierr);\n if (rp->bp_choice == CEED_BP1 || rp->bp_choice == CEED_BP2) {\n ierr = PCSetType(pc, PCJACOBI); CHKERRQ(ierr);\n ierr = PCJacobiSetType(pc, PC_JACOBI_ROWSUM); CHKERRQ(ierr);\n } else {\n ierr = PCSetType(pc, PCNONE); CHKERRQ(ierr);\n }\n ierr = KSPSetType(ksp, KSPCG); CHKERRQ(ierr);\n ierr = KSPSetNormType(ksp, KSP_NORM_NATURAL); CHKERRQ(ierr);\n ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT,\n PETSC_DEFAULT); CHKERRQ(ierr);\n }\n ierr = KSPSetOperators(ksp, mat_O, mat_O); CHKERRQ(ierr);\n\n // First run's performance log is not considered for benchmarking purposes\n ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 1);\n CHKERRQ(ierr);\n my_rt_start = MPI_Wtime();\n ierr = KSPSolve(ksp, rhs, X); CHKERRQ(ierr);\n my_rt = MPI_Wtime() - my_rt_start;\n ierr = MPI_Allreduce(MPI_IN_PLACE, &my_rt, 1, MPI_DOUBLE, MPI_MIN, rp->comm);\n CHKERRQ(ierr);\n // Set maxits based on first iteration timing\n if (my_rt > 0.02) {\n ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT,\n rp->ksp_max_it_clip[0]);\n CHKERRQ(ierr);\n } else {\n ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT,\n rp->ksp_max_it_clip[1]);\n CHKERRQ(ierr);\n }\n ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr);\n\n // Timed solve\n ierr = VecZeroEntries(X); CHKERRQ(ierr);\n ierr = PetscBarrier((PetscObject)ksp); CHKERRQ(ierr);\n\n // -- Performance logging\n ierr = PetscLogStagePush(rp->solve_stage); CHKERRQ(ierr);\n\n // -- Solve\n my_rt_start = MPI_Wtime();\n ierr = KSPSolve(ksp, rhs, X); CHKERRQ(ierr);\n my_rt = MPI_Wtime() - my_rt_start;\n\n // -- Performance logging\n ierr = PetscLogStagePop();\n\n // Output results\n {\n KSPType ksp_type;\n KSPConvergedReason reason;\n PetscReal rnorm;\n PetscInt its;\n ierr = KSPGetType(ksp, &ksp_type); CHKERRQ(ierr);\n ierr = KSPGetConvergedReason(ksp, &reason); CHKERRQ(ierr);\n ierr = KSPGetIterationNumber(ksp, &its); CHKERRQ(ierr);\n ierr = KSPGetResidualNorm(ksp, &rnorm); CHKERRQ(ierr);\n if (!rp->test_mode || reason < 0 || rnorm > 1e-8) {\n ierr = PetscPrintf(rp->comm,\n \" KSP:\\n\"\n \" KSP Type : %s\\n\"\n \" KSP Convergence : %s\\n\"\n \" Total KSP Iterations : %D\\n\"\n \" Final rnorm : %e\\n\",\n ksp_type, KSPConvergedReasons[reason], its,\n (double)rnorm); CHKERRQ(ierr);\n }\n if (!rp->test_mode) {\n ierr = PetscPrintf(rp->comm,\" Performance:\\n\"); CHKERRQ(ierr);\n }\n {\n PetscReal max_error;\n ierr = ComputeErrorMax(user_O, op_error, X, target, &max_error);\n CHKERRQ(ierr);\n PetscReal tol = 5e-2;\n if (!rp->test_mode || max_error > tol) {\n ierr = MPI_Allreduce(&my_rt, &rt_min, 1, MPI_DOUBLE, MPI_MIN, rp->comm);\n CHKERRQ(ierr);\n ierr = MPI_Allreduce(&my_rt, &rt_max, 1, MPI_DOUBLE, MPI_MAX, rp->comm);\n CHKERRQ(ierr);\n ierr = PetscPrintf(rp->comm,\n \" Pointwise Error (max) : %e\\n\"\n \" CG Solve Time : %g (%g) sec\\n\",\n (double)max_error, rt_max, rt_min); CHKERRQ(ierr);\n }\n }\n if (!rp->test_mode) {\n ierr = PetscPrintf(rp->comm,\n \" DoFs/Sec in CG : %g (%g) million\\n\",\n 1e-6*g_size*its/rt_max,\n 1e-6*g_size*its/rt_min); CHKERRQ(ierr);\n }\n }\n\n if (rp->write_solution) {\n PetscViewer vtk_viewer_soln;\n\n ierr = PetscViewerCreate(rp->comm, &vtk_viewer_soln); CHKERRQ(ierr);\n ierr = PetscViewerSetType(vtk_viewer_soln, PETSCVIEWERVTK); CHKERRQ(ierr);\n ierr = PetscViewerFileSetName(vtk_viewer_soln, \"solution.vtu\"); CHKERRQ(ierr);\n ierr = VecView(X, vtk_viewer_soln); CHKERRQ(ierr);\n ierr = PetscViewerDestroy(&vtk_viewer_soln); CHKERRQ(ierr);\n }\n\n // Cleanup\n ierr = VecDestroy(&X); CHKERRQ(ierr);\n ierr = VecDestroy(&X_loc); CHKERRQ(ierr);\n ierr = VecDestroy(&user_O->Y_loc); CHKERRQ(ierr);\n ierr = MatDestroy(&mat_O); CHKERRQ(ierr);\n ierr = PetscFree(user_O); CHKERRQ(ierr);\n ierr = CeedDataDestroy(0, ceed_data); CHKERRQ(ierr);\n\n ierr = VecDestroy(&rhs); CHKERRQ(ierr);\n ierr = VecDestroy(&rhs_loc); CHKERRQ(ierr);\n ierr = KSPDestroy(&ksp); CHKERRQ(ierr);\n CeedVectorDestroy(&target);\n CeedQFunctionDestroy(&qf_error);\n CeedOperatorDestroy(&op_error);\n CeedDestroy(&ceed);\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode Run(RunParams rp, PetscInt num_resources,\n char *const *ceed_resources, PetscInt num_bp_choices,\n const BPType *bp_choices) {\n PetscInt ierr;\n DM dm;\n\n PetscFunctionBeginUser;\n // Setup DM\n if (rp->read_mesh) {\n ierr = DMPlexCreateFromFile(PETSC_COMM_WORLD, rp->filename, PETSC_TRUE, &dm);\n CHKERRQ(ierr);\n } else {\n if (rp->user_l_nodes) {\n // Find a nicely composite number of elements no less than global nodes\n PetscMPIInt size;\n ierr = MPI_Comm_size(rp->comm, &size); CHKERRQ(ierr);\n for (PetscInt g_elem =\n PetscMax(1, size * rp->local_nodes / PetscPowInt(rp->degree, rp->dim));\n ;\n g_elem++) {\n Split3(g_elem, rp->mesh_elem, true);\n if (Max3(rp->mesh_elem) / Min3(rp->mesh_elem) <= 2) break;\n }\n }\n ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, rp->dim, PETSC_FALSE,\n rp->mesh_elem,\n NULL, NULL, NULL, PETSC_TRUE, &dm); CHKERRQ(ierr);\n }\n\n {\n DM dm_dist = NULL;\n PetscPartitioner part;\n\n ierr = DMPlexGetPartitioner(dm, &part); CHKERRQ(ierr);\n ierr = PetscPartitionerSetFromOptions(part); CHKERRQ(ierr);\n ierr = DMPlexDistribute(dm, 0, NULL, &dm_dist); CHKERRQ(ierr);\n if (dm_dist) {\n ierr = DMDestroy(&dm); CHKERRQ(ierr);\n dm = dm_dist;\n }\n }\n // Disable default VECSTANDARD *after* distribution (which creates a Vec)\n ierr = DMSetVecType(dm, NULL); CHKERRQ(ierr);\n\n for (PetscInt b = 0; b < num_bp_choices; b++) {\n DM dm_deg;\n VecType vec_type;\n PetscInt q_extra = rp->q_extra;\n rp->bp_choice = bp_choices[b];\n rp->num_comp_u = bp_options[rp->bp_choice].num_comp_u;\n rp->q_extra = q_extra < 0 ? bp_options[rp->bp_choice].q_extra : q_extra;\n ierr = DMClone(dm, &dm_deg); CHKERRQ(ierr);\n ierr = DMGetVecType(dm, &vec_type); CHKERRQ(ierr);\n ierr = DMSetVecType(dm_deg, vec_type); CHKERRQ(ierr);\n // Create DM\n PetscInt dim;\n ierr = DMGetDimension(dm_deg, &dim); CHKERRQ(ierr);\n ierr = SetupDMByDegree(dm_deg, rp->degree, rp->num_comp_u, dim,\n bp_options[rp->bp_choice].enforce_bc,\n bp_options[rp->bp_choice].bc_func); CHKERRQ(ierr);\n for (PetscInt r = 0; r < num_resources; r++) {\n ierr = RunWithDM(rp, dm_deg, ceed_resources[r]); CHKERRQ(ierr);\n }\n ierr = DMDestroy(&dm_deg); CHKERRQ(ierr);\n rp->q_extra = q_extra;\n }\n\n ierr = DMDestroy(&dm); CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\nint main(int argc, char **argv) {\n PetscInt ierr, comm_size;\n RunParams rp;\n MPI_Comm comm;\n char filename[PETSC_MAX_PATH_LEN];\n char *ceed_resources[30];\n PetscInt num_ceed_resources = 30;\n char hostname[PETSC_MAX_PATH_LEN];\n\n PetscInt dim = 3, mesh_elem[3] = {3, 3, 3};\n PetscInt num_degrees = 30, degree[30] = {}, num_local_nodes = 2,\n local_nodes[2] = {};\n PetscMPIInt ranks_per_node;\n PetscBool degree_set;\n BPType bp_choices[10];\n PetscInt num_bp_choices = 10;\n\n // Initialize PETSc\n ierr = PetscInitialize(&argc, &argv, NULL, help);\n if (ierr) return ierr;\n comm = PETSC_COMM_WORLD;\n ierr = MPI_Comm_size(comm, &comm_size);\n if (ierr != MPI_SUCCESS) return ierr;\n #if defined(PETSC_HAVE_MPI_PROCESS_SHARED_MEMORY)\n {\n MPI_Comm splitcomm;\n ierr = MPI_Comm_split_type(comm, MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL,\n &splitcomm);\n CHKERRQ(ierr);\n ierr = MPI_Comm_size(splitcomm, &ranks_per_node); CHKERRQ(ierr);\n ierr = MPI_Comm_free(&splitcomm); CHKERRQ(ierr);\n }\n #else\n ranks_per_node = -1; // Unknown\n #endif\n\n // Setup all parameters needed in Run()\n ierr = PetscMalloc1(1, &rp); CHKERRQ(ierr);\n rp->comm = comm;\n\n // Read command line options\n ierr = PetscOptionsBegin(comm, NULL, \"CEED BPs in PETSc\", NULL);\n CHKERRQ(ierr);\n {\n PetscBool set;\n ierr = PetscOptionsEnumArray(\"-problem\", \"CEED benchmark problem to solve\",\n NULL,\n bp_types, (PetscEnum *)bp_choices, &num_bp_choices, &set);\n CHKERRQ(ierr);\n if (!set) {\n bp_choices[0] = CEED_BP1;\n num_bp_choices = 1;\n }\n }\n rp->test_mode = PETSC_FALSE;\n ierr = PetscOptionsBool(\"-test\",\n \"Testing mode (do not print unless error is large)\",\n NULL, rp->test_mode, &rp->test_mode, NULL); CHKERRQ(ierr);\n rp->write_solution = PETSC_FALSE;\n ierr = PetscOptionsBool(\"-write_solution\", \"Write solution for visualization\",\n NULL, rp->write_solution, &rp->write_solution, NULL);\n CHKERRQ(ierr);\n degree[0] = rp->test_mode ? 3 : 2;\n ierr = PetscOptionsIntArray(\"-degree\",\n \"Polynomial degree of tensor product basis\", NULL,\n degree, &num_degrees, °ree_set); CHKERRQ(ierr);\n if (!degree_set)\n num_degrees = 1;\n rp->q_extra = PETSC_DECIDE;\n ierr = PetscOptionsInt(\"-q_extra\",\n \"Number of extra quadrature points (-1 for auto)\", NULL,\n rp->q_extra, &rp->q_extra, NULL); CHKERRQ(ierr);\n {\n PetscBool set;\n ierr = PetscOptionsStringArray(\"-ceed\",\n \"CEED resource specifier (comma-separated list)\", NULL,\n ceed_resources, &num_ceed_resources, &set); CHKERRQ(ierr);\n if (!set) {\n ierr = PetscStrallocpy( \"/cpu/self\", &ceed_resources[0]); CHKERRQ(ierr);\n num_ceed_resources = 1;\n }\n }\n ierr = PetscGetHostName(hostname, sizeof hostname); CHKERRQ(ierr);\n ierr = PetscOptionsString(\"-hostname\", \"Hostname for output\", NULL, hostname,\n hostname, sizeof(hostname), NULL); CHKERRQ(ierr);\n rp->read_mesh = PETSC_FALSE;\n ierr = PetscOptionsString(\"-mesh\", \"Read mesh from file\", NULL, filename,\n filename, sizeof(filename), &rp->read_mesh);\n CHKERRQ(ierr);\n rp->filename = filename;\n if (!rp->read_mesh) {\n PetscInt tmp = dim;\n ierr = PetscOptionsIntArray(\"-cells\", \"Number of cells per dimension\", NULL,\n mesh_elem, &tmp, NULL); CHKERRQ(ierr);\n }\n local_nodes[0] = 1000;\n ierr = PetscOptionsIntArray(\"-local_nodes\",\n \"Target number of locally owned nodes per \"\n \"process (single value or min,max)\",\n NULL, local_nodes, &num_local_nodes, &rp->user_l_nodes);\n CHKERRQ(ierr);\n if (num_local_nodes < 2)\n local_nodes[1] = 2 * local_nodes[0];\n {\n PetscInt two = 2;\n rp->ksp_max_it_clip[0] = 5;\n rp->ksp_max_it_clip[1] = 20;\n ierr = PetscOptionsIntArray(\"-ksp_max_it_clip\",\n \"Min and max number of iterations to use during benchmarking\",\n NULL, rp->ksp_max_it_clip, &two, NULL); CHKERRQ(ierr);\n }\n if (!degree_set) {\n PetscInt max_degree = 8;\n ierr = PetscOptionsInt(\"-max_degree\",\n \"Range of degrees [1, max_degree] to run with\",\n NULL, max_degree, &max_degree, NULL);\n CHKERRQ(ierr);\n for (PetscInt i = 0; i < max_degree; i++)\n degree[i] = i + 1;\n num_degrees = max_degree;\n }\n {\n PetscBool flg;\n PetscInt p = ranks_per_node;\n ierr = PetscOptionsInt(\"-p\", \"Number of MPI ranks per node\", NULL,\n p, &p, &flg);\n CHKERRQ(ierr);\n if (flg) ranks_per_node = p;\n }\n\n ierr = PetscOptionsEnd();\n CHKERRQ(ierr);\n\n // Register PETSc logging stage\n ierr = PetscLogStageRegister(\"Solve Stage\", &rp->solve_stage);\n CHKERRQ(ierr);\n\n rp->hostname = hostname;\n rp->dim = dim;\n rp->mesh_elem = mesh_elem;\n rp->ranks_per_node = ranks_per_node;\n\n for (PetscInt d = 0; d < num_degrees; d++) {\n PetscInt deg = degree[d];\n for (PetscInt n = local_nodes[0]; n < local_nodes[1]; n *= 2) {\n rp->degree = deg;\n rp->local_nodes = n;\n ierr = Run(rp, num_ceed_resources, ceed_resources,\n num_bp_choices, bp_choices); CHKERRQ(ierr);\n }\n }\n // Clear memory\n ierr = PetscFree(rp); CHKERRQ(ierr);\n for (PetscInt i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"symbols.h\"\n#include \"gsl_userdef.h\"\n\n/* The symbol table: a chain of `struct symrec'. */\nsymrec *sym_table = (symrec *)0;\n\nvoid str_tolower(char *in)\n{\n for(; *in; in++)\n *in = (char)tolower(*in);\n}\n\nvoid sym_mark_table_used ()\n{\n symrec *ptr;\n\n for (ptr = sym_table; ptr != (symrec *) 0;\n ptr = (symrec *)ptr->next)\n {\n ptr->used = 1;\n }\n}\n\nsymrec *putsym (const char *sym_name, symrec_type sym_type) \n{\n symrec *ptr;\n ptr = (symrec *)malloc(sizeof(symrec));\n\n /* names are always lowercase */\n ptr->name = strdup(sym_name);\n str_tolower(ptr->name);\n \n ptr->def = 0;\n ptr->used = 0;\n ptr->type = sym_type;\n GSL_SET_COMPLEX(&ptr->value.c, 0, 0); /* set value to 0 even if fctn. */\n ptr->next = (struct symrec *)sym_table;\n sym_table = ptr;\n return ptr;\n}\n\nsymrec *getsym (const char *sym_name)\n{\n symrec *ptr;\n for (ptr = sym_table; ptr != (symrec *) 0;\n ptr = (symrec *)ptr->next)\n if (strcasecmp(ptr->name,sym_name) == 0){\n ptr->used = 1;\n return ptr;\n }\n return (symrec *) 0;\n}\n\nint rmsym (const char *sym_name)\n{\n symrec *ptr, *prev;\n for (prev = (symrec *) 0, ptr = sym_table; ptr != (symrec *) 0;\n prev = ptr, ptr = ptr->next)\n if (strcasecmp(ptr->name,sym_name) == 0){\n if(prev == (symrec *) 0)\n\tsym_table = ptr->next;\n else\n\tprev->next = ptr->next;\n free(ptr->name);\n free(ptr);\n \n return 1;\n }\n \n return 0;\n}\n\nstruct init_fntc{\n char *fname;\n int nargs;\n gsl_complex (*fnctptr)();\n};\n\nvoid sym_notdef (symrec *sym)\n{\n fprintf(stderr, \"Parser error: symbol '%s' used before being defined.\\n\", sym->name);\n exit(1);\n}\n\nvoid sym_redef (symrec *sym)\n{\n fprintf(stderr, \"Parser warning: redefining symbol, previous value \");\n sym_print(stderr, sym);\n fprintf(stderr, \"\\n\");\n}\n\nvoid sym_wrong_arg (symrec *sym)\n{\n if(sym->type == S_BLOCK) {\n fprintf(stderr, \"Parser error: block name '%s' used in variable context.\\n\", sym->name);\n } else if(sym->type == S_STR) {\n fprintf(stderr, \"Parser error: string variable '%s' used in expression context.\\n\", sym->name);\n } else {\n fprintf(stderr, \"Parser error: function '%s' requires %d argument(s).\\n\", sym->name, sym->nargs);\n }\n exit(1);\n}\n\nstatic struct init_fntc arith_fncts[] = {\n {\"sqrt\", 1, (gsl_complex (*)()) &gsl_complex_sqrt},\n {\"exp\", 1, (gsl_complex (*)()) &gsl_complex_exp},\n {\"ln\", 1, (gsl_complex (*)()) &gsl_complex_log},\n {\"log\", 1, (gsl_complex (*)()) &gsl_complex_log},\n {\"log10\", 1, (gsl_complex (*)()) &gsl_complex_log10},\n {\"logb\", 2, (gsl_complex (*)()) &gsl_complex_log_b}, /* takes two arguments logb(z, b) = log_b(z) */\n\n {\"arg\", 1, (gsl_complex (*)()) &gsl_complex_carg},\n {\"abs\", 1, (gsl_complex (*)()) &gsl_complex_cabs},\n {\"abs2\", 1, (gsl_complex (*)()) &gsl_complex_cabs2},\n {\"logabs\", 1, (gsl_complex (*)()) &gsl_complex_clogabs},\n\n {\"conjg\", 1, (gsl_complex (*)()) &gsl_complex_conjugate},\n {\"inv\", 1, (gsl_complex (*)()) &gsl_complex_inverse},\n\n {\"sin\", 1, (gsl_complex (*)()) &gsl_complex_sin},\n {\"cos\", 1, (gsl_complex (*)()) &gsl_complex_cos},\n {\"tan\", 1, (gsl_complex (*)()) &gsl_complex_tan},\n {\"sec\", 1, (gsl_complex (*)()) &gsl_complex_sec},\n {\"csc\", 1, (gsl_complex (*)()) &gsl_complex_csc},\n {\"cot\", 1, (gsl_complex (*)()) &gsl_complex_cot},\n\n {\"asin\", 1, (gsl_complex (*)()) &gsl_complex_arcsin},\n {\"acos\", 1, (gsl_complex (*)()) &gsl_complex_arccos},\n {\"atan\", 1, (gsl_complex (*)()) &gsl_complex_arctan},\n {\"atan2\", 2, (gsl_complex (*)()) &gsl_complex_arctan2}, /* takes two arguments atan2(y,x) = atan(y/x) */\n {\"asec\", 1, (gsl_complex (*)()) &gsl_complex_arcsec},\n {\"acsc\", 1, (gsl_complex (*)()) &gsl_complex_arccsc},\n {\"acot\", 1, (gsl_complex (*)()) &gsl_complex_arccot},\n\n {\"sinh\", 1, (gsl_complex (*)()) &gsl_complex_sinh},\n {\"cosh\", 1, (gsl_complex (*)()) &gsl_complex_cosh},\n {\"tanh\", 1, (gsl_complex (*)()) &gsl_complex_tanh},\n {\"sech\", 1, (gsl_complex (*)()) &gsl_complex_sech},\n {\"csch\", 1, (gsl_complex (*)()) &gsl_complex_csch},\n {\"coth\", 1, (gsl_complex (*)()) &gsl_complex_coth},\n\n {\"asinh\", 1, (gsl_complex (*)()) &gsl_complex_arcsinh},\n {\"acosh\", 1, (gsl_complex (*)()) &gsl_complex_arccosh},\n {\"atanh\", 1, (gsl_complex (*)()) &gsl_complex_arctanh},\n {\"asech\", 1, (gsl_complex (*)()) &gsl_complex_arcsech},\n {\"acsch\", 1, (gsl_complex (*)()) &gsl_complex_arccsch},\n {\"acoth\", 1, (gsl_complex (*)()) &gsl_complex_arccoth},\t\n \n/* user-defined step function. this is not available in GSL, \n but we use GSL namespacing and macros here. */\n {\"step\", 1, (gsl_complex (*)()) &gsl_complex_step_real},\n\n/* Minimum and maximum of two arguments (comparing real parts) */ \n {\"min\", 2, (gsl_complex (*)()) &gsl_complex_min_real},\n {\"max\", 2, (gsl_complex (*)()) &gsl_complex_max_real},\n\n {\"erf\", 1, (gsl_complex (*)()) &gsl_complex_erf},\n\n {\"realpart\", 1, (gsl_complex (*)()) &gsl_complex_realpart},\n {\"imagpart\", 1, (gsl_complex (*)()) &gsl_complex_imagpart},\n {\"round\", 1, (gsl_complex (*)()) &gsl_complex_round},\n {\"floor\", 1, (gsl_complex (*)()) &gsl_complex_floor},\n {\"ceiling\", 1, (gsl_complex (*)()) &gsl_complex_ceiling},\n\n {\"rand\", 0, (gsl_complex (*)()) &gsl_complex_rand},\n\n {0, 0, 0}\n};\n\nstruct init_cnst{\n\tchar *fname;\n\tdouble re;\n\tdouble im;\n};\n\nstatic struct init_cnst arith_cnts[] = {\n\t{\"pi\", M_PI, 0}, \n\t{\"e\", M_E, 0},\n\t{\"i\", 0, 1},\n\t{\"true\", 1, 0}, \n\t{\"yes\", 1, 0},\n\t{\"false\", 0, 0}, \n\t{\"no\", 0, 0},\n\t{0, 0, 0}\n};\n\nchar *reserved_symbols[] = {\n \"x\", \"y\", \"z\", \"r\", \"w\", \"t\", 0\n};\n\nvoid sym_init_table () /* puts arithmetic functions in table. */\n{\n int i;\n symrec *ptr;\n for (i = 0; arith_fncts[i].fname != 0; i++){\n ptr = putsym (arith_fncts[i].fname, S_FNCT);\n ptr->def = 1;\n ptr->used = 1;\n ptr->nargs = arith_fncts[i].nargs;\n ptr->value.fnctptr = arith_fncts[i].fnctptr;\n }\n\n /* now the constants */\n for (i = 0; arith_cnts[i].fname != 0; i++){\n ptr = putsym(arith_cnts[i].fname, S_CMPLX);\n ptr->def = 1;\n ptr->used = 1;\n GSL_SET_COMPLEX(&ptr->value.c, arith_cnts[i].re, arith_cnts[i].im);\n }\n}\n\nvoid sym_end_table()\n{\n symrec *ptr, *ptr2;\n\n for (ptr = sym_table; ptr != NULL;){\n free(ptr->name);\n switch(ptr->type){\n case S_STR:\n free(ptr->value.str);\n break;\n case S_BLOCK:\n if(ptr->value.block->n > 0){\n\tfree(ptr->value.block->lines);\n }\n free(ptr->value.block);\n break;\n case S_CMPLX:\n case S_FNCT:\n break;\n }\n ptr2 = ptr->next;\n free(ptr);\n ptr = ptr2;\n }\n \n sym_table = NULL;\n}\n\n/* this function is defined in src/basic/varinfo_low.c */\nint varinfo_variable_exists(const char * var_name);\n\nvoid sym_output_table(int only_unused, int mpiv_node)\n{\n FILE *f;\n symrec *ptr;\n int any_unused = 0;\n\n if(mpiv_node != 0) {\n return;\n }\n \n if(only_unused) {\n f = stderr;\n } else {\n f = stdout;\n }\n \n for(ptr = sym_table; ptr != NULL; ptr = ptr->next){\n if(only_unused && ptr->used == 1) continue;\n if(only_unused && varinfo_variable_exists(ptr->name)) continue;\n if(any_unused == 0) {\n fprintf(f, \"\\nParser warning: possible mistakes in input file.\\n\");\n fprintf(f, \"List of variable assignments not used by parser:\\n\");\n any_unused = 1;\n }\n\n sym_print(f, ptr);\n }\n if(any_unused == 1) {\n fprintf(f, \"\\n\");\n }\n}\n\nvoid sym_print(FILE *f, const symrec *ptr)\n{\n fprintf(f, \"%s\", ptr->name);\n switch(ptr->type){\n case S_CMPLX:\n if(fabs(GSL_IMAG(ptr->value.c)) < 1.0e-14){\n fprintf(f, \" = %f\\n\", GSL_REAL(ptr->value.c));\n } else {\n fprintf(f, \" = (%f,%f)\\n\", GSL_REAL(ptr->value.c), GSL_IMAG(ptr->value.c));\n }\n break;\n case S_STR:\n fprintf(f, \" = \\\"%s\\\"\\n\", ptr->value.str);\n break;\n case S_BLOCK:\n fprintf(f, \"%s\\n\", \" <= BLOCK\");\n break;\n case S_FNCT:\n fprintf(f, \"%s\\n\", \" <= FUNCTION\");\n break;\n }\n}\n", "meta": {"hexsha": "12d95987f26290c4f1860e03cd305fc8c96eea31", "size": 8862, "ext": "c", "lang": "C", "max_stars_repo_path": "liboct_parser/symbols.c", "max_stars_repo_name": "shunsuke-sato/octopus", "max_stars_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-11-17T09:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-17T06:31:08.000Z", "max_issues_repo_path": "liboct_parser/symbols.c", "max_issues_repo_name": "shunsuke-sato/octopus", "max_issues_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-11T19:14:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-11T19:14:06.000Z", "max_forks_repo_path": "liboct_parser/symbols.c", "max_forks_repo_name": "shunsuke-sato/octopus", "max_forks_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-22T20:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-29T23:24:51.000Z", "avg_line_length": 27.2676923077, "max_line_length": 107, "alphanum_fraction": 0.5971563981, "num_tokens": 2937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.06853749065376102, "lm_q1q2_score": 0.03426874532688051}}
{"text": "\\documentclass{report}\n\\usepackage[T1]{fontenc}\n\\usepackage{bera}\n\n\\usepackage[pdftex,usenames,dvipsnames]{color}\n\\usepackage{listings}\n\\definecolor{mycode}{rgb}{0.9,0.9,1}\n\\lstset{language=c++,tabsize=1,basicstyle=\\scriptsize,backgroundcolor=\\color{mycode}}\n\n\\usepackage{hyperref}\n\\usepackage{fancyhdr}\n\\pagestyle{fancy}\n\\usepackage{verbatim}\n\\begin{document}\n\n%\\title{The Powell Class for Minimization of Functions}\n%\\author{G.A.}\n%\\maketitle\n\n\\begin{comment}\n@o Minimizer.h -t\n@{\n/*\n@i license.txt\n*/\n@}\n\\end{comment}\n\n\\section{A class to minimize a function without using Derivatives}\nThis requires the GNU Scientific Library, libraries and devel. headers.\n\nExplain usage here. FIXME.\n\nThis is the structure of this file:\n\n@o Minimizer.h -t\n@{\n#ifndef MINIMIZER_H\n#define MINIMIZER_H\n\n#include \n#include \n#include \nextern \"C\" {\n#include \n}\n\nnamespace PsimagLite {\n\t@\n\t@\n\t@\n} // namespace PsimagLite\n#endif // MINIMIZER_H\n\n@}\n\nAnd this is the class here:\n\n@d theClassHere\n@{\ntemplate\nclass Minimizer {\n\t@\npublic:\n\t@\n\t@\n\t@\nprivate:\n\t@\n\t@\n}; // class Minimizer\n@}\n\n\n@d privateTypedefsAndConstants\n@{\ntypedef typename FunctionType::FieldType FieldType;\ntypedef typename Vector::Type VectorType;\ntypedef Minimizer ThisType;\n\n@}\n\n@d privateData\n@{\nFunctionType& function_;\nSizeType maxIter_;\nconst gsl_multimin_fminimizer_type *gslT_;\ngsl_multimin_fminimizer *gslS_;\n@}\n\n@d constructor\n@{\nMinimizer(FunctionType& function,SizeType maxIter)\n\t\t: function_(function),\n\t\t maxIter_(maxIter),\n\t\t gslT_(gsl_multimin_fminimizer_nmsimplex2),\n\t\t gslS_(gsl_multimin_fminimizer_alloc(gslT_,function_.size()))\n{\n}\n@}\n\n@d publicFunctions\n@{\n@\n@}\n\n@d destructor\n@{\n~Minimizer()\n{\n\tgsl_multimin_fminimizer_free (gslS_);\n}\n@}\n\n\n@d simplex\n@{\nint simplex(VectorType& minVector,RealType delta=1e-3,RealType tolerance=1e-3)\n{\n\tgsl_vector *x;\n\t/* Starting point, */\n\tx = gsl_vector_alloc (function_.size());\n\tfor (SizeType i=0;i;\n\tfunc.n = function_.size();\n\tfunc.params = &function_;\n\tgsl_multimin_fminimizer_set (gslS_, &func, x, xs);\n\n\tfor (SizeType iter=0;iterx,iter);\n\t\t\tgsl_vector_free (x);\n\t\t\tgsl_vector_free (xs);\n\t\t\treturn iter;\n\t\t}\n\t}\n\tgsl_vector_free (x);\n\tgsl_vector_free (xs);\n\treturn -1;\n}\n@}\n\n@d privateFunctions\n@{\n@\n@}\n\n@d found\n@{\nvoid found(VectorType& minVector,gsl_vector* x,SizeType iter)\n{\n\tfor (SizeType i=0;i\nclass MockVector {\npublic:\n\tMockVector(const gsl_vector *v) : v_(v)\n\t{\n\t}\n\tconst FieldType& operator[](SizeType i) const\n\t{\n\t\treturn v_->data[i];\n\t}\n\tSizeType size() const { return v_->size; }\nprivate:\n\tconst gsl_vector *v_;\n}; // class MockVector\n@}\n\n@d MyFunction\n@{\ntemplate\ntypename FunctionType::FieldType myFunction(const gsl_vector *v, void *params)\n{\n\tMockVector mv(v);\n\tFunctionType* ft = (FunctionType *)params;\n\treturn ft->operator()(mv);\n}\n@}\n\n\\end{document}\n\n", "meta": {"hexsha": "0a18f2b0f305ccb7346011801c4693be7b9f96ab", "size": 3834, "ext": "w", "lang": "C", "max_stars_repo_path": "src/Minimizer.w", "max_stars_repo_name": "g1257/PsimagLite", "max_stars_repo_head_hexsha": "1cdeb4530c66cd41bd0c59af9ad2ecb1069ca010", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-08-19T16:06:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T02:37:47.000Z", "max_issues_repo_path": "src/Minimizer.w", "max_issues_repo_name": "npatel37/PsimagLiteORNL", "max_issues_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-02-02T20:28:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-08T22:56:12.000Z", "max_forks_repo_path": "src/Minimizer.w", "max_forks_repo_name": "npatel37/PsimagLiteORNL", "max_forks_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-04-29T17:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-22T03:33:19.000Z", "avg_line_length": 18.8866995074, "max_line_length": 85, "alphanum_fraction": 0.7282211789, "num_tokens": 1136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.07477005115479887, "lm_q1q2_score": 0.03389041156262909}}
{"text": "/* $Id$ */\n/*--------------------------------------------------------------------*/\n/*; Copyright (C) 2008 */\n/*; Associated Universities, Inc. Washington DC, USA. */\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 2 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/*; You should have received a copy of the GNU General Public */\n/*; License along with this program; if not, write to the Free */\n/*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */\n/*; MA 02139, USA. */\n/*; */\n/*; Correspondence about this software should be addressed as follows:*/\n/*; Internet email: bcotton@nrao.edu. */\n/*; Postal address: William Cotton */\n/*; National Radio Astronomy Observatory */\n/*; 520 Edgemont Road */\n/*; Charlottesville, VA 22903-2475 USA */\n/*--------------------------------------------------------------------*/\n\n#include \"ObitUtil.h\"\n#include \n\n/*----------------Obit: Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitUtil.c\n * ObitUtil utility function definitions.\n *\n */\n\n\n/*----------------------Private functions---------------------------*/\n/** Private: qsort ofloat comparison */\nstatic int compare_gfloat (const void* arg1, const void* arg2);\n\n\n/*----------------------Public functions---------------------------*/\n/**\n * Get mean values of an array.\n * \\param array array of values may be magic value blanked\n * \\param n dimension of array\n * \\return Mean value, possibly blanked\n */\nofloat meanValue (ofloat *array, olong incs, olong n)\n{\n olong i, count;\n ofloat sum, fblank =ObitMagicF() ;\n\n if (n<=0) return fblank;\n sum = 0.0;\n count = 0;\n for (i=0; i0) sum /= count;\n else sum = fblank;\n\n return sum;\n} /* end meanValue */\n\n/**\n * Get median value of an array.\n * Does sort then returns value array[ngood/2]\n * \\param array array of values, on return will be in ascending order\n * \\param n dimension of array\n * \\param inc stride in array\n * \\return Median value, possibly blanked\n */\nofloat medianValue (ofloat *array, olong incs, olong n)\n{\n olong i, ngood;\n ofloat out, fblank = ObitMagicF();\n gboolean blanked;\n\n if (n<=0) return fblank;\n\n /* Count good (non blank) points */\n ngood = 0;\n for (i=0; i1.0e20) array[i*incs] = fblank;\n }\n\n return out;\n} /* end medianValue */\n\n/**\n * Return average of navg values around median (with magic value blanking)\n * Does sort then returns average of center of array\n * If there are fewer than navg valid data then the median is returned.\n * \\param array array of values, on return will be in ascending order\n * \\param incs increment in data array, >1 => weights\n * \\param navg width of averaging about median\n * \\param doWt If True value after data is a weight\n * \\param n dimension of array\n * \\return Median/average, possibly blanked\n */\nofloat medianAvg (ofloat *array, olong incs, olong navg, gboolean doWt, olong n)\n{\n olong i, cnt, wid, ngood, ind, hi, lo;\n ofloat temp, wt, out=0.0, fblank = ObitMagicF();\n ofloat center;\n gboolean blanked;\n\n if (n<=0) return fblank;\n\n /* Count good (non blank) points */\n ngood = 0;\n for (i=0; inavg) {\n center = (ngood-1)/2.0;\n lo = MAX (1, (olong)(center - wid + 0.6));\n hi = MIN (ngood, (olong)(center + wid));\n /* Weighted? */\n if (doWt) {\n temp = 0.0; wt = 0.0;\n for (i=lo; i<=hi; i++) {\n\tif (array[i*incs]<1.0e20) {\n\t wt += array[i*incs+1];\n\t temp += array[i*incs]*array[i*incs+1];\n\t}\n }\n if (wt>0.0) out = temp/wt;\n } else { /* unweighted */\n temp = 0.0; cnt = 0;\n for (i=lo; i<=hi; i++) {\n\tif (array[i]<1.0e20) {\n\t cnt++;\n\t temp += array[i];\n\t}\n\tif (cnt>0) out = temp/cnt;\n }\n } /* end if weighting */\n }\n\n /* reset blanked values */\n if (blanked) {\n for (i=0; i1.0e20) array[i*incs] = fblank;\n }\n\n return out;\n} /* end medianAvg */\n\n/**\n * Return the running median of an array\n * \\param n Number of points\n * \\param wind Width of median window in cells\n * \\param array Array of values, fblank blanking supported\n * \\param alpha 0 -> 1 = pure boxcar -> pure MWF (Alpha of the \n * data samples in a window are discarded and \n * the rest averaged). \n * \\param rms RMS of array, median average sigma from each wind of data\n * \\param out array of size of array to be with median values\n * \\param work work array of size of array\n */\nvoid RunningMedian (olong n, olong wind, ofloat *array, ofloat alpha, \n\t\t ofloat *RMS, ofloat *out, ofloat *work)\n{\n ofloat *lwork=NULL;\n ofloat level, sigma, sigmaSum, sigmaCnt;\n ofloat fblank = ObitMagicF();\n olong i, j, k, op, ind, half, RMScnt=0;\n\n /* Create array */\n lwork = g_malloc0(wind*sizeof(ofloat));\n\n half = wind/2;\n ind = 0;\n op = 0;\n k = 0;\n sigmaSum = 0.0;\n sigmaCnt = 1;\n\n /* First half wind filled with median of first wind points */\n for (j=ind; j 1 = pure boxcar -> pure MWF (ALPHA of the \n * data samples are discarded and the rest averaged). \n * \\return alpha median value\n */\nofloat MedianLevel (olong n, ofloat *value, ofloat alpha)\n{\n ofloat out=0.0;\n ofloat fblank = ObitMagicF();\n ofloat beta, sum;\n olong i, i1, i2, count;\n\n if (n<=0) return out;\n\n /* Sort to ascending order */\n qsort ((void*)value, n, sizeof(ofloat), compare_gfloat);\n\n out = value[n/2];\n\n beta = MAX (0.05, MIN (0.95, alpha)) / 2.0; /* Average around median factor */\n\n /* Average around the center */\n i1 = MAX (0, (n/2)-(olong)(beta*n+0.5));\n i2 = MIN (n, (n/2)+(olong)(beta*n+0.5));\n\n if (i2>i1) {\n sum = 0.0;\n count = 0;\n for (i=i1; i0) out = sum / count;\n }\n \n return out;\n} /* end MedianLevel */\n\n/**\n * Determine robust RMS value of a ofloat array about mean\n * Use center 90% of points, excluding at least one point from each end\n * \\param n Number of points, needs at least 4\n * \\param value Array of values assumed sorted\n * \\param mean Mean value of value\n * \\return RMS value, fblank if cannot determine\n */\nofloat MedianSigma (olong n, ofloat *value, ofloat mean)\n{\n ofloat fblank = ObitMagicF();\n ofloat out;\n ofloat sum;\n olong i, i1, i2, count;\n\n out = fblank;\n if (n<=4) return out;\n if (mean==fblank) return out;\n\n /* Get RMS around the center 90% */\n i1 = MAX (1, (n/2)-(olong)(0.45*n+0.5));\n i2 = MIN (n-1, (n/2)+(olong)(0.45*n+0.5));\n\n if (i2>i1) {\n sum = 0.0;\n count = 0;\n for (i=i1; i1) out = sqrt(sum / (count-1));\n }\n \n return out;\n} /* end MedianSigma */\n\n/**\n * Fit polynomial y = f(poly, x) with magic value blanking\n * Use gsl package.\n * \\param poly [out] polynomial coef in order of increasing power of x\n * \\param order order of the polynomial\n * \\param x values at which y is sampled\n * \\param y values to be fitted\n * \\param wt weights for values\n * \\param n number of (x,y) value pairs\n */\nvoid FitPoly (ofloat *poly, olong order, ofloat *x, ofloat *y, ofloat *wt, \n\t olong n)\n{\n olong i, j, k, good, p=order+1;\n ofloat fgood=0.0;\n double xi, chisq;\n gsl_matrix *X, *cov;\n gsl_vector *yy, *w, *c;\n gsl_multifit_linear_workspace *work;\n ofloat fblank = ObitMagicF();\n\n /* Only use good data */\n good = 0;\n for (i=0; ilarg2) out = 1;\n return out;\n} /* end compare_gfloat */\n", "meta": {"hexsha": "acdd3182ad1a7a5d6e06944296e4766319b03a1b", "size": 13077, "ext": "c", "lang": "C", "max_stars_repo_path": "ObitSystem/Obit/src/ObitUtil.c", "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_issues_repo_path": "ObitSystem/Obit/src/ObitUtil.c", "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/Obit/src/ObitUtil.c", "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "avg_line_length": 28.5524017467, "max_line_length": 81, "alphanum_fraction": 0.5589967118, "num_tokens": 3994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.06954174450582809, "lm_q1q2_score": 0.03260051798356929}}
{"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#ifndef LIBNEWTON_H_\r\n#define LIBNEWTON_H_\r\n\r\n#include \r\n#include \r\n\r\n/**\r\n * @brief Jacobian Callback for the Newton algorithm\r\n * \r\n * The callback receivs the current input, the current control, and the list of\r\n * parameter vectors. It should store the first argument the Jacobian matrix (stored as an array).\r\n * To select the ordering in the matrix, you must select the correct ordering in newton_options \r\n * structure, at the ordering input.\r\n * @param df output vector (vectorized Jacobian matrix)\r\n * @param t current time for evaluation\r\n * @param x current point for evaluation\r\n * @param u current control for evaluation\r\n * @param p array of parameter vectors\r\n * @param data user space input (simply use it as a pointer casted to void)\r\n */\r\ntypedef void (*newton_jacobian)(\r\n double *df,\r\n const double t,\r\n const double *x,\r\n const double *u,\r\n const double **p,\r\n void *data);\r\n\r\n/**\r\n * @brief Vector Field Callback for the Newton algorithm\r\n * \r\n * The callback receivs the current input, the current control, and the list of\r\n * parameter vectors. It should store the first argument the function output vector.\r\n * @param df output vector (vectorized Jacobian matrix)\r\n * @param t current time for evaluation\r\n * @param x current point for evaluation\r\n * @param u current control for evaluation\r\n * @param p array of parameter vectors\r\n * @param data user space input (simply use it as a pointer casted to void)\r\n */\r\ntypedef void (*newton_function)(\r\n double *f,\r\n const double t,\r\n const double *x,\r\n const double *u,\r\n const double **p,\r\n void *data);\r\n\r\n/**\r\n * @brief Options for the Newton Algorithm\r\n * \r\n * This structure contains all the options for the Newton algorithm, alongside the callbacks.\r\n * The structure will be modified by the algorithm with some debug information, such as number\r\n * of iterations, tolerances and ordering for the jacobian matrix.\r\n */\r\ntypedef struct newton_options {\r\n lapack_int ordering; /**< Should be LAPACK_ROW_MAJOR or LAPACK_COL_MAJOR */\r\n lapack_int f_size; /**< Vector field size */\r\n lapack_int x_size; /**< Variable vector size */\r\n double f_tol; /**< Stopping tolerance for the zero. \r\n At the end will contain the 2 norm of the \r\n vector field in the solution */\r\n double x_tol; /**< Stopping tolerance for the x vector step.\r\n At the end will contain the 2 norm of the last update step */\r\n lapack_int max_iter; /**< Maximum number of iteration,\r\n At the end will contain the number of step executed */\r\n newton_function f; /**< Pointer to vector field callback */\r\n newton_jacobian df; /**< Pointer to Jacobian callback */\r\n} newton_options;\r\n\r\n/**\r\n * @brief Error code returned by the algorithm\r\n */\r\ntypedef enum newton_ret {\r\n NEWTON_F_TOL = 0, /**< (0) The solver reached the required tolerance limit for the vector field */\r\n NEWTON_X_TOL, /**< (1) The last step for solution update was less than the minimum */\r\n NEWTON_MAX_ITER, /**< (2) Maximum number of iterations reached */\r\n NEWTON_SINGULAR_JACOBIAN, /**< (3 LAPACKE) The jacobian is singular */\r\n NEWTON_ILLEGAL_JACOBIAN, /**< (4 LAPACKE) Illegal jacobian */\r\n NEWTON_MALLOC_ERROR, /**< (5) Cannot allocate memory */\r\n NEWTON_GENERIC_ERROR /**< (6) Generic error in the execution of the algorithm */\r\n} newton_ret;\r\n\r\n/**\r\n * @brief Boolean implementation\r\n */\r\ntypedef enum newton_bool {\r\n NEWTON_FALSE = 0, /**< False */\r\n NEWTON_TRUE /**< True */\r\n} newton_bool;\r\n\r\n/**\r\n * @brief Executes the Newton algorithm for root finding\r\n * \r\n * Executes the Newton algorithm for root finding. The step Performed is:\r\n * \\f{\r\n * x_{k+1} - x_{k} = -\\nabla F^{-1}(x_k, u, p) F(x_k, u, p)\r\n * \\f}\r\n * and the solution is found by using DGELS defined in LAPACK library.\r\n * The stopping conditions are:\r\n * * Number of iterations bigger than maximum allowed (specified in newton_options)\r\n * * \\f$ |x_{k+1} - x_k| \\leq x_{tol}\\f$\r\n * * \\f$ |f(x_k, u, p)| \\leq y_{tol}\\f$\r\n * and the function and jacobian are evaluated through callbacks. On exit, the values \r\n * inside the option structure are update for debuggin purposes (this is why Newton \r\n * options is not a const pointer). It returns a status enum.\r\n * @param opt option structure\r\n * @param x root position and initial condition. Will be modified\r\n * @param u control action input. It can be NULL.\r\n * @param p parameter array of vectors. It can be NULL.\r\n * @param data space for user data. Will be passed to callbacks. It can be NULL\r\n * @return a status exit code as described in newton_ret enum.\r\n */\r\nnewton_ret newton_solve(\r\n newton_options *opt,\r\n const double t,\r\n double *x,\r\n const double *u,\r\n const double **p,\r\n void *data);\r\n\r\n#endif\r\n", "meta": {"hexsha": "a098d32ea181b719f94091ce4350af5e06308d8e", "size": 6251, "ext": "h", "lang": "C", "max_stars_repo_path": "libnewton.h", "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": "libnewton.h", "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": "libnewton.h", "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.1103448276, "max_line_length": 109, "alphanum_fraction": 0.6667733163, "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.06656918804457732, "lm_q1q2_score": 0.029401813368302124}}
{"text": "/*******************************************************************************\n*\n* This file is part of the General Hidden Markov Model Library,\n* GHMM version __VERSION__, see http://ghmm.org\n*\n* Filename: ghmm/ghmm/randvar.c\n* Authors: Bernhard Knab, Benjamin Rich, Janne Grunau\n*\n* Copyright (C) 1998-2004 Alexander Schliep\n* Copyright (C) 1998-2001 ZAIK/ZPR, Universitaet zu Koeln\n* Copyright (C) 2002-2004 Max-Planck-Institut fuer Molekulare Genetik,\n* Berlin\n*\n* Contact: schliep@ghmm.org\n*\n* This library is free software; you can redistribute it and/or\n* modify it under the terms of the GNU Library General Public\n* License as published by the Free Software Foundation; either\n* version 2 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* Library General Public License for more details.\n*\n* You should have received a copy of the GNU Library General Public\n* License along with this library; if not, write to the Free\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n*\n* This file is version $Revision: 2310 $\n* from $Date: 2013-06-14 10:36:57 -0400 (Fri, 14 Jun 2013) $\n* last change by $Author: ejb177 $.\n*\n*******************************************************************************/\n\n#ifdef HAVE_CONFIG_H\n# include \"../config.h\"\n#endif\n\n#include \n#include \n#include \n#ifdef HAVE_LIBPTHREAD\n# include \n#endif /* HAVE_LIBPTHREAD */\n\n#include \"ghmm.h\"\n#include \"mes.h\"\n#include \"mprintf.h\"\n#include \"randvar.h\"\n#include \"rng.h\"\n\n#ifdef DO_WITH_GSL\n\n# include \n# include \n# include \n\n#include \n#include \n#include \n\n#endif /* DO_WITH_GSL */\n\n\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)\n#else\nstatic double ighmm_erf (double x);\nstatic double ighmm_erfc (double x);\n#endif /* check for ISO C99 */\n\n/* A list of already calculated values of the density function of a \n N(0,1)-distribution, with x in [0.00, 19.99] */\n#define PDFLEN 2000\n#define X_STEP_PDF 0.01 /* step size */\n#define X_FAKT_PDF 100 /* equivalent to step size */\nstatic double pdf_stdnormal[PDFLEN];\nstatic int pdf_stdnormal_exists = 0;\n\n/* A list of already calulated values PHI of the Gauss distribution is\n read in, x in [-9.999, 0] */\n#define X_STEP_PHI 0.001 /* step size */\n#define X_FAKT_PHI 1000 /* equivalent to step size */\nstatic double x_PHI_1 = -1.0;\n\n#ifndef M_SQRT1_2\n#define M_SQRT1_2 0.70710678118654752440084436210\n#endif\n\n\n/*============================================================================*/\n/* needed by ighmm_gtail_pmue_interpol */\n\ndouble ighmm_rand_get_xfaktphi ()\n{\n return X_FAKT_PHI;\n}\n\ndouble ighmm_rand_get_xstepphi ()\n{\n return X_STEP_PHI;\n}\n\ndouble ighmm_rand_get_philen ()\n{\n#ifdef DO_WITH_GSL\n return 0 /*PHI_len*/;\n#else\n return ighmm_rand_get_xPHIless1 () / X_STEP_PHI;\n#endif\n}\n\n\n/*============================================================================*/\ndouble ighmm_rand_get_PHI (double x)\n{\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)\n return (erf (x * M_SQRT1_2) + 1.0) / 2.0;\n#else\n return (ighmm_erf (x * M_SQRT1_2) + 1.0) / 2.0;\n#endif\n} /* randvar_get_PHI */\n\n\n/*============================================================================*/\n/* When is PHI[x,0,1] == 1? */\ndouble ighmm_rand_get_xPHIless1 ()\n{\n# define CUR_PROC \"ighmm_rand_get_xPHIless1\"\n\n if (x_PHI_1 == -1) {\n double low, up, half;\n low = 0;\n up = 100;\n while (up - low > 0.001) {\n half = (low + up) / 2.0;\n if (ighmm_rand_get_PHI (half) < 1.0)\n low = half;\n else\n up = half;\n }\n x_PHI_1 = low;\n }\n return (x_PHI_1);\n\n# undef CUR_PROC\n}\n\n/*============================================================================*/\ndouble ighmm_rand_get_1overa (double x, double mean, double u)\n{\n /* Calulates 1/a(x, mean, u), with a = the integral from x til \\infty over\n the Gauss density function */\n# define CUR_PROC \"ighmm_rand_get_1overa\"\n\n double erfc_value;\n\n if (u <= 0.0) {\n GHMM_LOG(LCONVERTED, \"u <= 0.0 not allowed\\n\");\n goto STOP;\n }\n\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)\n erfc_value = erfc ((x - mean) / sqrt (u * 2));\n#else\n erfc_value = ighmm_erfc ((x - mean) / sqrt (u * 2));\n#endif\n\n if (erfc_value <= DBL_MIN) {\n ighmm_mes (MES_WIN, \"a ~= 0.0 critical! (mue = %.2f, u =%.2f)\\n\", mean, u);\n return (erfc_value);\n }\n else\n return (2.0 / erfc_value);\n\nSTOP:\n return (-1.0);\n# undef CUR_PROC\n} /* ighmm_rand_get_1overa */\n\n\n/*============================================================================*/\n/* REMARK:\n The calulation of this density function was testet, by calculating the \n following integral sum for arbitrary mue and u:\n for (x = 0, x < ..., x += step(=0.01/0.001/0.0001)) \n isum += step * ighmm_rand_normal_density_pos(x, mue, u);\n In each case, the sum \"converged\" evidently towards 1!\n (BK, 14.6.99)\n CHANGE:\n Truncate at -EPS_NDT (const.h), so that x = 0 doesn't lead to a problem.\n (BK, 15.3.2000)\n*/\ndouble ighmm_rand_normal_density_pos (double x, double mean, double u)\n{\n# define CUR_PROC \"ighmm_rand_normal_density_pos\"\n return ighmm_rand_normal_density_trunc (x, mean, u, -GHMM_EPS_NDT);\n# undef CUR_PROC\n} /* double ighmm_rand_normal_density_pos */\n\n\n/*============================================================================*/\ndouble ighmm_rand_normal_density_trunc(double x, double mean, double u,\n double a)\n{\n# define CUR_PROC \"ighmm_rand_normal_density_trunc\"\n#ifndef DO_WITH_GSL\n double c;\n#endif /* DO_WITH_GSL */\n\n if (u <= 0.0) {\n GHMM_LOG(LERROR, \"u <= 0.0 not allowed\");\n goto STOP;\n }\n if (x < a)\n return 0.0;\n\n#ifdef DO_WITH_GSL\n /* move mean to the right position */\n return gsl_ran_gaussian_tail_pdf(x - mean, a - mean, sqrt(u));\n#else\n if ((c = ighmm_rand_get_1overa(a, mean, u)) == -1) {\n GHMM_LOG_QUEUED(LERROR);\n goto STOP;\n };\n return c * ighmm_rand_normal_density(x, mean, u);\n#endif /* DO_WITH_GSL */\n\nSTOP:\n return -1.0;\n# undef CUR_PROC\n} /* double ighmm_rand_normal_density_trunc */\n\n\n/*============================================================================*/\ndouble ighmm_rand_normal_density (double x, double mean, double u)\n{\n# define CUR_PROC \"ighmm_rand_normal_density\"\n#ifndef DO_WITH_GSL\n double expo;\n#endif\n if (u <= 0.0) {\n GHMM_LOG(LCONVERTED, \"u <= 0.0 not allowed\\n\");\n goto STOP;\n }\n /* The denominator is possibly < EPS??? Check that ? */\n#ifdef DO_WITH_GSL\n /* double gsl_ran_gaussian_pdf (double x, double sigma) */\n return gsl_ran_gaussian_pdf (x - mean, sqrt (u));\n#else\n expo = exp (-1 * m_sqr (mean - x) / (2 * u));\n return (1 / (sqrt (2 * PI * u)) * expo);\n#endif\n\nSTOP:\n return (-1.0);\n# undef CUR_PROC\n} /* double ighmm_rand_normal_density */\n\n\n/*============================================================================*/\n/* covariance matrix is linearized */\ndouble ighmm_rand_binormal_density(const double *x, double *mean, double *cov)\n{\n# define CUR_PROC \"ighmm_rand_binormal_density\"\n double rho;\n#ifndef DO_WITH_GSL\n double numerator,part1,part2,part3;\n#endif\n if (cov[0] <= 0.0 || cov[2 + 1] <= 0.0) {\n GHMM_LOG(LCONVERTED, \"variance <= 0.0 not allowed\\n\");\n goto STOP;\n }\n rho = cov[1] / ( sqrt (cov[0]) * sqrt (cov[2 + 1]) );\n /* The denominator is possibly < EPS??? Check that ? */\n#ifdef DO_WITH_GSL\n /* double gsl_ran_bivariate_gaussian_pdf (double x, double y, double sigma_x,\n double sigma_y, double rho) */\n return gsl_ran_bivariate_gaussian_pdf (x[0], x[1], sqrt (cov[0]),\n sqrt (cov[2 + 1]), rho);\n#else\n part1 = (x[0] - mean[0]) / sqrt (cov[0]);\n part2 = (x[1] - mean[1]) / sqrt (cov[2 + 1]);\n part3 = m_sqr (part1) - 2 * part1 * part2 + m_sqr (part2);\n numerator = exp ( -1 * (part3) / ( 2 * (1 - m_sqr(rho)) ) );\n return (numerator / ( 2 * PI * sqrt(1 - m_sqr(rho)) ));\n#endif\n\nSTOP:\n return (-1.0);\n# undef CUR_PROC\n} /* double ighmm_rand_binormal_density */\n\n/*============================================================================*/\n/* matrices are linearized */\ndouble ighmm_rand_multivariate_normal_density(int length, const double *x, double *mean, double *sigmainv, double det)\n{\n# define CUR_PROC \"ighmm_rand_multivariate_normal_density\"\n /* multivariate normal density function */\n /*\n * length dimension of the random vetor\n * x point at which to evaluate the pdf\n * mean vector of means of size n\n * sigmainv inverse variance matrix of dimension n x n\n * det determinant of covariance matrix\n */\n\n#ifdef DO_WITH_GSL\n int i, j;\n double ax,ay;\n gsl_vector *ym, *xm, *gmean;\n gsl_matrix *inv = gsl_matrix_alloc(length, length);\n\n\n for (i=0; i=min) ){\n return prob;\n }else{\n return 0.0;\n }\nSTOP:\n return (-1.0);\n# undef CUR_PROC\n} /* double ighmm_rand_uniform_density */\n\n\n/*============================================================================*/\n/* special ghmm_cmodel pdf need it: smo->density==normal_approx: */\n/* generates a table of of aequidistant samples of gaussian pdf */\n\nstatic int randvar_init_pdf_stdnormal ()\n{\n# define CUR_PROC \"randvar_init_pdf_stdnormal\"\n int i;\n double x = 0.00;\n for (i = 0; i < PDFLEN; i++) {\n pdf_stdnormal[i] = 1 / (sqrt (2 * PI)) * exp (-1 * x * x / 2);\n x += (double) X_STEP_PDF;\n }\n pdf_stdnormal_exists = 1;\n /* printf(\"pdf_stdnormal_exists = %d\\n\", pdf_stdnormal_exists); */\n return (0);\n# undef CUR_PROC\n} /* randvar_init_pdf_stdnormal */\n\n\ndouble ighmm_rand_normal_density_approx (double x, double mean, double u)\n{\n# define CUR_PROC \"ighmm_rand_normal_density_approx\"\n#ifdef HAVE_LIBPTHREAD\n static pthread_mutex_t lock;\n#endif /* HAVE_LIBPTHREAD */\n int i;\n double y, z, pdf_x;\n if (u <= 0.0) {\n GHMM_LOG(LCONVERTED, \"u <= 0.0 not allowed\\n\");\n goto STOP;\n }\n if (!pdf_stdnormal_exists) {\n#ifdef HAVE_LIBPTHREAD\n pthread_mutex_lock (&lock); /* Put on a lock, because the clustering is parallel */\n#endif /* HAVE_LIBPTHREAD */\n randvar_init_pdf_stdnormal ();\n#ifdef HAVE_LIBPTHREAD\n pthread_mutex_unlock (&lock); /* Take the lock off */\n#endif /* HAVE_LIBPTHREAD */\n }\n y = 1 / sqrt (u);\n z = fabs ((x - mean) * y);\n i = (int) (z * X_FAKT_PDF);\n /* linear interpolation: */\n if (i >= PDFLEN - 1) {\n i = PDFLEN - 1;\n pdf_x = y * pdf_stdnormal[i];\n }\n else\n pdf_x = y * (pdf_stdnormal[i] +\n (z - i * X_STEP_PDF) *\n (pdf_stdnormal[i + 1] - pdf_stdnormal[i]) / X_STEP_PDF);\n return (pdf_x);\nSTOP:\n return (-1.0);\n# undef CUR_PROC\n} /* double ighmm_rand_normal_density_approx */\ndouble ighmm_rand_dirichlet(int seed, int len, double *alpha, double *theta){\n if (seed != 0) {\n GHMM_RNG_SET(RNG, seed);\n }\n#ifdef DO_WITH_GSL\n gsl_ran_dirichlet(RNG, len, alpha, theta);\n#else\n printf(\"not implemted without gsl. Compile with gsl to use dirichlet\");\n#endif\n}\n\n/*============================================================================*/\ndouble ighmm_rand_std_normal (int seed)\n{\n# define CUR_PROC \"ighmm_rand_std_normal\"\n if (seed != 0) {\n GHMM_RNG_SET (RNG, seed);\n }\n\n#ifdef DO_WITH_GSL\n return (gsl_ran_gaussian (RNG, 1.0));\n#else\n /* Use the polar Box-Mueller transform */\n /*\n double x, y, r2;\n\n do {\n x = 2.0 * GHMM_RNG_UNIFORM(RNG) - 1.0;\n y = 2.0 * GHMM_RNG_UNIFORM(RNG) - 1.0;\n r2 = (x * x) + (y * y);\n } while (r2 >= 1.0);\n\n return x * sqrt((-2.0 * log(r2)) / r2);\n */\n\n double r2, theta;\n\n r2 = -2.0 * log (GHMM_RNG_UNIFORM (RNG)); /* r2 ~ chi-square(2) */\n theta = 2.0 * PI * GHMM_RNG_UNIFORM (RNG); /* theta ~ uniform(0, 2 \\pi) */\n return sqrt (r2) * cos (theta);\n#endif\n\n# undef CUR_PROC\n} /* ighmm_rand_std_normal */\n\n\n/*============================================================================*/\ndouble ighmm_rand_normal(double mue, double u, int seed)\n{\n# define CUR_PROC \"ighmm_rand_normal\"\n if (seed != 0) {\n GHMM_RNG_SET(RNG, seed);\n }\n\n#ifdef DO_WITH_GSL\n return gsl_ran_gaussian(RNG, sqrt (u)) + mue;\n#else\n double x;\n x = sqrt(u) * ighmm_rand_std_normal(seed) + mue;\n return x;\n#endif\n\n# undef CUR_PROC\n} /* ighmm_rand_normal */\n\n/*============================================================================*/\nint ighmm_rand_multivariate_normal (int dim, double *x, double *mue, double *sigmacd, int seed)\n{\n# define CUR_PROC \"ighmm_rand_multivariate_normal\"\n /* generate random vector of multivariate normal\n *\n * dim number of dimensions\n * x space to store resulting vector in\n * mue vector of means\n * sigmacd linearized cholesky decomposition of cov matrix\n * seed RNG seed\n *\n * see Barr & Slezak, A Comparison of Multivariate Normal Generators */\n int i, j;\n#ifdef DO_WITH_GSL\n gsl_vector *y = gsl_vector_alloc(dim);\n gsl_vector *xgsl = gsl_vector_alloc(dim);\n gsl_matrix *cd = gsl_matrix_alloc(dim, dim);\n#endif\n if (seed != 0) {\n GHMM_RNG_SET (RNG, seed);\n /* do something here */\n return 0;\n }\n else {\n#ifdef DO_WITH_GSL\n /* cholesky decomposition matrix */\n for (i=0;i= 199901L)\n /* PHI(x)=erf(x/sqrt(2))/2+0.5 */\n return (erf ((x - mean) / sqrt (u * 2.0)) + 1.0) / 2.0;\n#else\n return (ighmm_erf ((x - mean) / sqrt (u * 2.0)) + 1.0) / 2.0;\n#endif /* Check for ISO C99 */\nSTOP:\n return (-1.0);\n# undef CUR_PROC\n} /* double ighmm_rand_normal_cdf */\n\n/*============================================================================*/\n/* cumalative distribution function of a-truncated N(mean, u) */\ndouble ighmm_rand_normal_right_cdf (double x, double mean, double u, double a)\n{\n# define CUR_PROC \"ighmm_rand_normal_right_cdf\"\n\n if (x <= a)\n return (0.0);\n if (u <= a) {\n GHMM_LOG(LCONVERTED, \"u <= a not allowed\\n\");\n goto STOP;\n }\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)\n /*\n Function: int erfc (double x, gsl_sf_result * result) \n These routines compute the complementary error function\n erfc(x) = 1 - erf(x) = 2/\\sqrt(\\pi) \\int_x^\\infty \\exp(-t^2). \n */\n return 1.0 + (erf ((x - mean) / sqrt (u * 2)) -\n 1.0) / erfc ((a - mean) / sqrt (u * 2));\n#else\n return 1.0 + (ighmm_erf ((x - mean) / sqrt (u * 2)) -\n 1.0) / ighmm_erfc ((a - mean) / sqrt (u * 2));\n#endif /* Check for ISO C99 */\nSTOP:\n return (-1.0);\n# undef CUR_PROC\n} /* double ighmm_rand_normal_cdf */\n\n/*============================================================================*/\n/* cumalative distribution function of a uniform distribution in the range [min,max] */\ndouble ighmm_rand_uniform_cdf (double x, double max, double min)\n{\n# define CUR_PROC \"ighmm_rand_uniform_cdf\"\n if (max <= min) {\n GHMM_LOG(LCONVERTED, \"max <= min not allowed\\n\");\n goto STOP;\n } \n if (x < min) {\n return 0.0;\n }\n if (x >= max) {\n return 1.0;\n }\n return (x-min)/(max-min);\nSTOP:\n return (-1.0);\n# undef CUR_PROC\n} /* ighmm_rand_uniform_cdf */\n\n\n\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)\n#else\n\n/* THIS WILL BE OBSOLETE WHEN WE USE ISO C99 */ \n\n/*===========================================================================\n *\n * The following functions for the error function and the complementory\n * error function are taken from\n * http://www.mathematik.uni-bielefeld.de/~sillke/ALGORITHMS/special-functions/erf.c\n * and have following different copyright.\n\n * ====================================================\n * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\n *\n * Developed at SunPro, a Sun Microsystems, Inc. business.\n * Permission to use, copy, modify, and distribute this\n * software is freely granted, provided that this notice\n * is preserved.\n * ====================================================\n */\n\n/*\n * ====================================================\n * \n * Reference:\n *\n * W. J. Cody,\n * Rational Chebychev approximations for the\n * error function.\n * Mathematics of Computations 23 (1969) 631-637\n *\n * W. J. Cody,\n * Performance evaluations of programs for the \n * error and complementary error function.\n * Transactions of the ACM on Mathematical Software, \n * 16:1 (March 1990) 38-46\n * \n * W. J. Cody,\n * SPECFUN - A portable special function package,\n * In: New Computing environments; \n * Microcomputers in Large-Scale Scientific Computing,\n * A. Wouk, SIAM, 1987, 1-12\n *\n * W. J. Cody,\n * http://www.netlib.org/specfun/erf.\n *\n * For calculations with complex arguments see: \n * \n * Walter Gautschi\n * \"Efficient computation of the complex error function\"\n * SIAM J. Numer. Anal.\n * 7:1 (1970), 187-198\n * \n * J.A.C. Weideman\n * \"Computation of the complex error function\"\n * SIAM J. Numer. Anal.\n * 31:5 (1994), 1497-1518 \n *\n * ====================================================\n */\n\n\n/* double erf(double x)\n * double erfc(double x)\n *\t\t\t x\n *\t\t 2 |\\\n * erf(x) = --------- | exp(-t*t)dt\n *\t \t sqrt(pi) \\|\n *\t\t\t 0\n *\n * erfc(x) = 1-erf(x)\n * Note that\n *\t\terf(-x) = -erf(x)\n *\t\terfc(-x) = 2 - erfc(x)\n *\n * Method:\n *\t1. For |x| in [0, 0.84375]\n *\t erf(x) = x + x*R(x^2)\n * erfc(x) = 1 - erf(x) if x in [-.84375,0.25]\n * = 0.5 + ((0.5-x)-x*R) if x in [0.25,0.84375]\n *\t where R = P/Q where P is an odd poly of degree 8 and\n *\t Q is an odd poly of degree 10.\n *\t\t\t\t\t\t -57.90\n *\t\t\t| R - (erf(x)-x)/x | <= 2\n *\n *\n *\t Remark. The formula is derived by noting\n * erf(x) = (2/sqrt(pi))*(x - x^3/3 + x^5/10 - x^7/42 + ....)\n *\t and that\n * 2/sqrt(pi) = 1.128379167095512573896158903121545171688\n *\t is close to one. The interval is chosen because the fix\n *\t point of erf(x) is near 0.6174 (i.e., erf(x)=x when x is\n *\t near 0.6174), and by some experiment, 0.84375 is chosen to\n * \t guarantee the error is less than one ulp for erf.\n *\n * 2. For |x| in [0.84375,1.25], let s = |x| - 1, and\n * c = 0.84506291151 rounded to single (24 bits)\n * \terf(x) = sign(x) * (c + P1(s)/Q1(s))\n * \terfc(x) = (1-c) - P1(s)/Q1(s) if x > 0\n *\t\t\t 1+(c+P1(s)/Q1(s)) if x < 0\n * \t|P1/Q1 - (erf(|x|)-c)| <= 2**-59.06\n *\t Remark: here we use the taylor series expansion at x=1.\n *\t\terf(1+s) = erf(1) + s*Poly(s)\n *\t\t\t = 0.845.. + P1(s)/Q1(s)\n *\t That is, we use rational approximation to approximate\n *\t\t\terf(1+s) - (c = (single)0.84506291151)\n *\t Note that |P1/Q1|< 0.078 for x in [0.84375,1.25]\n *\t where\n *\t\tP1(s) = degree 6 poly in s\n *\t\tQ1(s) = degree 6 poly in s\n *\n * 3. For x in [1.25,1/0.35(~2.857143)],\n * \terfc(x) = (1/x)*exp(-x*x-0.5625+R1/S1)\n * \terf(x) = 1 - erfc(x)\n *\t where\n *\t\tR1(z) = degree 7 poly in z, (z=1/x^2)\n *\t\tS1(z) = degree 8 poly in z\n *\n * 4. For x in [1/0.35,28]\n * \terfc(x) = (1/x)*exp(-x*x-0.5625+R2/S2) if x > 0\n *\t\t\t= 2.0 - (1/x)*exp(-x*x-0.5625+R2/S2) if -6 x >= 28\n * \terf(x) = sign(x) *(1 - tiny) (raise inexact)\n * \terfc(x) = tiny*tiny (raise underflow) if x > 0\n *\t\t\t= 2 - tiny if x<0\n *\n * 7. Special case:\n * \terf(0) = 0, erf(inf) = 1, erf(-inf) = -1,\n * \terfc(0) = 1, erfc(inf) = 0, erfc(-inf) = 2,\n *\t \terfc/erf(NaN) is NaN\n */\n\n\nstatic const double\n\ntiny = 1e-300,\nhalf = 5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */\none = 1.00000000000000000000e+00, /* 0x3FF00000, 0x00000000 */\ntwo = 2.00000000000000000000e+00, /* 0x40000000, 0x00000000 */\n\nerx = 8.45062911510467529297e-01, /* 0x3FEB0AC1, 0x60000000 */\n/*\n * Coefficients for approximation to erf on [0,0.84375]\n */\nefx = 1.28379167095512586316e-01, /* 0x3FC06EBA, 0x8214DB69 */\nefx8 = 1.02703333676410069053e+00, /* 0x3FF06EBA, 0x8214DB69 */\npp0 = 1.28379167095512558561e-01, /* 0x3FC06EBA, 0x8214DB68 */\npp1 = -3.25042107247001499370e-01, /* 0xBFD4CD7D, 0x691CB913 */\npp2 = -2.84817495755985104766e-02, /* 0xBF9D2A51, 0xDBD7194F */\npp3 = -5.77027029648944159157e-03, /* 0xBF77A291, 0x236668E4 */\npp4 = -2.37630166566501626084e-05, /* 0xBEF8EAD6, 0x120016AC */\nqq1 = 3.97917223959155352819e-01, /* 0x3FD97779, 0xCDDADC09 */\nqq2 = 6.50222499887672944485e-02, /* 0x3FB0A54C, 0x5536CEBA */\nqq3 = 5.08130628187576562776e-03, /* 0x3F74D022, 0xC4D36B0F */\nqq4 = 1.32494738004321644526e-04, /* 0x3F215DC9, 0x221C1A10 */\nqq5 = -3.96022827877536812320e-06, /* 0xBED09C43, 0x42A26120 */\n/*\n * Coefficients for approximation to erf in [0.84375,1.25]\n */\npa0 = -2.36211856075265944077e-03, /* 0xBF6359B8, 0xBEF77538 */\npa1 = 4.14856118683748331666e-01, /* 0x3FDA8D00, 0xAD92B34D */\npa2 = -3.72207876035701323847e-01, /* 0xBFD7D240, 0xFBB8C3F1 */\npa3 = 3.18346619901161753674e-01, /* 0x3FD45FCA, 0x805120E4 */\npa4 = -1.10894694282396677476e-01, /* 0xBFBC6398, 0x3D3E28EC */\npa5 = 3.54783043256182359371e-02, /* 0x3FA22A36, 0x599795EB */\npa6 = -2.16637559486879084300e-03, /* 0xBF61BF38, 0x0A96073F */\nqa1 = 1.06420880400844228286e-01, /* 0x3FBB3E66, 0x18EEE323 */\nqa2 = 5.40397917702171048937e-01, /* 0x3FE14AF0, 0x92EB6F33 */\nqa3 = 7.18286544141962662868e-02, /* 0x3FB2635C, 0xD99FE9A7 */\nqa4 = 1.26171219808761642112e-01, /* 0x3FC02660, 0xE763351F */\nqa5 = 1.36370839120290507362e-02, /* 0x3F8BEDC2, 0x6B51DD1C */\nqa6 = 1.19844998467991074170e-02, /* 0x3F888B54, 0x5735151D */\n/*\n * Coefficients for approximation to erfc in [1.25,1/0.35]\n */\nra0 = -9.86494403484714822705e-03, /* 0xBF843412, 0x600D6435 */\nra1 = -6.93858572707181764372e-01, /* 0xBFE63416, 0xE4BA7360 */\nra2 = -1.05586262253232909814e+01, /* 0xC0251E04, 0x41B0E726 */\nra3 = -6.23753324503260060396e+01, /* 0xC04F300A, 0xE4CBA38D */\nra4 = -1.62396669462573470355e+02, /* 0xC0644CB1, 0x84282266 */\nra5 = -1.84605092906711035994e+02, /* 0xC067135C, 0xEBCCABB2 */\nra6 = -8.12874355063065934246e+01, /* 0xC0545265, 0x57E4D2F2 */\nra7 = -9.81432934416914548592e+00, /* 0xC023A0EF, 0xC69AC25C */\nsa1 = 1.96512716674392571292e+01, /* 0x4033A6B9, 0xBD707687 */\nsa2 = 1.37657754143519042600e+02, /* 0x4061350C, 0x526AE721 */\nsa3 = 4.34565877475229228821e+02, /* 0x407B290D, 0xD58A1A71 */\nsa4 = 6.45387271733267880336e+02, /* 0x40842B19, 0x21EC2868 */\nsa5 = 4.29008140027567833386e+02, /* 0x407AD021, 0x57700314 */\nsa6 = 1.08635005541779435134e+02, /* 0x405B28A3, 0xEE48AE2C */\nsa7 = 6.57024977031928170135e+00, /* 0x401A47EF, 0x8E484A93 */\nsa8 = -6.04244152148580987438e-02, /* 0xBFAEEFF2, 0xEE749A62 */\n/*\n * Coefficients for approximation to erfc in [1/.35,28]\n */\nrb0 = -9.86494292470009928597e-03, /* 0xBF843412, 0x39E86F4A */\nrb1 = -7.99283237680523006574e-01, /* 0xBFE993BA, 0x70C285DE */\nrb2 = -1.77579549177547519889e+01, /* 0xC031C209, 0x555F995A */\nrb3 = -1.60636384855821916062e+02, /* 0xC064145D, 0x43C5ED98 */\nrb4 = -6.37566443368389627722e+02, /* 0xC083EC88, 0x1375F228 */\nrb5 = -1.02509513161107724954e+03, /* 0xC0900461, 0x6A2E5992 */\nrb6 = -4.83519191608651397019e+02, /* 0xC07E384E, 0x9BDC383F */\nsb1 = 3.03380607434824582924e+01, /* 0x403E568B, 0x261D5190 */\nsb2 = 3.25792512996573918826e+02, /* 0x40745CAE, 0x221B9F0A */\nsb3 = 1.53672958608443695994e+03, /* 0x409802EB, 0x189D5118 */\nsb4 = 3.19985821950859553908e+03, /* 0x40A8FFB7, 0x688C246A */\nsb5 = 2.55305040643316442583e+03, /* 0x40A3F219, 0xCEDF3BE6 */\nsb6 = 4.74528541206955367215e+02, /* 0x407DA874, 0xE79FE763 */\nsb7 = -2.24409524465858183362e+01; /* 0xC03670E2, 0x42712D62 */\n\nstatic double ighmm_erf (double x) {\n double R,S,P,Q,s,y,z,r;\n double ax = fabs(x);\n#ifdef HAVE_IEEE754\n if (!isfinite(x)) {\n if (isnan(x)) return x; /* erf(nan)=nan */\n return (x==ax) ? 1 : -1;\t/* erf(+-inf)=+-1 */\n }\n#endif\n if (ax < 0.84375) {\t\t/* |x|<0.84375 */\n if (ax < 3.7252903e-9) { \t/* |x|<2**-28 */\n if (ax < tiny)\n\treturn 0.125*(8.0*x+efx8*x); /*avoid underflow */\n return x + efx*x;\n }\n z = x*x;\n r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));\n s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));\n y = r/s;\n return x + x*y;\n }\n if (ax < 1.25) {\t\t\t/* 0.84375 <= |x| < 1.25 */\n s = ax-one;\n P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));\n Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));\n if (x>=0) return erx + P/Q;\n else return -erx - P/Q;\n }\n if (ax >= 6.0) {\t\t/* inf>|x|>=6 */\n if (x>=0) return one-tiny;\n else return tiny-one;\n }\n s = one/(x*x);\n if (ax < 2.857142857) {\t/* |x| < 1/0.35 */\n R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))));\n S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))));\n }\n else {\t\t/* |x| >= 1/0.35 */\n R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))));\n S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))));\n }\n z = (double)(float) ax;\n r = exp(-z*z-0.5625)*exp((z-ax)*(z+ax)+R/S);\n if (x>=0) return one-r/ax;\n else return r/ax-one;\n}\n\nstatic double ighmm_erfc (double x) {\n double R,S,P,Q,s,y,z,r;\n double ax = fabs(x);\n#ifdef HAVE_IEEE754\n if (!isfinite(x)) {\n if (isnan(x)) return x; /* erfc(nan)=nan */\n return (x==ax) ? 0 : 2;\t/* erfc(+-inf)=0,2 */\n }\n#endif\n if (ax < 0.84375) {\t\t/* |x|<0.84375 */\n if (ax < 13.8777878e-18) \t/* |x|<2**-56 */\n return one-x;\n z = x*x;\n r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));\n s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));\n y = r/s;\n if (ax < 0.25) { \t\t/* x<1/4 */\n return one-(x+x*y);\n }\n else {\n r = x*y;\n r += (x-half);\n return half - r ;\n }\n }\n if (ax < 1.25) {\t\t\t/* 0.84375 <= |x| < 1.25 */\n s = fabs(x)-one;\n P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));\n Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));\n if (x>=0) {\n z = one-erx; return z - P/Q;\n }\n else {\n z = erx+P/Q; return one+z;\n }\n }\n if (ax < 28.0) {\t\t/* |x|<28 */\n s = one/(x*x);\n if (ax < 2.857142857) {\t/* |x| < 1/.35 ~ 2.857143*/\n R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))));\n S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))));\n }\n else {\t\t\t/* |x| >= 1/.35 ~ 2.857143 */\n if (x < -6.0) return two-tiny;/* x < -6 */\n R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))));\n S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))));\n }\n z = (double)(float) ax;\n r = exp(-z*z-0.5625)*exp((z-ax)*(z+ax)+R/S);\n if (x>0) return r/ax;\n else return two-r/ax;\n }\n else {\n if(x>0) return tiny*tiny;\n else return two-tiny;\n }\n}\n#endif /* check for ISO C99 */\n", "meta": {"hexsha": "e56b71e01e7135d101c35b16089a28c183c38051", "size": 33412, "ext": "c", "lang": "C", "max_stars_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/randvar.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/randvar.c", "max_issues_repo_name": "ruslankuzmin/julia", "max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/randvar.c", "max_forks_repo_name": "ruslankuzmin/julia", "max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 30.7944700461, "max_line_length": 118, "alphanum_fraction": 0.5614150605, "num_tokens": 11645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047869292635403, "lm_q2_score": 0.06097517531917227, "lm_q1q2_score": 0.029297272538311176}}
{"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 type_3f1a28e2_0da6_44b6_84db_29542f5a65c0_h\r\n#define type_3f1a28e2_0da6_44b6_84db_29542f5a65c0_h\r\n\r\n#include \r\n#include \r\n#include \r\n\r\n__gslib_begin__\r\n\r\ntemplate\r\nstruct point_t:\r\n public _protopt\r\n{\r\n typedef _ty type;\r\n typedef _protopt proto;\r\n typedef point_t<_ty, _protopt> myref;\r\n\r\npublic:\r\n point_t() { this->x = 0; this->y = 0; }\r\n point_t(const proto& p): proto(p) {}\r\n point_t(type a, type b) { this->x = a; this->y = b; }\r\n void offset(type u, type v) { this->x += u; this->y += v; }\r\n void offset(const proto& p) { this->x += p.x; this->y += p.y; }\r\n void set_point(type a, type b) { this->x = a; this->y = b; }\r\n bool operator == (const myref& that) const { return this->x == that.x && this->y == that.y; }\r\n bool operator != (const myref& that) const { return this->x != that.x || this->y != that.y; }\r\n};\r\n\r\nstruct vec2i { int x, y; };\r\ntypedef point_t point;\r\ntypedef point_t pointf;\r\n\r\ntemplate\r\nstruct rect_t\r\n{\r\n typedef _ty type;\r\n typedef rect_t<_ty, _ptcls> myref;\r\n typedef _ptcls point;\r\n\r\npublic:\r\n type left, top, right, bottom;\r\n\r\npublic:\r\n rect_t()\r\n {\r\n left = 0;\r\n top = 0;\r\n right = 0;\r\n bottom = 0;\r\n }\r\n rect_t(type l, type t, type w, type h) { set_rect(l, t, w, h); }\r\n type width() const { return right - left; }\r\n type height() const { return bottom - top; }\r\n void set_rect(type l, type t, type w, type h)\r\n {\r\n left = l;\r\n top = t;\r\n right = l + w;\r\n bottom = t + h;\r\n }\r\n void set_ltrb(type l, type t, type r, type b)\r\n {\r\n left = l;\r\n top = t;\r\n right = r;\r\n bottom = b;\r\n }\r\n void set_by_pts(const point& p1, const point& p2)\r\n {\r\n left = gs_min(p1.x, p2.x);\r\n top = gs_min(p1.y, p2.y);\r\n right = gs_max(p1.x, p2.x);\r\n bottom = gs_max(p1.y, p2.y);\r\n }\r\n bool in_rect(const point& pt) const { return pt.x >= left && pt.x < right && pt.y >= top && pt.y < bottom; }\r\n void offset(type x, type y) { left += x; right += x; top += y; bottom += y; }\r\n void deflate(type u, type v);\r\n void move_to(const point& pt) { move_to(pt.x, pt.y); }\r\n void move_to(type x, type y);\r\n bool operator == (const myref& that) const { return left == that.left && right == that.right && top == that.top && bottom == that.bottom; }\r\n bool operator != (const myref& that) const { return left != that.left || right != that.right || top != that.top || bottom != that.bottom; }\r\n type area() const { return width() * height(); }\r\n point center() const\r\n {\r\n point c;\r\n c.x = (left + right) / 2;\r\n c.y = (top + bottom) / 2;\r\n return c;\r\n }\r\n point top_left() const { return point(left, top); }\r\n point top_right() const { return point(right, top); }\r\n point bottom_left() const { return point(left, bottom); }\r\n point bottom_right() const { return point(right, bottom); }\r\n};\r\n\r\ntypedef rect_t rect;\r\ntypedef rect_t rectf;\r\n\r\ninline rectf to_rectf(const rect& rc)\r\n{\r\n return std::move(rectf((float)rc.left, (float)rc.top, (float)rc.width(), (float)rc.height()));\r\n}\r\n\r\ninline rect to_aligned_rect(const rectf& rc)\r\n{\r\n return std::move(rect(round(rc.left), round(rc.top), round(rc.width()), round(rc.height())));\r\n}\r\n\r\ngs_export extern bool intersect_rect(rect& rc, const rect& rc1, const rect& rc2);\r\ngs_export extern bool is_rect_intersected(const rect& rc1, const rect& rc2);\r\ngs_export extern void union_rect(rect& rc, const rect& rc1, const rect& rc2);\r\ngs_export extern bool substract_rect(rect& rc, const rect& rc1, const rect& rc2);\r\ngs_export extern bool intersect_rect(rectf& rc, const rectf& rc1, const rectf& rc2);\r\ngs_export extern bool is_rect_intersected(const rectf& rc1, const rectf& rc2);\r\ngs_export extern bool is_rect_contained(const rect& rc1, const rect& rc2);\r\ngs_export extern bool is_rect_contained(const rectf& rc1, const rectf& rc2);\r\ngs_export extern void union_rect(rectf& rc, const rectf& rc1, const rectf& rc2);\r\ngs_export extern bool substract_rect(rectf& rc, const rectf& rc1, const rectf& rc2);\r\ngs_export extern bool is_line_rect_overlapped(const point& p1, const point& p2, const rect& rc);\r\ngs_export extern bool is_line_rect_overlapped(const pointf& p1, const pointf& p2, const rectf& rc);\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "46174f5fa068275d52a85c8ffc77be91f6045a3c", "size": 5773, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/type.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/type.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/type.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": 37.9802631579, "max_line_length": 144, "alphanum_fraction": 0.6429932444, "num_tokens": 1601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.06465348520228963, "lm_q1q2_score": 0.028555698185686908}}
{"text": "/*\r\nThis file is a part of NNTL project (https://github.com/Arech/nntl)\r\n\r\nCopyright (c) 2015-2021, Arech (aradvert@gmail.com; https://github.com/Arech)\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are met:\r\n\r\n* Redistributions of source code must retain the above copyright notice, this\r\n list of conditions and the following disclaimer.\r\n\r\n* Redistributions in binary form must reproduce the above copyright notice,\r\n this list of conditions and the following disclaimer in the documentation\r\n and/or other materials provided with the distribution.\r\n\r\n* Neither the name of NNTL nor the names of its\r\n contributors may be used to endorse or promote products derived from\r\n this software without specific prior written permission.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\r\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n*/\r\n#pragma once\r\n\r\n#include \r\n//TODO: function definitions (like dgemm()) conflicts with similar function definitions in ACML. It builds successfully, but\r\n//links to wrong library and access violation happens in run-time.\r\n\r\n#include \r\n#define lapack_complex_float ::std::complex\r\n#define lapack_complex_double ::std::complex\r\n#include \r\n\r\n//#include \"../../../utils/denormal_floats.h\"\r\n\r\n#pragma comment(lib,\"libopenblas.dll.a\")\r\n\r\n//what else to do to use OpenBLAS:\r\n// -in the Solution's VC++ Directories property page set parameter Library Directories to point to a folder with the libopenblas.dll.a file\r\n// -copy correct libopenblas.dll and another dlls that the libopenblas.dll require to the debug/release solution's folder\r\n// -if you're going to use any calling convetion except for __cdecl, then most likely, you'll have to update function declarations\r\n//\t\twithin the cblas.h and other blas's .h files included to contain the __cdecl keyword (it's absent for some reason).\r\n//\t\tCheck the b_OpenBLAS:: methods to find out which function definitions should be changed.\r\n\r\n\r\n//http://www.christophlassner.de/using-blas-from-c-with-row-major-data.html\r\n\r\n// BTW: lda,ldb,ldc is a \"major stride\". The stride represents the distance in memory between elements in adjacent rows\r\n// (if row-major) or in adjacent columns (if column-major). This means that the stride is usually equal to the number\r\n// of rows/columns in the matrix.\r\n// Matrix A = [1 2 3]\r\n// [4 5 6]\r\n// Row-major stores values as {1,2,3,4,5,6} Stride here is 3\r\n// Col-major stores values as {1,4,2,5,3,6} Stride here is 2\r\n// (https://www.physicsforums.com/threads/understanding-blas-dgemm-in-c.543110/)\r\n\r\n\r\n\r\nnamespace nntl {\r\nnamespace math {\r\n\r\n\t// wrapper around BLAS API. Should at least isolate from double/float differences\r\n\t// Also, we are going to use ColMajor ordering in all math libraries (most of them use it by default)\r\n\t// EXPECTING data to be in COL-MAJOR mode!\r\n\t// \r\n\t// NB: Leading dimension is the number of elements in major dimension. We're using Col-Major ordering,\r\n\t// therefore it is the number of ROWs of a matrix\r\n\tstruct b_OpenBLAS {\r\n\tprivate:\r\n\t\ttypedef utils::_scoped_restore_FPU _restoreFPU;\r\n\tpublic:\r\n\t\t//TODO: beware that sz_t type used as substitution of blasint can overflow blasint and silencing conversion warnings here can make it difficult to debug!\r\n\t\t//TODO: May be there should be some preliminary check for this condition.\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// LEVEL 1\r\n\t\t// AXPY y=a*x+y\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, double>::value > axpy(\r\n\t\t\tconst sz_t n, const fl_t alpha, const fl_t *x, const sz_t incx, fl_t *y, const sz_t incy)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_daxpy(static_cast(n), alpha, x, static_cast(incx), y, static_cast(incy));\r\n\t\t}\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, float>::value > axpy(\r\n\t\t\tconst sz_t n, const fl_t alpha, const fl_t *x, const sz_t incx, fl_t *y, const sz_t incy)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_saxpy(static_cast(n), alpha, x, static_cast(incx), y, static_cast(incy));\r\n\t\t}\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// cblas_?dot\r\n\t\t// Computes a vector - vector dot product.\r\n\t\t//\tInput Parameters\r\n\t\t// n - Specifies the number of elements in vectors x and y.\r\n\t\t// x - Array, size at least(1 + (n - 1)*abs(incx)).\r\n\t\t// incx - Specifies the increment for the elements of x.\r\n\t\t// y - Array, size at least(1 + (n - 1)*abs(incy)).\r\n\t\t// incy - Specifies the increment for the elements of y.\r\n\t\t// Return Values - The result of the dot product of x and y, if n is positive.Otherwise, returns 0.\r\n\t\t//https://software.intel.com/en-us/mkl-developer-reference-c-cblas-dot\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, double>::value, double >\r\n\t\t\tdot(const sz_t n, const fl_t *x, const sz_t incx, const fl_t *y, const sz_t incy)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\treturn cblas_ddot(static_cast(n), x, static_cast(incx), y, static_cast(incy));\r\n\t\t}\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, float>::value, float >\r\n\t\t\tdot(const sz_t n, const fl_t *x, const sz_t incx, const fl_t *y, const sz_t incy)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\treturn cblas_sdot(static_cast(n), x, static_cast(incx), y, static_cast(incy));\r\n\t\t}\r\n\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// LEVEL 2\r\n\r\n\t\t\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// LEVEL 3\r\n\t\t// \r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// General matrix multiplication\r\n\t\t// GEMM C := alpha*op(A)*op(B) + beta*C\r\n\t\t// https://software.intel.com/en-us/node/520775\r\n\t\t// where:\r\n\t\t// op(X) is one of op(X) = X, or op(X) = XT, or op(X) = XH,\r\n\t\t// alpha and beta are scalars,\r\n\t\t// A, B and C are matrices :\r\n\t\t// op(A) is an m - by - k matrix,\r\n\t\t// op(B) is a k - by - n matrix,\r\n\t\t// C is an m - by - n matrix.\r\n\t\t// \r\n\t\t// M - Specifies the number of rows of the matrix op(A) and of the matrix C. The value of m must be at least zero.\r\n\t\t// N - Specifies the number of columns of the matrix op(B) and the number of columns of the matrix C. The value of n must be at least zero.\r\n\t\t// K - Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). The value of k must be at least zero.\r\n\t\t// A - {transa=CblasNoTrans : Array, size lda*k. Before entry, the leading m-by-k part of the array a must contain the matrix A.\r\n\t\t//\t\ttransa=CblasTrans : Array, size lda*m. Before entry, the leading k-by-m part of the array a must contain the matrix A.}\r\n\t\t// lda - Specifies the leading dimension of A as declared in the calling (sub)program.\r\n\t\t//\t\t{transa=CblasNoTrans, lda must be at least max(1, m).\r\n\t\t//\t\ttransa=CblasTrans, lda must be at least max(1, k)}\r\n\t\t// B - {transb=CblasNoTrans : Array, size ldb by n. Before entry, the leading k-by-n part of the array b must contain the matrix B.\r\n\t\t//\t\ttransb=CblasTrans : Array, size ldb by k. Before entry the leading n-by-k part of the array b must contain the matrix B.}\r\n\t\t// ldb - Specifies the leading dimension of B as declared in the calling (sub)program.\r\n\t\t//\t\t{transb = CblasNoTrans : ldb must be at least max(1, k).\r\n\t\t//\t\ttransb=CblasTrans : ldb must be at least max(1, n).}\r\n\t\t// C - Array, size ldc by n. Before entry, the leading m-by-n part of the array c must contain the matrix C, except when beta is\r\n\t\t//\t\tequal to zero, in which case c need not be set on entry.\r\n\t\t// ldc - Specifies the leading dimension of c as declared in the calling (sub)program. ldc must be at least max(1, m).\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, double>::value >\r\n\t\t\tgemm( //const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB,\r\n\t\t\tconst bool bTransposeA, const bool bTransposeB,\r\n\t\t\tconst sz_t M, const sz_t N, const sz_t K, const fl_t alpha, const fl_t *A, const sz_t lda,\r\n\t\t\tconst fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_dgemm(CblasColMajor, bTransposeA ? CblasTrans : CblasNoTrans, bTransposeB ? CblasTrans : CblasNoTrans,\r\n\t\t\t\tstatic_cast(M), static_cast(N), static_cast(K),\r\n\t\t\t\talpha, A, static_cast(lda), B, static_cast(ldb), beta, C, static_cast(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, float>::value >\r\n\t\t\tgemm( //const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB,\r\n\t\t\tconst bool bTransposeA, const bool bTransposeB,\r\n\t\t\tconst sz_t M, const sz_t N, const sz_t K, const fl_t alpha, const fl_t *A, const sz_t lda,\r\n\t\t\tconst fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_sgemm(CblasColMajor, bTransposeA ? CblasTrans: CblasNoTrans, bTransposeB ? CblasTrans : CblasNoTrans,\r\n\t\t\t\tstatic_cast(M), static_cast(N), static_cast(K),\r\n\t\t\t\talpha, A, static_cast(lda), B, static_cast(ldb), beta, C, static_cast(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// cblas_?syrk, https://software.intel.com/en-us/node/520780\r\n\t\t// Performs a symmetric rank-k update.\r\n\t\t// The ?syrk routines perform a rank-k matrix-matrix operation for a symmetric matrix C using a general matrix A.\r\n\t\t// The operation is defined as:\r\n\t\t// C := alpha*A*A' + beta*C,\r\n\t\t//\t\tor\r\n\t\t// C : = alpha*A'*A + beta*C,\r\n\t\t// where :\r\n\t\t//\t\talpha and beta are scalars,\r\n\t\t//\t\tC is an n-by-n symmetric matrix,\r\n\t\t//\t\tA is an n-by-k matrix in the first case and a k-by-n matrix in the second case.\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, double>::value >\r\n\t\t\tsyrk( const bool bCLowerTriangl, const bool bFirstATransposed, const sz_t N, const sz_t K, const fl_t alpha\r\n\t\t\t\t, const fl_t *A, const sz_t lda, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_dsyrk(CblasColMajor, bCLowerTriangl ? CblasLower : CblasUpper, bFirstATransposed ? CblasTrans : CblasNoTrans\r\n\t\t\t\t, static_cast(N), static_cast(K), alpha, A, static_cast(lda), beta, C, static_cast(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, float>::value >\r\n\t\t\tsyrk(const bool bCLowerTriangl, const bool bFirstATransposed, const sz_t N, const sz_t K, const fl_t alpha\r\n\t\t\t\t, const fl_t *A, const sz_t lda, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_ssyrk(CblasColMajor, bCLowerTriangl ? CblasLower : CblasUpper, bFirstATransposed ? CblasTrans : CblasNoTrans\r\n\t\t\t\t, static_cast(N), static_cast(K), alpha, A, static_cast(lda), beta, C, static_cast(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// cblas_?symm, https://software.intel.com/en-us/node/520779\r\n\t\t// Computes a matrix - matrix product where one input matrix is symmetric.\r\n\t\t// The ?symm routines compute a scalar-matrix-matrix product with one symmetric matrix and add the\r\n\t\t// result to a scalar-matrix product. The operation is defined as\r\n\t\t// C: = alpha*A*B + beta*C,\r\n\t\t//\t\tor\r\n\t\t// C : = alpha*B*A + beta*C,\r\n\t\t// where :\r\n\t\t//\t\talpha and beta are scalars,\r\n\t\t//\t\tA is a symmetric matrix,\r\n\t\t//\t\tB and C are m - by - n matrices.\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, double>::value >\r\n\t\t\tsymm(const bool bSymmAatLeft, const bool bALowerTriangl, const sz_t M, const sz_t N, const fl_t alpha\r\n\t\t\t\t, const fl_t *A, const sz_t lda, const fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_dsymm(CblasColMajor, bSymmAatLeft ? CblasLeft : CblasRight, bALowerTriangl ? CblasLower : CblasUpper\r\n\t\t\t\t, static_cast(M), static_cast(N), alpha, A, static_cast(lda)\r\n\t\t\t\t, B, static_cast(ldb), beta, C, static_cast(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, float>::value >\r\n\t\t\tsymm(const bool bSymmAatLeft, const bool bALowerTriangl, const sz_t M, const sz_t N, const fl_t alpha\r\n\t\t\t\t, const fl_t *A, const sz_t lda, const fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\tcblas_ssymm(CblasColMajor, bSymmAatLeft ? CblasLeft : CblasRight, bALowerTriangl ? CblasLower : CblasUpper\r\n\t\t\t\t, static_cast(M), static_cast(N), alpha, A, static_cast(lda)\r\n\t\t\t\t, B, static_cast(ldb), beta, C, static_cast(ldc));\r\n\t\t\t//global_denormalized_floats_mode();\r\n\t\t}\r\n\r\n\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t// LAPACKE\r\n\r\n\t\t// ?gesvd\r\n\t\t// https://software.intel.com/en-us/node/521150\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, double>::value, int>\r\n\t\t\tgesvd(/*int matrix_layout,*/ const char jobu, const char jobvt,\r\n\t\t\t\tconst sz_t m, const sz_t n, fl_t* A,\r\n\t\t\t\tconst sz_t lda, fl_t* S, fl_t* U, const sz_t ldu,\r\n\t\t\t\tfl_t* Vt, const sz_t ldvt, fl_t* superb)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\treturn static_cast(LAPACKE_dgesvd(LAPACK_COL_MAJOR, jobu, jobvt, static_cast(m), static_cast(n)\r\n\t\t\t\t, A, static_cast(lda), S, U, static_cast(ldu), Vt, static_cast(ldvt), superb));\r\n\t\t}\r\n\t\ttemplate\r\n\t\tstatic typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t, float>::value, int>\r\n\t\t\tgesvd(/*int matrix_layout,*/ const char jobu, const char jobvt,\r\n\t\t\t\tconst sz_t m, const sz_t n, fl_t* A,\r\n\t\t\t\tconst sz_t lda, fl_t* S, fl_t* U, const sz_t ldu,\r\n\t\t\t\tfl_t* Vt, const sz_t ldvt, fl_t* superb)\r\n\t\t{\r\n\t\t\t_restoreFPU r;\r\n\t\t\treturn static_cast(LAPACKE_sgesvd(LAPACK_COL_MAJOR, jobu, jobvt, static_cast(m), static_cast(n)\r\n\t\t\t\t, A, static_cast(lda), S, U, static_cast(ldu), Vt, static_cast