{"text": "/* poly/solve_quadratic.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* solve_quadratic.c - finds the real roots of a x^2 + b x + c = 0 */\n\n#include \n#include \n\n#include \n\nint \ngsl_poly_solve_quadratic (double a, double b, double c, \n double *x0, double *x1)\n{\n double disc = b * b - 4 * a * c;\n\n if (a == 0) /* Handle linear case */\n {\n if (b == 0)\n {\n return 0;\n }\n else\n {\n *x0 = -c / b;\n return 1;\n };\n }\n\n if (disc > 0)\n {\n if (b == 0)\n {\n double r = fabs (0.5 * sqrt (disc) / a);\n *x0 = -r;\n *x1 = r;\n }\n else\n {\n double sgnb = (b > 0 ? 1 : -1);\n double temp = -0.5 * (b + sgnb * sqrt (disc));\n double r1 = temp / a ;\n double r2 = c / temp ;\n\n if (r1 < r2) \n {\n *x0 = r1 ;\n *x1 = r2 ;\n } \n else \n {\n *x0 = r2 ;\n *x1 = r1 ;\n }\n }\n return 2;\n }\n else if (disc == 0) \n {\n *x0 = -0.5 * b / a ;\n *x1 = -0.5 * b / a ;\n return 2 ;\n }\n else\n {\n return 0;\n }\n}\n\n", "meta": {"hexsha": "8af69dbe6baa1476654e95138a9a000b2c82efc8", "size": 2001, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/poly/solve_quadratic.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/poly/solve_quadratic.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/poly/solve_quadratic.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 23.2674418605, "max_line_length": 81, "alphanum_fraction": 0.4982508746, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7488840299240829}} {"text": "#include \n#include \n#include \n\nint\nmain (void)\n{\n double data[] = { 1.0 , 1/2.0, 1/3.0, 1/4.0,\n 1/2.0, 1/3.0, 1/4.0, 1/5.0,\n 1/3.0, 1/4.0, 1/5.0, 1/6.0,\n 1/4.0, 1/5.0, 1/6.0, 1/7.0 };\n\n gsl_matrix_view m \n = gsl_matrix_view_array (data, 4, 4);\n\n gsl_vector *eval = gsl_vector_alloc (4);\n gsl_matrix *evec = gsl_matrix_alloc (4, 4);\n\n gsl_eigen_symmv_workspace * w = \n gsl_eigen_symmv_alloc (4);\n \n gsl_eigen_symmv (&m.matrix, eval, evec, w);\n\n gsl_eigen_symmv_free (w);\n\n gsl_eigen_symmv_sort (eval, evec, \n GSL_EIGEN_SORT_ABS_ASC);\n \n {\n int i;\n\n for (i = 0; i < 4; i++)\n {\n double eval_i \n = gsl_vector_get (eval, i);\n gsl_vector_view evec_i \n = gsl_matrix_column (evec, i);\n\n printf (\"eigenvalue = %g\\n\", eval_i);\n printf (\"eigenvector = \\n\");\n gsl_vector_fprintf (stdout, \n &evec_i.vector, \"%g\");\n }\n }\n\n gsl_vector_free (eval);\n gsl_matrix_free (evec);\n\n return 0;\n}\n", "meta": {"hexsha": "a24c912fce7b7dea2b5714fff9fd8c6d583a9f2a", "size": 1114, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/eigen.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/eigen.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/eigen.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 21.8431372549, "max_line_length": 50, "alphanum_fraction": 0.526032316, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7472984841453993}} {"text": "#include \n#include \n#include \n#include \"sphere.h\"\n#include \n#undef __FUNCT__\n#define __FUNCT__ \"CartesianToSpherical\"\nPetscErrorCode CartesianToSpherical(Vec xyz, Vec sph)\n{\n PetscErrorCode ierr;\n PetscScalar *xyzPt, *sphPt;\n PetscInt size;\n PetscReal x, y, z, r, theta, phi;\n PetscFunctionBegin;\n //get size of xyz vec\n ierr = VecGetSize(xyz, &size);CHKERRQ(ierr);\n \n ierr = VecGetArrayRead(xyz, &xyzPt);CHKERRQ(ierr);\n ierr = VecGetArray(sph, &sphPt);CHKERRQ(ierr);\n for(PetscInt k=0; k0) sphPt[3*k+1] = theta;\n \n }\n ierr = VecRestoreArray(sph, &sphPt);CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(xyz, &xyzPt);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\nvoid cartesianToSpherical(SPoint *point) {\n \n double r, theta, phi;\n\n r = sqrt((point->x1)*(point->x1) + (point->x2)*(point->x2) + (point->x3)*(point->x3)); \n theta = acos(point->x3/r);\n phi = atan2((point->x2),(point->x1));\n\n point->x1 = r;\n point->x2 = 0;\n point->x3 = phi;\n\n if(r > 0) point->x2 = theta;\n\n point->type = 's';\n}\n\nvoid sphericalToCartesian(SPoint *point) {\n double r = point->x1;\n double theta = point->x2;\n double phi = point->x3;\n\n double x = r*sin(theta)*cos(phi);\n double y = r*sin(theta)*sin(phi);\n double z = r*cos(theta);\n\n point->x1 = x;\n point->x2 = y;\n point->x3 = z;\n}\n", "meta": {"hexsha": "479dbfaaf5234ce91d0eeaa974e85e2b57e44888", "size": 1637, "ext": "c", "lang": "C", "max_stars_repo_path": "src/sphere/sphere.c", "max_stars_repo_name": "tom-klotz/ellipsoid-solvation", "max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z", "max_issues_repo_path": "src/sphere/sphere.c", "max_issues_repo_name": "tom-klotz/ellipsoid-solvation", "max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sphere/sphere.c", "max_forks_repo_name": "tom-klotz/ellipsoid-solvation", "max_forks_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3857142857, "max_line_length": 90, "alphanum_fraction": 0.6108735492, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7469541205451125}} {"text": "\r\n#include \r\n#include \r\n\r\nint main (void)\r\n{\r\n int n = 11;\r\n double x[11] = {10.0, 8.0, 13.0, 9.0,11.0,14.0,6.0,4.0 ,12.0,7.0,5.0};\r\n double y[11] = { 8.04, 6.95,7.68, 8.81, 8.33,9.96,7.24,4.26,10.84,4.82,5.68 };\r\n\r\n double c0, c1, cov00, cov01, cov11, sumsq;\r\n\r\n gsl_fit_linear (x, 1, y, 1, n,\r\n &c0, &c1, &cov00, &cov01, &cov11,\r\n &sumsq);\r\n\r\n printf (\"best fit: Y = %g + %g X\\n\", c0, c1);\r\n printf (\"covariance matrix:\\n\");\r\n printf (\"[ %g, %g\\n %g, %g]\\n\",\r\n cov00, cov01, cov01, cov11);\r\n printf (\"sumsq = %g\\n\", sumsq);\r\n\r\n printf (\"\\n\");\r\n\r\n return 0;\r\n}\r\n", "meta": {"hexsha": "a8a3dcbff72d2790cd1122987f206ceff1949d63", "size": 646, "ext": "c", "lang": "C", "max_stars_repo_path": "notebook/demo/src/demo_fit.c", "max_stars_repo_name": "marketmodelbrokendown/1", "max_stars_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebook/demo/src/demo_fit.c", "max_issues_repo_name": "marketmodelbrokendown/1", "max_issues_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-18T21:55:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-18T21:55:20.000Z", "max_forks_repo_path": "notebook/demo/src/demo_fit.c", "max_forks_repo_name": "marketmodelbrokendown/1", "max_forks_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9259259259, "max_line_length": 83, "alphanum_fraction": 0.4783281734, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250325, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7439828825537597}} {"text": "#include \n#include \n#include \n#include \n\nint DEBUG = 1;\nint DEBUG_SOLUTION = 1;\nint STORE_TIMING = 0;\n\nFILE* decompFile;\nFILE* solveFile;\n\ndouble* generateVector(int size)\n{\n double* vec = calloc(sizeof(double), size);\n for (int i = 0; i < size; ++i){\n double val = (double)rand() / RAND_MAX; // double [0, 1]\n vec[i] = val;\n }\n return vec;\n}\n\nvoid printMatrix(double* m, int size)\n{\n for (int i = 0; i < size; ++i){\n for (int j = 0; j < size; ++j){\n printf(\"%g \", m[j + i * size]);\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n\nvoid printVector(double* v, int size)\n{\n for (int i = 0; i < size; ++i){\n printf(\"%g\", v[i]);\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n\ndouble* copyVector(double* src, int size)\n{\n double* vec = calloc(sizeof(double), size);\n for (int i = 0; i < size; ++i){\n vec[i] = src[i];\n }\n return vec;\n}\n\nvoid checkSolution(double* m, double* b, gsl_vector x, int size)\n{\n const double epsilon = 0.0001;\n int failures = 0;\n\n for (int i = 0; i < size; ++i){\n double sum = 0;\n for (int j = 0; j < size; ++j){\n sum += m[j + i * size] * x.data[j];\n // printf(\"%g * %g = %g\\n\", m[j + i * size], x.data[j], m[j + i * size] * x.data[j]);\n }\n if (abs(sum - b[i]) > epsilon){\n failures++;\n if (DEBUG_SOLUTION){\n printf(\"Wrong solution was calculated: %g --- %g\\n\", sum, b[i]);\n printf(\"\\n\");\n }\n }\n }\n if (DEBUG_SOLUTION){\n if (failures == 0){\n printf(\"All calculated values were correct\");\n } else {\n printf(\"Total %n errors in calculated value\", failures);\n }\n printf(\"\\n\");\n }\n}\n\nvoid decomp(gsl_matrix *A, gsl_permutation* p, int *signum, int size)\n{\n clock_t start = clock();\n gsl_linalg_LU_decomp(A, p, signum);\n clock_t end = clock();\n\n double t = ((double) (end - start)) / CLOCKS_PER_SEC;\n if (STORE_TIMING) fprintf (decompFile,\"%d %g\\n\", size, t);\n}\n\nvoid solve(const gsl_matrix* LU, const gsl_permutation* p, const gsl_vector* b, gsl_vector* x, int size)\n{\n clock_t start = clock();\n gsl_linalg_LU_solve(LU, p, b, x);\n clock_t end = clock();\n\n double t = ((double) (end - start)) / CLOCKS_PER_SEC;\n if (STORE_TIMING) fprintf (solveFile,\"%d %g\\n\", size, t);\n}\n\nvoid calculate(int n)\n{\n double* a_data = generateVector(n * n);\n double* b_data = generateVector(n);\n\n double* originalMatrix = copyVector(a_data, n * n);\n\n gsl_matrix_view m = gsl_matrix_view_array(a_data, n, n);\n gsl_vector_view b = gsl_vector_view_array(b_data, n);\n\n if (DEBUG){\n printf(\"Matrix M:\\n\");\n printMatrix(a_data, n);\n\n printf(\"Vector B:\\n\");\n printVector(b_data, n);\n }\n gsl_vector *x = gsl_vector_alloc(n);\n int s;\n \n gsl_permutation *p = gsl_permutation_alloc(n);\n\n decomp(&m.matrix, p, &s, n);\n solve(&m.matrix, p, &b.vector, x, n);\n\n if (DEBUG){\n printf(\"Solution X:\\n\");\n gsl_vector_fprintf(stdout, x, \"%g\");\n printf(\"\\n\");\n }\n checkSolution(originalMatrix, b_data, *x, n);\n\n gsl_permutation_free(p);\n gsl_vector_free(x);\n}\n\nint main(int argc, char* argv[])\n{\n if (argc != 2){\n return -1;\n }\n char *pEnd;\n int n = strtol(argv[1], &pEnd, 0);\n\n srand(time(NULL));\n decompFile = fopen(\"decomp.txt\", \"w\");\n solveFile = fopen(\"solve.txt\", \"w\");\n\n if (n == 0){\n return -1;\n } else if (n < 0){\n DEBUG = 0;\n DEBUG_SOLUTION = 0;\n STORE_TIMING = 1;\n for (int i = 10; i <= 1000; i+=10){\n calculate(i);\n }\n } else {\n calculate(n);\n }\n\n return 0;\n}", "meta": {"hexsha": "a0968b6fa47972b02dd26ad87f25ab77128575b1", "size": 3805, "ext": "c", "lang": "C", "max_stars_repo_path": "zad6/linear.c", "max_stars_repo_name": "komilll/mownit_linux", "max_stars_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "zad6/linear.c", "max_issues_repo_name": "komilll/mownit_linux", "max_issues_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "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": "zad6/linear.c", "max_forks_repo_name": "komilll/mownit_linux", "max_forks_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3435582822, "max_line_length": 104, "alphanum_fraction": 0.5272010512, "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7404057994293768}} {"text": "#ifndef ROUNDING_H_ZL4GHC5J\n#define ROUNDING_H_ZL4GHC5J\n\n#include \n#include \n#include \n\nnamespace sens_loc::math {\n\n/// Round the value \\c val to the nth \\c digit.\n///\n/// \\tparam Number arithmetic type that represents a number\n/// \\param val number to be rounded\n/// \\param digit The decimal digit the number shall be rounded to. Positive\n/// values indicate the position behind the comma for rational numbers, a\n/// negative number indicates a position before the comma.\n/// \\pre \\c std::is_arithmetic_v\n/// \\post the result is rounded to the nth digit\n/// \\post \\f$digit == 0 => result == val\\f$\n/// \\post \\f$!std::isfinite(val) => result == val\\f$\n/// \\code\n/// roundn(10.055, 2) == 10.06;\n/// roundn(10.055, 0) == 10.055;\n/// roundn(10.055, -1) == 10.00;\n/// roundn(1052.4, -2) == 1100.0;\n/// roundn(1052, -2) == 1100;\n/// roundn(1052, 2) == 1052;\n/// \\endcode\ntemplate \nNumber roundn(Number val, int digit) noexcept {\n static_assert(std::is_arithmetic_v);\n\n if (digit == 0)\n return val;\n\n if constexpr (std::is_floating_point_v) {\n if (!std::isfinite(val))\n return val;\n Number potence_10 = std::pow(Number(10), digit);\n return std::round(val * potence_10) / potence_10;\n } else {\n double potence_10 = std::pow(10., digit);\n double rounded = std::round(val * potence_10) / potence_10;\n return Number(std::round(rounded));\n }\n}\n\n} // namespace sens_loc::math\n\n#endif /* end of include guard: ROUNDING_H_ZL4GHC5J */\n", "meta": {"hexsha": "d1980e3b2a2c25400c3350282896daf31e1374ef", "size": 1569, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/sens_loc/math/rounding.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/include/sens_loc/math/rounding.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/sens_loc/math/rounding.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7647058824, "max_line_length": 75, "alphanum_fraction": 0.6462715105, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7397330033363487}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* number of data points to fit */\n#define N 40\n\nstruct data {\n size_t n;\n double * y;\n};\n\nint\nexpb_f (const gsl_vector * x, void *data, \n gsl_vector * f)\n{\n size_t n = ((struct data *)data)->n;\n double *y = ((struct data *)data)->y;\n\n double A = gsl_vector_get (x, 0);\n double lambda = gsl_vector_get (x, 1);\n double b = gsl_vector_get (x, 2);\n\n size_t i;\n\n for (i = 0; i < n; i++)\n {\n /* Model Yi = A * exp(-lambda * i) + b */\n double t = i;\n double Yi = A * exp (-lambda * t) + b;\n gsl_vector_set (f, i, Yi - y[i]);\n }\n\n return GSL_SUCCESS;\n}\n\nint\nexpb_df (const gsl_vector * x, void *data, \n gsl_matrix * J)\n{\n size_t n = ((struct data *)data)->n;\n\n double A = gsl_vector_get (x, 0);\n double lambda = gsl_vector_get (x, 1);\n\n size_t i;\n\n for (i = 0; i < n; i++)\n {\n /* Jacobian matrix J(i,j) = dfi / dxj, */\n /* where fi = (Yi - yi)/sigma[i], */\n /* Yi = A * exp(-lambda * i) + b */\n /* and the xj are the parameters (A,lambda,b) */\n double t = i;\n double e = exp(-lambda * t);\n gsl_matrix_set (J, i, 0, e); \n gsl_matrix_set (J, i, 1, -t * A * e);\n gsl_matrix_set (J, i, 2, 1.0);\n }\n return GSL_SUCCESS;\n}\n\nvoid\ncallback(const size_t iter, void *params,\n const gsl_multifit_nlinear_workspace *w)\n{\n gsl_vector *f = gsl_multifit_nlinear_residual(w);\n gsl_vector *x = gsl_multifit_nlinear_position(w);\n double rcond;\n\n /* compute reciprocal condition number of J(x) */\n gsl_multifit_nlinear_rcond(&rcond, w);\n\n fprintf(stderr, \"iter %2zu: A = %.4f, lambda = %.4f, b = %.4f, cond(J) = %8.4f, |f(x)| = %.4f\\n\",\n iter,\n gsl_vector_get(x, 0),\n gsl_vector_get(x, 1),\n gsl_vector_get(x, 2),\n 1.0 / rcond,\n gsl_blas_dnrm2(f));\n}\n\nint\nmain (void)\n{\n const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust;\n gsl_multifit_nlinear_workspace *w;\n gsl_multifit_nlinear_fdf fdf;\n gsl_multifit_nlinear_parameters fdf_params =\n gsl_multifit_nlinear_default_parameters();\n const size_t n = N;\n const size_t p = 3;\n\n gsl_vector *f;\n gsl_matrix *J;\n gsl_matrix *covar = gsl_matrix_alloc (p, p);\n double y[N], weights[N];\n struct data d = { n, y };\n double x_init[3] = { 1.0, 1.0, 0.0 }; /* starting values */\n gsl_vector_view x = gsl_vector_view_array (x_init, p);\n gsl_vector_view wts = gsl_vector_view_array(weights, n);\n gsl_rng * r;\n double chisq, chisq0;\n int status, info;\n size_t i;\n\n const double xtol = 1e-8;\n const double gtol = 1e-8;\n const double ftol = 0.0;\n\n gsl_rng_env_setup();\n r = gsl_rng_alloc(gsl_rng_default);\n\n /* define the function to be minimized */\n fdf.f = expb_f;\n fdf.df = expb_df; /* set to NULL for finite-difference Jacobian */\n fdf.fvv = NULL; /* not using geodesic acceleration */\n fdf.n = n;\n fdf.p = p;\n fdf.params = &d;\n\n /* this is the data to be fitted */\n for (i = 0; i < n; i++)\n {\n double t = i;\n double yi = 1.0 + 5 * exp (-0.1 * t);\n double si = 0.1 * yi;\n double dy = gsl_ran_gaussian(r, si);\n\n weights[i] = 1.0 / (si * si);\n y[i] = yi + dy;\n printf (\"data: %zu %g %g\\n\", i, y[i], si);\n };\n\n /* allocate workspace with default parameters */\n w = gsl_multifit_nlinear_alloc (T, &fdf_params, n, p);\n\n /* initialize solver with starting point and weights */\n gsl_multifit_nlinear_winit (&x.vector, &wts.vector, &fdf, w);\n\n /* compute initial cost function */\n f = gsl_multifit_nlinear_residual(w);\n gsl_blas_ddot(f, f, &chisq0);\n\n /* solve the system with a maximum of 20 iterations */\n status = gsl_multifit_nlinear_driver(20, xtol, gtol, ftol,\n callback, NULL, &info, w);\n\n /* compute covariance of best fit parameters */\n J = gsl_multifit_nlinear_jac(w);\n gsl_multifit_nlinear_covar (J, 0.0, covar);\n\n /* compute final cost */\n gsl_blas_ddot(f, f, &chisq);\n\n#define FIT(i) gsl_vector_get(w->x, i)\n#define ERR(i) sqrt(gsl_matrix_get(covar,i,i))\n\n fprintf(stderr, \"summary from method '%s/%s'\\n\",\n gsl_multifit_nlinear_name(w),\n gsl_multifit_nlinear_trs_name(w));\n fprintf(stderr, \"number of iterations: %zu\\n\",\n gsl_multifit_nlinear_niter(w));\n fprintf(stderr, \"function evaluations: %zu\\n\", fdf.nevalf);\n fprintf(stderr, \"Jacobian evaluations: %zu\\n\", fdf.nevaldf);\n fprintf(stderr, \"reason for stopping: %s\\n\",\n (info == 1) ? \"small step size\" : \"small gradient\");\n fprintf(stderr, \"initial |f(x)| = %f\\n\", sqrt(chisq0));\n fprintf(stderr, \"final |f(x)| = %f\\n\", sqrt(chisq));\n\n { \n double dof = n - p;\n double c = GSL_MAX_DBL(1, sqrt(chisq / dof));\n\n fprintf(stderr, \"chisq/dof = %g\\n\", chisq / dof);\n\n fprintf (stderr, \"A = %.5f +/- %.5f\\n\", FIT(0), c*ERR(0));\n fprintf (stderr, \"lambda = %.5f +/- %.5f\\n\", FIT(1), c*ERR(1));\n fprintf (stderr, \"b = %.5f +/- %.5f\\n\", FIT(2), c*ERR(2));\n }\n\n fprintf (stderr, \"status = %s\\n\", gsl_strerror (status));\n\n gsl_multifit_nlinear_free (w);\n gsl_matrix_free (covar);\n gsl_rng_free (r);\n\n return 0;\n}\n", "meta": {"hexsha": "370ad8f74d26f990c53c3969f4883c79c4fd3da0", "size": 5296, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc_texinfo/examples/nlfit.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/nlfit.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/nlfit.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.158974359, "max_line_length": 99, "alphanum_fraction": 0.6025302115, "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103779, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7396336795483008}} {"text": "#include \n#include \n#include \n#include \n\n/*\n gsl_matrix_printf prints a matrix as a column vector. This function\n prints a matrix in block form.\n*/\nvoid pretty_print(const gsl_matrix * M)\n{\n // Get the dimension of the matrix.\n int rows = M->size1;\n int cols = M->size2;\n // Now print out the data in a square format.\n for(int i = 0; i < rows; i++){\n for(int j = 0; j < cols; j++){\n printf(\"%f \", gsl_matrix_get(M, i, j));\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n\nint run_svd(const gsl_matrix * a) {\n // Need to transpose the input\n gsl_matrix *a_transpose = gsl_matrix_alloc(a->size2, a->size1);\n gsl_matrix_transpose_memcpy(a_transpose, a);\n printf(\"a_matrix'\\n\");\n pretty_print(a_transpose);\n\n int m = a->size1;\n gsl_matrix * V = gsl_matrix_alloc(m, m);\n gsl_vector * S = gsl_vector_alloc(m);\n gsl_vector * work = gsl_vector_alloc(m);\n\n gsl_linalg_SV_decomp(a_transpose, V, S, work);\n printf(\"U\\n\");\n pretty_print(V); printf(\"\\n\");\n printf(\"V\\n\");\n pretty_print(a_transpose); printf(\"\\n\");\n printf(\"S\\n\");\n gsl_vector_fprintf(stdout, S, \"%g\");\n\n gsl_matrix_free(V);\n gsl_vector_free(S);\n gsl_vector_free(work);\n\n return 0;\n}\n", "meta": {"hexsha": "b52af305a0fc57384a5269cbe14a773991ca817c", "size": 1221, "ext": "c", "lang": "C", "max_stars_repo_path": "src/c/src/run_svd.c", "max_stars_repo_name": "paul-reiners/getting-smaller", "max_stars_repo_head_hexsha": "c1b9f0a0e72d7f92b9ce84aa111c063efcac1241", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/c/src/run_svd.c", "max_issues_repo_name": "paul-reiners/getting-smaller", "max_issues_repo_head_hexsha": "c1b9f0a0e72d7f92b9ce84aa111c063efcac1241", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/c/src/run_svd.c", "max_forks_repo_name": "paul-reiners/getting-smaller", "max_forks_repo_head_hexsha": "c1b9f0a0e72d7f92b9ce84aa111c063efcac1241", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9411764706, "max_line_length": 70, "alphanum_fraction": 0.6527436527, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.739619193405046}} {"text": "#include \n#include \n#include \n#include \n#include // high level interface to blas\n#include // lapack\n\nvoid print_matrix(gsl_matrix* m, int nx, int ny);\n\nint main (void) {\n\tint i, j;\n\tint signum = 0;\n\tdouble determinant_m = 0.0;\n\tgsl_permutation *m_LU_permutation = gsl_permutation_alloc(8);\n\tgsl_matrix *m_test = gsl_matrix_alloc(8, 8);\n\tgsl_matrix *m_original = gsl_matrix_alloc(8,8);\n\tgsl_matrix *m_inverted = gsl_matrix_alloc(8,8);\n\t\n\t/*for (i = 0; i < 8; i++){\n\t\tfor(j = 0; j < 8; j++){\n\t\t\tgsl_matrix_set(m_test, i, j, 1);\n\t\t}\n\t}*/\n\t\n\tgsl_matrix_set(m_test, 0, 7, 1);\n\tgsl_matrix_set(m_test, 7,0, 1);\n\tgsl_matrix_set(m_test, 3,2, 5);\n\tgsl_matrix_set(m_test, 5,2, 5);\n\n\n\tfor( i = 0; i < 8; i++){\n\t\tgsl_matrix_set(m_test, i, i, 3);\n\t}\n\n\n\t// set the oritinal one too\n\tgsl_matrix_memcpy(m_original, m_test); \t\n\t// now print the matrix out\n\t//print_matrix(m_test, 8, 8);\n\t\n\tprintf(\"\\n\");\n\tprint_matrix(m_original, 8,8);\n\n\t// simple matrix operations\n\t//gsl_matrix_add(m_test, m_test);\n\t//gsl_matrix_add_constant(m_test, 1.05);\n\n\t//print_matrix(m_test, 8,8);\n\n\t// creates the lu decomp of the matrix\n\t// need to allocate the permutation\n\tgsl_linalg_LU_decomp(m_test, m_LU_permutation, &signum);\n\n\t// calculate the determinant of m_test from the lu\n\tdeterminant_m = gsl_linalg_LU_det(m_test, signum);\n\tprintf(\"det_m = %g\\n\", determinant_m);\n\t// invert the matrix\n\tgsl_linalg_LU_invert(m_test, m_LU_permutation, m_inverted);\n\n\t// multiply the inverse and the matrix together (can't use the LU one bc it's fucked up)\n\t// m_test should be I\n\tgsl_blas_dgemm( CblasNoTrans,CblasNoTrans , 1.0, m_original, m_inverted, 0.0, m_test);\n\n\tprint_matrix(m_test, 8,8);\n\n\n\tgsl_permutation_free(m_LU_permutation);\n\tgsl_matrix_free(m_inverted);\n\tgsl_matrix_free(m_test);\n\treturn(0);\n}\n\nvoid print_matrix(gsl_matrix* m, int nx, int ny){\n\tint i,j;\n\tfor(i = 0; i < nx; i++){\n\t\tfor(j= 0; j < ny; j++){\n\t\t\tprintf(\"%g \", gsl_matrix_get(m, i, j));\n\t\t}\n\t\tprintf(\"\\n\");\n \t}\n}\n", "meta": {"hexsha": "e96cfcdf5d65f3235d99871d43cc6266920fb6ba", "size": 2029, "ext": "c", "lang": "C", "max_stars_repo_path": "src/test/array-test.c", "max_stars_repo_name": "jackdawjackdaw/emulator", "max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z", "max_issues_repo_path": "src/test/array-test.c", "max_issues_repo_name": "MADAI/MADAIEmulator", "max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "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/test/array-test.c", "max_forks_repo_name": "MADAI/MADAIEmulator", "max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z", "avg_line_length": 24.743902439, "max_line_length": 90, "alphanum_fraction": 0.6860522425, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7394197736083413}} {"text": "// SPDX-License-Identifier: Unlicense\n\n/*\n * libinput calibration calculation\n */\n\n#include \n#include \n#include \n\n/*\n * Compute the (Moore-Penrose) pseudo-inverse of a matrix.\n * \n * PUBLIC DOMAIN by Charl Linssen \n *\n * If the singular value decomposition (SVD) of A = UΣVᵀ then the\n * pseudoinverse A⁻¹ = VΣ⁻¹Uᵀ, where ᵀ indicates transpose and\n * Σ⁻¹ is obtained by taking the reciprocal of each nonzero element on\n * the diagonal, leaving zeros in place. Elements on the diagonal smaller\n * than ``rcond`` times the largest singular value are considered zero.\n *\n * @parameter A\t\tInput matrix. **WARNING**: the input matrix ``A`` is\n * \t\t\tdestroyed. However, it is still the responsibility of\n * \t\t\tthe caller to free it.\n *\n * @parameter rcond\tA real number specifying the singular value threshold\n * \t\t\tfor inclusion. NumPy default for ``rcond`` is 1E-15.\n *\n * @returns A_pinv\tMatrix containing the result. ``A_pinv`` is allocated\n * \t\t\tin this function and it is the responsibility of the\n * \t\t\tcaller to free it.\n * \n *\n */\ngsl_matrix* moore_penrose_pinv(gsl_matrix *A, const double rcond) {\n\n\tgsl_matrix *V, *Sigma_pinv, *U, *A_pinv;\n\tgsl_matrix *_tmp_mat = NULL;\n\tgsl_vector *_tmp_vec;\n\tgsl_vector *u;\n\tdouble x, cutoff;\n\tsize_t i, j;\n\tunsigned int n = A->size1;\n\tunsigned int m = A->size2;\n\tunsigned int was_swapped = 0;\n\n\n\tif (m > n) {\n\t\t/* libgsl SVD can only handle the case m <= n - transpose matrix */\n\t\twas_swapped = 1;\n\t\t_tmp_mat = gsl_matrix_alloc(m, n);\n\t\tgsl_matrix_transpose_memcpy(_tmp_mat, A);\n\t\tA = _tmp_mat;\n\t\ti = m;\n\t\tm = n;\n\t\tn = i;\n\t}\n\n\t/* do SVD */\n\tV = gsl_matrix_alloc(m, m);\n\tu = gsl_vector_alloc(m);\n\t_tmp_vec = gsl_vector_alloc(m);\n\tgsl_linalg_SV_decomp(A, V, u, _tmp_vec);\n\tgsl_vector_free(_tmp_vec);\n\n\t/* compute Σ⁻¹ */\n\tSigma_pinv = gsl_matrix_alloc(m, n);\n\tgsl_matrix_set_zero(Sigma_pinv);\n\tcutoff = rcond * gsl_vector_max(u);\n\n\tfor (i = 0; i < m; ++i) {\n\t\tif (gsl_vector_get(u, i) > cutoff) {\n\t\t\tx = 1. / gsl_vector_get(u, i);\n\t\t}\n\t\telse {\n\t\t\tx = 0.;\n\t\t}\n\t\tgsl_matrix_set(Sigma_pinv, i, i, x);\n\t}\n\n\t/* libgsl SVD yields \"thin\" SVD - pad to full matrix by adding zeros */\n\tU = gsl_matrix_alloc(n, n);\n\tgsl_matrix_set_zero(U);\n\n\tfor (i = 0; i < n; ++i) {\n\t\tfor (j = 0; j < m; ++j) {\n\t\t\tgsl_matrix_set(U, i, j, gsl_matrix_get(A, i, j));\n\t\t}\n\t}\n\n\tif (_tmp_mat != NULL) {\n\t\tgsl_matrix_free(_tmp_mat);\n\t}\n\n\t/* two dot products to obtain pseudoinverse */\n\t_tmp_mat = gsl_matrix_alloc(m, n);\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1., V, Sigma_pinv, 0., _tmp_mat);\n\n\tif (was_swapped) {\n\t\tA_pinv = gsl_matrix_alloc(n, m);\n\t\tgsl_blas_dgemm(CblasNoTrans, CblasTrans, 1., U, _tmp_mat, 0., A_pinv);\n\t}\n\telse {\n\t\tA_pinv = gsl_matrix_alloc(m, n);\n\t\tgsl_blas_dgemm(CblasNoTrans, CblasTrans, 1., _tmp_mat, U, 0., A_pinv);\n\t}\n\n\tgsl_matrix_free(_tmp_mat);\n\tgsl_matrix_free(U);\n\tgsl_matrix_free(Sigma_pinv);\n\tgsl_vector_free(u);\n\tgsl_matrix_free(V);\n\n\treturn A_pinv;\n}\n\nint main(int argc, char **argv) {\n\tconst unsigned int col = 4;\n\tconst unsigned int row = 3;\n\tconst double rcond = 1E-15;\n\n\tconst double oneEigth = 1.0/8.0;\n\tconst double sevenEight = 7.0/8.0;\n\n\tif (argc < 11) {\n\t\tprintf(\"usage: %s x-res y-res x0 y0 x1 y1 x2 y2 x3 y3 [swap-x-y]\\n\", argv[0]);\n\t\treturn EXIT_FAILURE;\n\t}\n\n int xres = atoi(argv[1]);\n int yres = atoi(argv[2]);\n int x0in = atoi(argv[3]);\n int y0in = atoi(argv[4]);\n int x1in = atoi(argv[5]);\n int y1in = atoi(argv[6]);\n int x2in = atoi(argv[7]);\n int y2in = atoi(argv[8]);\n int x3in = atoi(argv[9]);\n int y3in = atoi(argv[10]);\n\n\tint swapxy = 0;\n\tif (argc > 11)\n\t\tswapxy = 1;\n\n\tdouble x0 = (double)x0in / (double)xres;\n\tdouble y0 = (double)y0in / (double)yres;\n\tdouble x1 = (double)x1in / (double)xres;\n\tdouble y1 = (double)y1in / (double)yres;\n\tdouble x2 = (double)x2in / (double)xres;\n\tdouble y2 = (double)y2in / (double)yres;\n\tdouble x3 = (double)x3in / (double)xres;\n\tdouble y3 = (double)y3in / (double)yres;\n\n\n\tgsl_matrix *A = gsl_matrix_alloc(row, col);\n\tgsl_matrix *C = gsl_matrix_alloc(row, col);\n\tgsl_matrix *R = gsl_matrix_alloc(3, 3);\n\tgsl_matrix *S;\n\tgsl_matrix *T;\n\tgsl_matrix *A_pinv;\n\n\tgsl_matrix_set(A, 0, 0, x0);\n\tgsl_matrix_set(A, 0, 1, x1);\n\tgsl_matrix_set(A, 0, 2, x2);\n\tgsl_matrix_set(A, 0, 3, x3);\n\tgsl_matrix_set(A, 1, 0, y0);\n\tgsl_matrix_set(A, 1, 1, y1);\n\tgsl_matrix_set(A, 1, 2, y2);\n\tgsl_matrix_set(A, 1, 3, y3);\n\tgsl_matrix_set(A, 2, 0, 1.0);\n\tgsl_matrix_set(A, 2, 1, 1.0);\n\tgsl_matrix_set(A, 2, 2, 1.0);\n\tgsl_matrix_set(A, 2, 3, 1.0);\n\n\tgsl_matrix_set(C, 0, 0, oneEigth);\n\tgsl_matrix_set(C, 0, 1, sevenEight);\n\tgsl_matrix_set(C, 0, 2, oneEigth);\n\tgsl_matrix_set(C, 0, 3, sevenEight);\n\tgsl_matrix_set(C, 1, 0, oneEigth);\n\tgsl_matrix_set(C, 1, 1, oneEigth);\n\tgsl_matrix_set(C, 1, 2, sevenEight);\n\tgsl_matrix_set(C, 1, 3, sevenEight);\n\tgsl_matrix_set(C, 2, 0, 1.0);\n\tgsl_matrix_set(C, 2, 1, 1.0);\n\tgsl_matrix_set(C, 2, 2, 1.0);\n\tgsl_matrix_set(C, 2, 3, 1.0);\n\n\tA_pinv = moore_penrose_pinv(A, rcond);\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, C, A_pinv, 0.0, R);\n\n\tif (swapxy) {\n\t\tS = gsl_matrix_alloc(3, 3);\n\n\t\t/* extra swapping x-y axes as requested */\n\t\tgsl_matrix_set(S, 0, 0, 0.0);\n\t\tgsl_matrix_set(S, 0, 1, -1.0);\n\t\tgsl_matrix_set(S, 0, 2, 1.0);\n\t\tgsl_matrix_set(S, 1, 0, -1.0);\n\t\tgsl_matrix_set(S, 1, 1, 0.0);\n\t\tgsl_matrix_set(S, 1, 2, 1.0);\n\t\tgsl_matrix_set(S, 2, 0, 0.0);\n\t\tgsl_matrix_set(S, 2, 1, 0.0);\n\t\tgsl_matrix_set(S, 2, 2, 1.0);\n\n\t\tT = R;\n\t\tR = gsl_matrix_alloc(3, 3);\n\t\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, T, S, 0.0, R);\n\t}\n\n printf(\"%f, %f, %f, %f, %f, %f, %f, %f, %f\\n\",\n gsl_matrix_get((const gsl_matrix *)R, 0, 0), gsl_matrix_get((const gsl_matrix *)R, 0, 1), gsl_matrix_get((const gsl_matrix *)R, 0, 2),\n gsl_matrix_get((const gsl_matrix *)R, 1, 0), gsl_matrix_get((const gsl_matrix *)R, 1, 1), gsl_matrix_get((const gsl_matrix *)R, 1, 2),\n gsl_matrix_get((const gsl_matrix *)R, 2, 0), gsl_matrix_get((const gsl_matrix *)R, 2, 1), gsl_matrix_get((const gsl_matrix *)R, 2, 2));\n\n\tgsl_matrix_free(A);\n\tgsl_matrix_free(C);\n\tgsl_matrix_free(R);\n\tgsl_matrix_free(A_pinv);\n\n\tif (swapxy) {\n\t\tgsl_matrix_free(S);\n\t\tgsl_matrix_free(T);\n\t}\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "610104bbdd43d15e9d7334ff960326c2d2f78d71", "size": 6268, "ext": "c", "lang": "C", "max_stars_repo_path": "calc_libinput_matrix.c", "max_stars_repo_name": "g0hl1n/xinput_calibrator_libinput", "max_stars_repo_head_hexsha": "8b10c8a7530b20a9b25835e47c614e1dd7ec4dd9", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-23T14:18:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T14:18:22.000Z", "max_issues_repo_path": "calc_libinput_matrix.c", "max_issues_repo_name": "g0hl1n/xinput_calibrator_libinput", "max_issues_repo_head_hexsha": "8b10c8a7530b20a9b25835e47c614e1dd7ec4dd9", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calc_libinput_matrix.c", "max_forks_repo_name": "g0hl1n/xinput_calibrator_libinput", "max_forks_repo_head_hexsha": "8b10c8a7530b20a9b25835e47c614e1dd7ec4dd9", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7345132743, "max_line_length": 151, "alphanum_fraction": 0.6482131461, "num_tokens": 2314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.738695991328974}} {"text": "//\n// Created by Harold on 2020/9/16.\n//\n\n#ifndef M_MATH_M_CURVEFIT_H\n#define M_MATH_M_CURVEFIT_H\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace M_MATH {\n class CurveFit{\n public:\n enum robust_type {\n DEFAULT,\n BISQUARE,\n CAUCHY,\n FAIR,\n HUBER,\n OLS,\n WELSCH\n };\n public:\n bool is_valid() const { return !m_coefficient.empty(); }\n bool linearfit(double const* x, double const* y, size_t n);\n bool polyfit(double const* x, double const* y, size_t length, unsigned poly_n);\n bool robustfit(double const* x, double const* y, size_t length, robust_type type, unsigned poly_n);\n\n double getY(double x) const;\n\n template\n void getYs(IT_X x_begin, IT_X x_end, IT_Y y_begin) const;\n\n double get_coefficient(size_t n) const;\n void set_coefficient(size_t n, double c) { m_coefficient[n] = c; };\n size_t get_coefficient_size() const { return m_coefficient.size(); };\n\n double get_slope() { return m_coefficient[1]; };\n double get_intercept() { return m_coefficient[0]; };\n double get_SSR() const { return m_ssr; };\n double get_SSE() const { return m_sse; };\n double get_SST() const { return m_sst; };\n double get_RMSE() const { return m_rmse; };\n double get_RSquare() const { return m_RSquare; };\n double get_Goodness() const { return m_goodness; };\n\n void clear() {\n m_coefficient.clear();\n m_err.clear();\n }\n\n private:\n std::map m_coefficient; // , [0]: slope, [1] intercept\n std::map m_err;\n double m_cov; // covariance\n double m_ssr; // sum of squares due to regression\n double m_sse; // sum of squares error\n double m_sst; // m_sst = m_ssr + m_sse\n double m_rmse; // RMS error\n double m_RSquare; // R-Square\n\n double m_sumsq; // sum of squares\n double m_goodness; // fit goodness\n\n static void get_determinate_parameters(double const* y, double const* yf,\n size_t length,\n double &ssr,\n double &sse,\n double &sst,\n double &rmse,\n double &RSquare) {\n double y_mean = std::accumulate(y, y+length, 0.0);\n ssr = 0.0;\n for (auto i = 0; i < length; ++i) {\n ssr += (yf[i] - y_mean) * (yf[i] - y_mean);\n sse += (y[i] - yf[i]) * (y[i] - yf[i]);\n }\n sst = ssr + sse;\n rmse = std::sqrt(sse/(double)length);\n RSquare = 1.0 - ssr/sst;\n }\n\n static gsl_multifit_robust_type const* get_robust_type(robust_type type) {\n switch (type) {\n case DEFAULT:\n return gsl_multifit_robust_default;\n case BISQUARE:\n return gsl_multifit_robust_bisquare;\n case CAUCHY:\n return gsl_multifit_robust_cauchy;\n case FAIR:\n return gsl_multifit_robust_fair;\n case HUBER:\n return gsl_multifit_robust_huber;\n case OLS:\n return gsl_multifit_robust_ols;\n case WELSCH:\n return gsl_multifit_robust_welsch;\n }\n return nullptr;\n }\n };\n\n inline bool CurveFit::linearfit(const double *x, const double *y, size_t n) {\n clear();\n m_coefficient[0] = 0;\n m_coefficient[1] = 1;\n m_err[0] = 0;\n m_err[0] = 0;\n // double const* x, size_t const x_stride,\n // double const* y, size_t const y_stride,\n // size_t n,\n // double &intercept,\n // double &slope,\n // double &intercept_err,\n // double &slope_err,\n // double &cov,\n // double &wssr\n int ret = gsl_fit_linear(x, 1, y, 1, n,\n &m_coefficient[0], &m_coefficient[1],\n &m_err[0], &m_err[1],\n &m_cov, &m_sumsq);\n if (ret != 0)\n return false;\n // gammaQ function\n m_goodness = gsl_cdf_chisq_Q(m_sumsq / 2.0, double(n - 2) / 2.0);\n {\n std::vector yf(n, 0);\n getYs(x, x+n, yf.begin());\n get_determinate_parameters(y, &yf[0], n, m_ssr, m_sse, m_sst, m_rmse, m_RSquare);\n }\n return true;\n }\n\n inline bool CurveFit::polyfit(const double *x, const double *y, size_t length, unsigned poly_n) {\n gsl_matrix *Xf = gsl_matrix_alloc(length, poly_n+1);\n gsl_vector *Yf = gsl_vector_alloc(length);\n gsl_vector *c = gsl_vector_alloc(poly_n+1);\n gsl_matrix *cov = gsl_matrix_alloc(poly_n+1, poly_n+1);\n\n for (auto i = 0; i < length; i++) {\n gsl_matrix_set(Xf, i, 0, 1.0);\n gsl_vector_set(Yf, i, y[i]);\n for (auto j = 1; j < poly_n + 1; j++)\n gsl_matrix_set(Xf, i, j, std::pow(x[i], int(j)));\n }\n\n auto *workspace = gsl_multifit_linear_alloc(length, poly_n+1);\n double chisq;\n // temporary vec to hold computed coefficients\n std::vector coe(poly_n+1, 0);\n\n int ret = gsl_multifit_linear(Xf, Yf, c, cov, &chisq, workspace);\n gsl_multifit_linear_free(workspace);\n for (auto i = 0; i < c->size; i++)\n coe[i] = gsl_vector_get(c, i);\n\n gsl_matrix_free(Xf);\n gsl_vector_free(Yf);\n gsl_vector_free(c);\n gsl_matrix_free(cov);\n\n // if not successfully computed, not change former results\n if (ret != 0)\n return false;\n\n // update results\n m_goodness = gsl_cdf_chisq_Q(chisq/2.0, double(length-2)/2.0);\n clear();\n for (auto i = 0; i < poly_n+1; i++)\n m_coefficient[i] = coe[i];\n {\n std::vector yf(length, 0);\n getYs(x, x+length, yf.begin());\n get_determinate_parameters(y, &yf[0], length, m_ssr, m_sse, m_sst, m_rmse, m_RSquare);\n }\n return true;\n }\n\n inline double CurveFit::getY(double x) const {\n double ret = 0;\n for (auto const& it : m_coefficient)\n ret += (it.second) * std::pow(x, it.first);\n return ret;\n }\n\n template\n inline void CurveFit::getYs(IT_X x_begin, IT_X x_end, IT_Y y_begin) const {\n for (; x_begin != x_end; ++x_begin, ++y_begin)\n *y_begin = getY(*x_begin);\n }\n\n inline double CurveFit::get_coefficient(size_t n) const {\n auto it = m_coefficient.find(n);\n if (it != m_coefficient.end())\n return it->second;\n return 0.0;\n }\n\n // poly_n >= 2\n // poly_n = 2: linear fit\n bool CurveFit::robustfit(const double *x, const double *y, size_t length, robust_type type, unsigned int poly_n) {\n gsl_matrix *Xf = gsl_matrix_alloc(length, poly_n);\n gsl_vector *Yf = gsl_vector_alloc(length);\n gsl_vector *c = gsl_vector_alloc(poly_n);\n gsl_matrix *cov = gsl_matrix_alloc(poly_n, poly_n);\n\n for (auto i = 0; i < length; i++) {\n gsl_matrix_set(Xf, i, 0, 1.0);\n gsl_vector_set(Yf, i, y[i]);\n for (auto j = 1; j < poly_n; j++)\n gsl_matrix_set(Xf, i, j, std::pow(x[i], int(j)));\n }\n\n auto *workspace = gsl_multifit_robust_alloc(get_robust_type(type), length, poly_n);\n // temporary vec to hold computed coefficients\n std::vector coe(poly_n, 0);\n\n int ret = gsl_multifit_robust(Xf, Yf, c, cov, workspace);\n gsl_multifit_robust_free(workspace);\n for (auto i = 0; i < c->size; i++)\n coe[i] = gsl_vector_get(c, i);\n\n gsl_matrix_free(Xf);\n gsl_vector_free(Yf);\n gsl_vector_free(c);\n gsl_matrix_free(cov);\n\n // if not successfully computed, not change former results\n if (ret != 0)\n return false;\n\n // update results\n clear();\n for (auto i = 0; i < poly_n; i++)\n m_coefficient[i] = coe[i];\n {\n std::vector yf(length, 0);\n getYs(x, x+length, yf.begin());\n get_determinate_parameters(y, &yf[0], length, m_ssr, m_sse, m_sst, m_rmse, m_RSquare);\n }\n return true;\n }\n}\n\n#endif //M_MATH_M_CURVEFIT_H\n", "meta": {"hexsha": "0287efaded35483edbc4d7b5414267bd1082b471", "size": 8904, "ext": "h", "lang": "C", "max_stars_repo_path": "include/m_curvefit.h", "max_stars_repo_name": "Harold2017/m_math", "max_stars_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-04T12:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T08:00:15.000Z", "max_issues_repo_path": "include/m_curvefit.h", "max_issues_repo_name": "Harold2017/m_math", "max_issues_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-03T02:50:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T06:32:29.000Z", "max_forks_repo_path": "include/m_curvefit.h", "max_forks_repo_name": "Harold2017/m_math", "max_forks_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-04T12:26:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T12:26:12.000Z", "avg_line_length": 35.0551181102, "max_line_length": 118, "alphanum_fraction": 0.5344788859, "num_tokens": 2385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7378641127396195}} {"text": "#include \n#include \n#include \n#include \n#include \n\nint main (int argc, char* argv[])\n{\n /* Parse the command line arguments. */\n const char* usage = \"Usage: zeroes ... - ... \\n\";\n\n if (argc < 8) {\n fprintf (stderr, \"%s\", usage);\n exit(EXIT_FAILURE);\n }\n\n /* The window in the plane. */\n const double xmin = atof(argv[1]);\n const double xmax = atof(argv[2]);\n const double ymin = atof(argv[3]);\n const double ymax = atof(argv[4]);\n\n /* Image size, width is given, height is computed. */\n const int xres = atoi(argv[5]);\n const int yres = (int)((xres * (ymax-ymin)) / (xmax-xmin));\n\n /* The coefficients */\n int ci_max = 0 ;\n while (6 + ci_max < argc && (argv[6+ci_max][0] != '-' || argv[6+ci_max][1] != 0)) { ci_max++; }\n if (ci_max == 0) {\n fprintf (stderr, \"%s\\nError: specify at least one coefficient.\", usage) ;\n exit(EXIT_FAILURE);\n }\n double coeff[ci_max];\n for (int ci = 0; ci < ci_max; ci++) { coeff[ci] = atof(argv[6+ci]); }\n\n /* The degrees */\n const int di_max = argc - 7 - ci_max;\n if (di_max <= 0) {\n fprintf (stderr, \"%s\\nError: specify at least one degree.\", usage) ;\n exit(EXIT_FAILURE);\n }\n int degree[di_max];\n for (int di = 0; di < di_max; di++) { degree[di] = atoi(argv[7+ci_max+di]); }\n \n /* Allocate the image and initialize it */\n unsigned int *image = (unsigned int *)calloc(sizeof(unsigned int), yres * xres) ;\n const unsigned int count_bound = 0xffffffff;\n unsigned int max_count = 0 ;\n\n /* Turn off the GSL error handler that aborts on error (some polynomials have tricky zeroes) */\n gsl_set_error_handler_off ();\n\n /* We're going to skip zeroes whose imaginary part is almost zero. */\n const double epsilon = 1.0e-20 ;\n\n time_t start = time(NULL);\n\n /* Run through degrees and compute the zeroes for each one. */\n for (int di = 0; di < di_max; di++) {\n const int d = degree[di]; /* The degree we're working on. */\n time_t now = time(NULL);\n fprintf (stderr, \"Degree %d (%.2lf seconds)\\n\", d, difftime(now, start));\n /* Initialize the polynomial. */\n double poly[d+1];\n for (int j = 0; j <= d; j++) { poly[j] = coeff[0]; } \n /* Initialize the counters. */\n int counter[d+1];\n for (int j = 0; j <= d; j++) { counter[j] = 0; }\n int j = 0;\n /* Allocate the workspace. */\n gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc(d+1);\n do {\n /* Compute the zeroes if head coefficient is non-zero. */\n if (poly[d] > epsilon || poly[d] < -epsilon) {\n double z[2*d]; /* the zeroes are stored here */\n int status = gsl_poly_complex_solve (poly, d+1, w, z);\n /* Only use zeroes if GSL reported success */\n if (status == 0) {\n /* Draw zeroes, skipping the real ones that are away from the origin */\n for (int i=0; i < d; i++) {\n if (-epsilon < z[2*i+1] && z[2*i+1] < epsilon && (z[2*i] < -0.5 || z[2*i] > 0.5)) {\n continue;\n }\n int x = (int)((xres * (z[2*i] - xmin)) / (xmax - xmin));\n int y = yres - (int)((yres * (z[2*i+1] - ymin)) / (ymax - ymin));\n if (0 <= x && x < xres && 0 <= y && y < yres && image[xres * y + x] < count_bound) {\n int c = ++image[xres * y + x];\n if (max_count < c) { max_count = c; }\n }\n }\n }\n }\n /* calculate the next polynomial */\n for (j = 0; j <= d && counter[j] == ci_max-1; j++) { counter[j] = 0; poly[j] = coeff[0]; }\n if (j <= d) { counter[j]++; poly[j] = coeff[counter[j]]; }\n } while (j <= d);\n /* Deallocate workspace. */\n gsl_poly_complex_workspace_free (w);\n }\n\n /* Output the computed result. */\n /* ASCII header to the file*/\n printf(\"P6\\n# Zeroes, xmin=%lf, xmax=%lf, ymin=%lf, ymax=%lf, max_count=%d, coeffs=[\", xmin, xmax, ymin, ymax, max_count);\n for (int ci=0; ci < ci_max; ci++) { printf(\"%lf%s\", coeff[ci], (ci < ci_max-1 ? \", \" : \"],\")); }\n printf(\"degrees = [\");\n for (int di=0; di < di_max; di++) { printf(\"%d%s\", degree[di], (di < di_max-1 ? \", \" : \"],\")); }\n printf(\"\\n\");\n printf(\"%d\\n%d\\n%d\\n\", xres, yres, 0xffff);\n /* Image */\n double r = 65535.0 / log((double)max_count) ;\n for (int y = 0; y < yres; y++) {\n for (int x = 0; x < xres; x++) {\n unsigned char color[6];\n unsigned int k = (unsigned int)(r * log((float)image[xres * y + x])) ;\n color[0] = k >> 8;\n color[1] = k & 255;\n color[2] = k >> 8;\n color[3] = k & 255;\n color[4] = k >> 8;\n color[5] = k & 255;\n fwrite(color, 6, 1, stdout);\n }\n }\n free(image);\n return(0);\n}\n", "meta": {"hexsha": "042840bcad3dd105a8ea105d6b5ff035ec975370", "size": 4717, "ext": "c", "lang": "C", "max_stars_repo_path": "zeroes.c", "max_stars_repo_name": "andrejbauer/zeroes", "max_stars_repo_head_hexsha": "948f10bedcf38ac3aa63cdd1d629163f67c59d55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T18:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T09:13:58.000Z", "max_issues_repo_path": "zeroes.c", "max_issues_repo_name": "andrejbauer/zeroes", "max_issues_repo_head_hexsha": "948f10bedcf38ac3aa63cdd1d629163f67c59d55", "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": "zeroes.c", "max_forks_repo_name": "andrejbauer/zeroes", "max_forks_repo_head_hexsha": "948f10bedcf38ac3aa63cdd1d629163f67c59d55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-02-25T19:33:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T03:30:42.000Z", "avg_line_length": 36.8515625, "max_line_length": 124, "alphanum_fraction": 0.543989824, "num_tokens": 1491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145364, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7376646528858083}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct color {\n\tdouble value[3];\n};\n\nstruct color cartesian_to_polar(struct color source_color) {\n\tstruct color target_color;\n\ttarget_color.value[0] = source_color.value[0];\n\ttarget_color.value[1] = hypot(source_color.value[1], source_color.value[2]);\n\ttarget_color.value[2] = atan2(source_color.value[2], source_color.value[1])*180.0/M_PI;\n\n\tif (target_color.value[2] < 0) {\n\t\ttarget_color.value[2] = target_color.value[2] + 360;\n\t}\n\n\treturn target_color;\n}\n\nstruct color polar_to_cartesian(struct color source_color) {\n\tstruct color target_color;\n\tdouble angle;\n\tangle = source_color.value[2]/180*(M_PI);\n\ttarget_color.value[0] = source_color.value[0];\n\ttarget_color.value[1] = cos(angle)*source_color.value[1];\n\ttarget_color.value[2] = sin(angle)*source_color.value[1];\n\treturn target_color;\n}\n\n\n/* XYZ = CIE 1931 XYZ */\n\nstruct color XYZ_values_to_OSA74(double X, double Y, double Z) {\n\tstruct color target_color;\n\tdouble x = X/(X+Y+Z);\n\tdouble y = Y/(X+Y+Z);\n\tdouble Y0 = (4.4934*x*x + 4.3034*y*y - 4.276*x*y - 1.3744*x - 2.5643*y + 1.8103)*Y;\n\tdouble Lambda = 5.9*(cbrt(Y0) - 2.0/3 + 0.042*cbrt(Y0-30));\n\tdouble C = Lambda/(5.9*(cbrt(Y0) - 2.0/3));\n\tdouble R = 0.7990*X + 0.4194*Y - 0.1648*Z;\n\tdouble G = -0.4493*X + 1.3265*Y + 0.0927*Z;\n\tdouble B = -0.1149*X + 0.3394*Y + 0.7170*Z;\n\t/* target_color.value[0] = (Lambda - 14.3993)/sqrt(2); */\n\ttarget_color.value[0] = (Lambda - 14.4)/sqrt(2);\n\ttarget_color.value[1] = C*(1.7*cbrt(R) + 8*cbrt(G) - 9.7*cbrt(B));\n\ttarget_color.value[2] = C*(-13.7*cbrt(R) + 17.7*cbrt(G) - 4*cbrt(B));\n\treturn target_color;\n}\n\nstruct color XYZ_values_to_OSA90(double X, double Y, double Z) {\n\tstruct color target_color;\n\tdouble x = X/(X+Y+Z);\n\tdouble y = Y/(X+Y+Z);\n\tdouble Y0 = (4.4934*x*x + 4.3034*y*y - 4.276*x*y - 1.3744*x - 2.5643*y + 1.8103)*Y;\n\tdouble Lambda = 5.9*(cbrt(Y0) - 2.0/3 + 0.06*cbrt(Y0-30));\n\tdouble C = Lambda/(5.9*(cbrt(Y0) - 2.0/3));\n\tdouble R = 0.9285*X + 0.3251*Y - 0.1915*Z;\n\tdouble G = -0.4493*X + 1.3265*Y + 0.0927*Z;\n\tdouble B = -0.2032*X + 0.6*Y + 0.5523*Z;\n\t/* target_color.value[0] = (Lambda - 14.3993)/sqrt(2); */\n\ttarget_color.value[0] = (Lambda - 14.4)/sqrt(2);\n\ttarget_color.value[1] = C*(-1.3*cbrt(R) + 17*cbrt(G) - 15.7*cbrt(B));\n\ttarget_color.value[2] = C*(-12.7*cbrt(R) + 19*cbrt(G) - 6.3*cbrt(B));\n\treturn target_color;\n}\n\nstruct color XYZ_to_OSA74(struct color source_color) {\n\tdouble X, Y, Z;\n\tX = source_color.value[0];\n\tY = source_color.value[1];\n\tZ = source_color.value[2];\n\treturn XYZ_values_to_OSA74(X, Y, Z);\n}\n\nstruct color XYZ_to_OSA90(struct color source_color) {\n\tdouble X, Y, Z;\n\tX = source_color.value[0];\n\tY = source_color.value[1];\n\tZ = source_color.value[2];\n\treturn XYZ_values_to_OSA90(X, Y, Z);\n}\n\nint print_matrix(gsl_matrix *matrix) {\n\tint row, column;\n\tfor(row = 0; row < matrix->size1; row++) {\n\t\tfor(column = 0; column < matrix->size2; column++) {\n\t\t\tprintf(\"%8.8f\", gsl_matrix_get(matrix, row, column));\n\t\t}\n\t\tputchar('\\n');\n\t}\n\treturn 0;\n}\n\nstruct color OSA74_to_XYZ(struct color source_color) {\n\tdouble L, j, g;\n\tL = source_color.value[0];\n\tj = source_color.value[1];\n\tg = source_color.value[2];\n\tstruct color target_color;\n\tint max_iterations = 600;\n\tdouble X, Y, Z, previous_X, previous_Y, previous_Z, Delta;\n\tdouble L0, L1, L2, L3, j0, j1, j2, j3, g0, g1, g2, g3;\n\tstruct color color0, color1, color2, color3;\n\n\tgsl_matrix *matrix0 = gsl_matrix_alloc(3, 3);\n\tgsl_matrix *inverse_matrix0 = gsl_matrix_alloc(3, 3);\n\tgsl_matrix *matrix1 = gsl_matrix_alloc(3, 1);\n\tgsl_matrix *matrix2 = gsl_matrix_alloc(3, 1);\n\tgsl_permutation *permutation = gsl_permutation_alloc(3);\n\tint sign = 0;\n\n\t/* start values */\n\t/*X = 28.4; Y = 30.0; Z = 32.2; Delta = 0.5;*/\n\tX = 28.4; Y = 30.0; Z = 32.2; Delta = 0.005;\n\tgsl_matrix_set(matrix2, 0, 0, X);\n\tgsl_matrix_set(matrix2, 1, 0, Y);\n\tgsl_matrix_set(matrix2, 2, 0, Z);\n\n\tint i = 0; do {\n\t\t/* calculate colors for influence matrix */\n\t\tcolor0 = XYZ_values_to_OSA74(X, Y, Z);\n\t\tcolor1 = XYZ_values_to_OSA74(X+Delta, Y, Z);\n\t\tcolor2 = XYZ_values_to_OSA74(X, Y+Delta, Z);\n\t\tcolor3 = XYZ_values_to_OSA74(X, Y, Z+Delta);\n\t\tL0 = color0.value[0]; j0 = color0.value[1]; g0 = color0.value[2];\n\t\tL1 = color1.value[0]; j1 = color1.value[1]; g1 = color1.value[2];\n\t\tL2 = color2.value[0]; j2 = color2.value[1]; g2 = color2.value[2];\n\t\tL3 = color3.value[0]; j3 = color3.value[1]; g3 = color3.value[2];\n\n\t\tgsl_matrix_set(matrix0, 0, 0, (L1-L0)/Delta);\n\t\tgsl_matrix_set(matrix0, 0, 1, (L2-L0)/Delta);\n\t\tgsl_matrix_set(matrix0, 0, 2, (L3-L0)/Delta);\n\t\tgsl_matrix_set(matrix0, 1, 0, (j1-j0)/Delta);\n\t\tgsl_matrix_set(matrix0, 1, 1, (j2-j0)/Delta);\n\t\tgsl_matrix_set(matrix0, 1, 2, (j3-j0)/Delta);\n\t\tgsl_matrix_set(matrix0, 2, 0, (g1-g0)/Delta);\n\t\tgsl_matrix_set(matrix0, 2, 1, (g2-g0)/Delta);\n\t\tgsl_matrix_set(matrix0, 2, 2, (g3-g0)/Delta);\n\n\t\tgsl_matrix_set(matrix1, 0, 0, L-L0);\n\t\tgsl_matrix_set(matrix1, 1, 0, j-j0);\n\t\tgsl_matrix_set(matrix1, 2, 0, g-g0);\n\n\t\t/* update matrix2: matrix2 = inverse_matrix0 matrix1 + matrix2 */\n\t\t/* incremental term (inverse_matrix0 × matrix1) is divided by (5+cbrt(i)) */\n\t\tgsl_linalg_LU_decomp(matrix0, permutation, &sign);\n\t\tgsl_linalg_LU_invert(matrix0, permutation, inverse_matrix0);\n\t\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1/(5+cbrt(i)), inverse_matrix0, matrix1, 1.0, matrix2);\n\n\t\tprevious_X = X; previous_Y = Y; previous_Z = Z;\n\t\tX = gsl_matrix_get(matrix2, 0, 0);\n\t\tY = gsl_matrix_get(matrix2, 1, 0);\n\t\tZ = gsl_matrix_get(matrix2, 2, 0);\n\n\t\t/* printf(\"\\n%d\\n\", i);\n\t\tprint_matrix(matrix2); */\n\n\t\ti++;\n\t} while ((i < max_iterations) && ((fabs(X - previous_X) > 0.0001) || (fabs(Y - previous_Y) > 0.0001) || (fabs(Z - previous_Z) > 0.0001)));\n\n\t/*printf(\"Iterations: %i\\n\", i);*/\n\n\t/*free memory*/\n\tgsl_matrix_free(matrix0);\n\tgsl_matrix_free(inverse_matrix0);\n\tgsl_matrix_free(matrix1);\n\tgsl_matrix_free(matrix2);\n\t/*gsl_matrix_free(matrix_product);*/\n\tgsl_permutation_free(permutation);\n\n\tif (i == max_iterations) {\n\t\tfprintf(stderr, \"Error: Maximum iterations reached.\\n\");\n\t}\n\n\ttarget_color.value[0] = X;\n\ttarget_color.value[1] = Y;\n\ttarget_color.value[2] = Z;\n\treturn target_color;\n}\n\nstruct color OSA90_to_XYZ(struct color source_color) {\n\tdouble L, j, g;\n\tL = source_color.value[0];\n\tj = source_color.value[1];\n\tg = source_color.value[2];\n\tstruct color target_color;\n\tint max_iterations = 600;\n\tdouble X, Y, Z, previous_X, previous_Y, previous_Z, Delta;\n\tdouble L0, L1, L2, L3, j0, j1, j2, j3, g0, g1, g2, g3;\n\tstruct color color0, color1, color2, color3;\n\n\tgsl_matrix *matrix0 = gsl_matrix_alloc(3, 3);\n\tgsl_matrix *inverse_matrix0 = gsl_matrix_alloc(3, 3);\n\tgsl_matrix *matrix1 = gsl_matrix_alloc(3, 1);\n\tgsl_matrix *matrix2 = gsl_matrix_alloc(3, 1);\n\tgsl_permutation *permutation = gsl_permutation_alloc(3);\n\tint sign = 0;\n\n\t/* start values */\n\t/*X = 28.4; Y = 30.0; Z = 32.2; Delta = 0.5;*/\n\tX = 28.4; Y = 30.0; Z = 32.2; Delta = 0.005;\n\tgsl_matrix_set(matrix2, 0, 0, X);\n\tgsl_matrix_set(matrix2, 1, 0, Y);\n\tgsl_matrix_set(matrix2, 2, 0, Z);\n\n\tint i = 0; do {\n\t\t/* calculate colors for influence matrix */\n\t\tcolor0 = XYZ_values_to_OSA90(X, Y, Z);\n\t\tcolor1 = XYZ_values_to_OSA90(X+Delta, Y, Z);\n\t\tcolor2 = XYZ_values_to_OSA90(X, Y+Delta, Z);\n\t\tcolor3 = XYZ_values_to_OSA90(X, Y, Z+Delta);\n\t\tL0 = color0.value[0]; j0 = color0.value[1]; g0 = color0.value[2];\n\t\tL1 = color1.value[0]; j1 = color1.value[1]; g1 = color1.value[2];\n\t\tL2 = color2.value[0]; j2 = color2.value[1]; g2 = color2.value[2];\n\t\tL3 = color3.value[0]; j3 = color3.value[1]; g3 = color3.value[2];\n\n\t\tgsl_matrix_set(matrix0, 0, 0, (L1-L0)/Delta);\n\t\tgsl_matrix_set(matrix0, 0, 1, (L2-L0)/Delta);\n\t\tgsl_matrix_set(matrix0, 0, 2, (L3-L0)/Delta);\n\t\tgsl_matrix_set(matrix0, 1, 0, (j1-j0)/Delta);\n\t\tgsl_matrix_set(matrix0, 1, 1, (j2-j0)/Delta);\n\t\tgsl_matrix_set(matrix0, 1, 2, (j3-j0)/Delta);\n\t\tgsl_matrix_set(matrix0, 2, 0, (g1-g0)/Delta);\n\t\tgsl_matrix_set(matrix0, 2, 1, (g2-g0)/Delta);\n\t\tgsl_matrix_set(matrix0, 2, 2, (g3-g0)/Delta);\n\n\t\tgsl_matrix_set(matrix1, 0, 0, L-L0);\n\t\tgsl_matrix_set(matrix1, 1, 0, j-j0);\n\t\tgsl_matrix_set(matrix1, 2, 0, g-g0);\n\n\t\t/* update matrix2: matrix2 = inverse_matrix0 matrix1 + matrix2 */\n\t\t/* incremental term (inverse_matrix0 × matrix1) is divided by (5+cbrt(i)) */\n\t\tgsl_linalg_LU_decomp(matrix0, permutation, &sign);\n\t\tgsl_linalg_LU_invert(matrix0, permutation, inverse_matrix0);\n\t\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1/(5+cbrt(i)), inverse_matrix0, matrix1, 1.0, matrix2);\n\n\t\tprevious_X = X; previous_Y = Y; previous_Z = Z;\n\t\tX = gsl_matrix_get(matrix2, 0, 0);\n\t\tY = gsl_matrix_get(matrix2, 1, 0);\n\t\tZ = gsl_matrix_get(matrix2, 2, 0);\n\n\t\t/* printf(\"\\n%d\\n\", i);\n\t\tprint_matrix(matrix2); */\n\n\t\ti++;\n\t} while ((i < max_iterations) && ((fabs(X - previous_X) > 0.0001) || (fabs(Y - previous_Y) > 0.0001) || (fabs(Z - previous_Z) > 0.0001)));\n\n\t/*printf(\"Iterations: %i\\n\", i);*/\n\n\t/*free memory*/\n\tgsl_matrix_free(matrix0);\n\tgsl_matrix_free(inverse_matrix0);\n\tgsl_matrix_free(matrix1);\n\tgsl_matrix_free(matrix2);\n\t/*gsl_matrix_free(matrix_product);*/\n\tgsl_permutation_free(permutation);\n\n\tif (i == max_iterations) {\n\t\tfprintf(stderr, \"Error: Maximum iterations reached.\\n\");\n\t}\n\n\ttarget_color.value[0] = X;\n\ttarget_color.value[1] = Y;\n\ttarget_color.value[2] = Z;\n\treturn target_color;\n}\n\ndouble npow(double base, double exponent) {\n\tif (base < 0) {\n\t\treturn -pow(fabs(base), exponent);\n\t} else {\n\t\treturn pow(base, exponent);\n\t}\n}\n\nconst double c1 = 3424/pow(2, 12);\nconst double c2 = 2413/pow(2, 7);\nconst double c3 = 2392/pow(2, 7);\nconst double n = 2610/pow(2, 14);\nconst double p = 1.7*2523/pow(2, 5);\n\ndouble perceptual_quantizer(double cone_response) {\n\treturn npow((c1 + c2*npow(cone_response/10000, n)) / (1 + c3*npow(cone_response/10000, n)), p);\n}\n\ndouble invert_perceptual_quantizer(double cone_response) {\n\t/*printf(\"input: %f\\n\", cone_response);*/\n\t/*printf(\"return: %f\\n\", 10000*npow((c1 - npow(cone_response, 1/p))/(c3*npow(cone_response, 1/p) - c2), 1/n));*/\n\n\treturn 10000*npow((c1 - npow(cone_response, 1/p))/(c3*npow(cone_response, 1/p) - c2), 1/n);\n}\n\nconst double d = -0.56;\nconst double d0 = 1.6295499532821566E-11;\n\nstruct color XYZ_to_Jab(struct color source_color) {\n\tdouble X = source_color.value[0];\n\tdouble Y = source_color.value[1];\n\tdouble Z = source_color.value[2];\n\tdouble adjusted_X, adjusted_Y, L, M, S, adjusted_L, adjusted_M, adjusted_S, I, J, a, b, C, h;\n\tstruct color target_color;\n\n\tadjusted_X = 1.15*X - 0.15*Z;\n\tadjusted_Y = 0.66*Y + 0.34*X;\n\n\tL = 0.41478972*adjusted_X + 0.579999*adjusted_Y + 0.0146480*Z;\n\tM = -0.2015100*adjusted_X + 1.120649*adjusted_Y + 0.0531008*Z;\n\tS = -0.0166008*adjusted_X + 0.264800*adjusted_Y + 0.6684799*Z;\n\n\tadjusted_L = perceptual_quantizer(L);\n\tadjusted_M = perceptual_quantizer(M);\n\tadjusted_S = perceptual_quantizer(S);\n\n\tI = 0.5*adjusted_L + 0.5*adjusted_M;\n\tJ = ((1+d)*I)/(1+d*I) - d0;\n\n\ta = 3.524000*adjusted_L - 4.066708*adjusted_M + 0.542708*adjusted_S;\n\tb = 0.199076*adjusted_L + 1.096799*adjusted_M - 1.295875*adjusted_S;\n\n\ttarget_color.value[0] = J;\n\ttarget_color.value[1] = a;\n\ttarget_color.value[2] = b;\n\treturn target_color;\n}\n\nstruct color Jab_to_XYZ(struct color source_color) {\n\tdouble J = source_color.value[0];\n\tdouble a = source_color.value[1];\n\tdouble b = source_color.value[2];\n\tdouble I, adjusted_L, adjusted_M, adjusted_S, L, M, S, adjusted_X, adjusted_Y, X, Y, Z;\n\tstruct color target_color;\n\n\tI = ((J + d0)/(1 + d - d*(J + d0)));\n\n\tadjusted_L = I + 0.138605*a + 0.0580473*b;\n\tadjusted_M = I - 0.138605*a - 0.0580473*b;\n\tadjusted_S = I - 0.0960192*a - 0.811892*b;\n\n\tL = invert_perceptual_quantizer(adjusted_L);\n\tM = invert_perceptual_quantizer(adjusted_M);\n\tS = invert_perceptual_quantizer(adjusted_S);\n\n\tadjusted_X = 1.92423*L - 1.00479*M + 0.0376514*S;\n\tadjusted_Y = 0.350317*L + 0.726481*M - 0.0653844*S;\n\tZ = -0.0909828*L - 0.312728*M + 1.52277*S;\n\n\tX = (adjusted_X + 0.15*Z)/1.15;\n\tY = (adjusted_Y - 0.34*X)/0.66;\n\n\ttarget_color.value[0] = X;\n\ttarget_color.value[1] = Y;\n\ttarget_color.value[2] = Z;\n\treturn target_color;\n}\n\nconst double J_scale = 0.167174631034780;\n\nstruct color scale_Jab(struct color source_color) {\n\tstruct color target_color;\n\n\ttarget_color.value[0] = source_color.value[0]/J_scale*100;\n\ttarget_color.value[1] = source_color.value[1]/J_scale*100;\n\ttarget_color.value[2] = source_color.value[2];\n\treturn target_color;\n}\n\nstruct color unscale_Jab(struct color source_color) {\n\tstruct color target_color;\n\n\ttarget_color.value[0] = source_color.value[0]*J_scale/100;\n\ttarget_color.value[1] = source_color.value[1]*J_scale/100;\n\ttarget_color.value[2] = source_color.value[2];\n\treturn target_color;\n}\n\ndouble apply_gamma_correction(double value) {\n\tif (value > 0.0031308) {\n\t\treturn 1.055*pow(value, (1.0/2.4)) - 0.055;\n\t} else {\n\t\treturn 12.92*value;\n\t}\n}\n\ndouble remove_gamma_correction(double value) {\n\tif (value > 0.04045) {\n\t\treturn pow(((value+0.055)/1.055), 2.4);\n\t} else {\n\t\treturn value/12.92;\n\t}\n}\n\nstruct color XYZ_to_sRGB(struct color source_color) {\n\tdouble X, Y, Z;\n\tX = source_color.value[0];\n\tY = source_color.value[1];\n\tZ = source_color.value[2];\n\tstruct color target_color;\n\tdouble linear_R, linear_G, linear_B, R, G, B;\n\n\t/* XYZ source values range = [0, 100] */\n\tX = X/100.0; Y = Y/100.0; Z = Z/100.0;\n\n\t/* 2° observer, D65 illuminant */\n\tlinear_R = X* 3.2406 + Y*-1.5372 + Z*-0.4986;\n\tlinear_G = X*-0.9689 + Y* 1.8758 + Z* 0.0415;\n\tlinear_B = X* 0.0557 + Y*-0.2040 + Z* 1.0570;\n\n\tR = apply_gamma_correction(linear_R);\n\tG = apply_gamma_correction(linear_G);\n\tB = apply_gamma_correction(linear_B);\n\n\tif ((R<0.0) || (R>1.0) || (G<0.0) || (G>1.0) || (B<0.0) || (B>1.0)) {\n\t\terrno = ERANGE;\n\t}\n\n\t/* RGB target values range = [0, 255] */\n\ttarget_color.value[0] = R*255;\n\ttarget_color.value[1] = G*255;\n\ttarget_color.value[2] = B*255;\n\n\treturn target_color;\n}\n\nstruct color sRGB_to_XYZ(struct color source_color) {\n\tdouble R, G, B;\n\tR = source_color.value[0];\n\tG = source_color.value[1];\n\tB = source_color.value[2];\n\tstruct color target_color;\n\tdouble linear_R, linear_G, linear_B, X, Y, Z;\n\n\t/* RGB source values range = [0, 255] */\n\tR = R/255.0; G = G/255.0; B = B/255.0;\n\n\tlinear_R = remove_gamma_correction(R);\n\tlinear_G = remove_gamma_correction(G);\n\tlinear_B = remove_gamma_correction(B);\n\n\t/* 2° observer, D65 illuminant */\n\tX = linear_R*0.4124 + linear_G*0.3576 + linear_B*0.1805;\n\tY = linear_R*0.2126 + linear_G*0.7152 + linear_B*0.0722;\n\tZ = linear_R*0.0193 + linear_G*0.1192 + linear_B*0.9505;\n\n\t/* XYZ target values range = [0, 100] */\n\ttarget_color.value[0] = 100*X;\n\ttarget_color.value[1] = 100*Y;\n\ttarget_color.value[2] = 100*Z;\n\treturn target_color;\n}\n\nconst double Y_threshold = pow((6/29.0), 3);\nconst double D65_X = 95.0156;\nconst double D65_Y = 100;\nconst double D65_Z = 108.8199;\n\n/*const double D65_X = 97.31273;*/\n/*const double D65_Y = 100.00;*/\n/*const double D65_Z = 138.59590;*/\n\n\nstruct color XYZ_to_Luv(struct color source_color) {\n\t/* L, u, v stand for L*, u*, v* */\n\tdouble X, Y, Z, prime_u, prime_v, relative_Y, white_prime_u, white_prime_v, L, u, v;\n\tstruct color target_color;\n\n\tX = source_color.value[0];\n\tY = source_color.value[1];\n\tZ = source_color.value[2];\n\n\tprime_u = (4*X) / (X + 15*Y + 3*Z);\n\tprime_v = (9*Y) / (X + 15*Y + 3*Z);\n\n\twhite_prime_u = (4*D65_X) / (D65_X + 15*D65_Y + 3*D65_Z);\n\twhite_prime_v = (9*D65_Y) / (D65_X + 15*D65_Y + 3*D65_Z);\n\n\trelative_Y = Y/D65_Y;\n\n\tif (relative_Y > pow((6/29.0), 3)) {\n\t\tL = cbrt(relative_Y)*116 - 16;\n\t} else {\n\t\tL = relative_Y*pow((29/3.0), 3);\n\t}\n\n\tu = 13*L*(prime_u - white_prime_u);\n\tv = 13*L*(prime_v - white_prime_v);\n\n\ttarget_color.value[0] = L;\n\ttarget_color.value[1] = u;\n\ttarget_color.value[2] = v;\n\treturn target_color;\n}\n\nstruct color Luv_to_XYZ(struct color source_color) {\n\t/* L, u, v stand for L*, u*, v* */\n\tdouble L, u, v, white_prime_u, white_prime_v, prime_u, prime_v, X, Y, Z;\n\tstruct color target_color;\n\n\tL = source_color.value[0];\n\tu = source_color.value[1];\n\tv = source_color.value[2];\n\n\twhite_prime_u = (4*D65_X) / (D65_X + 15*D65_Y + 3*D65_Z);\n\twhite_prime_v = (9*D65_Y) / (D65_X + 15*D65_Y + 3*D65_Z);\n\n\tprime_u = u/(13*L) + white_prime_u;\n\tprime_v = v/(13*L) + white_prime_v;\n\n\tif (L > 8.0) {\n\t\tY = D65_Y*pow((L + 16)/116.0, 3);\n\t} else {\n\t\tY = D65_Y*L*pow(3/29.0, 3);\n\t}\n\n\tX = Y * (9*prime_u)/(4.0*prime_v);\n\tZ = Y * (12 - 3*prime_u - 20*prime_v)/(4.0*prime_v);\n\n\ttarget_color.value[0] = X;\n\ttarget_color.value[1] = Y;\n\ttarget_color.value[2] = Z;\n\treturn target_color;\n}\n\n/* OSA74 range: -19.1032--10.0938 (29.1970) */\n\nstruct color OSA74_to_pOSA74(struct color source_color) {\n\tdouble L, j, g, new_L, chroma, hue;\n\tstruct color target_color;\n\n\tL = source_color.value[0];\n\tj = source_color.value[1];\n\tg = source_color.value[2];\n\n\tnew_L = (L*sqrt(2) + 19.1032)*100/29.1970;\n\tchroma = hypot(j, g)*100/29.1970;\n\thue = atan2(g, j)*180.0/M_PI;\n\n\tif (hue < 0) {\n\t\thue = hue + 360;\n\t}\n\n\ttarget_color.value[0] = new_L;\n\ttarget_color.value[1] = chroma;\n\ttarget_color.value[2] = hue;\n\treturn target_color;\n}\n\nstruct color pOSA74_to_OSA74(struct color source_color) {\n\tdouble new_L, chroma, hue, L, angle, j, g;\n\tstruct color target_color;\n\n\tnew_L = source_color.value[0];\n\tchroma = source_color.value[1];\n\thue = source_color.value[2];\n\n\tL = (new_L*29.1970/100 - 19.1032)/sqrt(2);\n\n\tangle = hue/180*(M_PI);\n\tj = cos(angle)*chroma*29.1970/100;\n\tg = sin(angle)*chroma*29.1970/100;\n\n\ttarget_color.value[0] = L;\n\ttarget_color.value[1] = j;\n\ttarget_color.value[2] = g;\n\treturn target_color;\n}\n\nint RGB_to_hex(struct color RGB_color) {\n\tint R = (int)(RGB_color.value[0] + 0.5);\n\tint G = (int)(RGB_color.value[1] + 0.5);\n\tint B = (int)(RGB_color.value[2] + 0.5);\n\treturn (R<<16) | (G<<8) | B;\n}\n\nstruct color hex_to_RGB(int hex_value) {\n\tstruct color RGB_color;\n\tRGB_color.value[0] = ((hex_value>>16) & 0xFF)/255.0;\n\tRGB_color.value[1] = ((hex_value>>8) & 0xFF)/255.0;\n\tRGB_color.value[2] = (hex_value & 0xFF)/255.0;\n\treturn RGB_color;\n}\n\n\nint main(int argc, char *argv[]) {\n\tint i;\n\tstruct color source_color;\n\tstruct color intermediate_color;\n\tstruct color target_color;\n\tchar next_char;\n\tchar *source_format = argv[1];\n\tchar *target_format = argv[2];\n\n\t/* check arguments */\n\n\t/* check argument count */\n\tif (argc != 6) {\n\t\tfprintf(stderr, \"Usage: %s source_format target_format value1 value2 value3\\n\", argv[0]);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tif (strcmp(source_format, target_format) == 0) {\n\t\tfprintf(stderr, \"Source and target formats are identical.\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t/* check if color values are numbers */\n\tfor (i = 3; i < argc; i++) {\n\t\tif (sscanf(argv[i], \"%lf%c\", &source_color.value[i-3], &next_char) != 1) {\n\t\t\tfprintf(stderr, \"Invalid color values, values must be numbers.\\n\");\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\n\t/* OSA/polar conversions do not need intermediate conversion to XYZ */\n\tif ((strcmp(source_format, \"pOSA74\") == 0) && (strcmp(target_format, \"OSA74\") == 0)) {\n\t\ttarget_color = pOSA74_to_OSA74(source_color);\n\t\tprintf(\"%.2f %.2f %.2f\\n\", target_color.value[0], target_color.value[1], target_color.value[2]);\n\t\treturn EXIT_SUCCESS;\n\t} else if ((strcmp(source_format, \"OSA74\") == 0) && (strcmp(target_format, \"pOSA74\") == 0)) {\n\t\ttarget_color = OSA74_to_pOSA74(source_color);\n\t\tprintf(\"%.2f %.2f %.2f\\n\", target_color.value[0], target_color.value[1], target_color.value[2]);\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\t/* convert from source format to XYZ */\n\tif (strcmp(source_format, \"Jab\") == 0) {\n\t\tintermediate_color = Jab_to_XYZ(polar_to_cartesian(unscale_Jab(source_color)));\n\t\t/*intermediate_color = Jab_to_XYZ(polar_to_cartesian(source_color));*/\n\t\t/*intermediate_color = Jab_to_XYZ(source_color);*/\n\t} else if (strcmp(source_format, \"LCh\") == 0) {\n\t\tintermediate_color = Luv_to_XYZ(polar_to_cartesian(source_color));\n\t} else if (strcmp(source_format, \"Luv\") == 0) {\n\t\tintermediate_color = Luv_to_XYZ(source_color);\n\t} else if (strcmp(source_format, \"OSA74\") == 0) {\n\t\tintermediate_color = OSA74_to_XYZ(source_color);\n\t} else if (strcmp(source_format, \"OSA90\") == 0) {\n\t\tintermediate_color = OSA90_to_XYZ(source_color);\n\t} else if (strcmp(source_format, \"pOSA74\") == 0) {\n\t\t/*intermediate_color = OSA90_to_XYZ(polar_to_OSA(source_color));*/\n\t\tintermediate_color = OSA74_to_XYZ(pOSA74_to_OSA74(source_color));\n\t} else if (strcmp(source_format, \"sRGB\") == 0) {\n\t\tintermediate_color = sRGB_to_XYZ(source_color);\n\t} else if (strcmp(source_format, \"XYZ\") == 0) {\n\t\tintermediate_color = source_color;\n\t} else {\n\t\tfprintf(stderr, \"Invalid source format.\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t/* convert from XYZ to target format */\n\tif (strcmp(target_format, \"Jab\") == 0) {\n\t\ttarget_color = scale_Jab(cartesian_to_polar(XYZ_to_Jab(intermediate_color)));\n\t\t/*target_color = cartesian_to_polar(XYZ_to_Jab(intermediate_color));*/\n\t\t/*target_color = XYZ_to_Jab(intermediate_color);*/\n\t} else if (strcmp(target_format, \"LCh\") == 0) {\n\t\ttarget_color = cartesian_to_polar(XYZ_to_Luv(intermediate_color));\n\t} else if (strcmp(target_format, \"Luv\") == 0) {\n\t\ttarget_color = XYZ_to_Luv(intermediate_color);\n\t} else if (strcmp(target_format, \"OSA74\") == 0) {\n\t\ttarget_color = XYZ_to_OSA74(intermediate_color);\n\t} else if (strcmp(target_format, \"OSA90\") == 0) {\n\t\ttarget_color = XYZ_to_OSA90(intermediate_color);\n\t} else if (strcmp(target_format, \"pOSA74\") == 0) {\n\t\ttarget_color = OSA74_to_pOSA74(XYZ_to_OSA74(intermediate_color));\n\t} else if (strcmp(target_format, \"polarOSA74\") == 0) {\n\t\ttarget_color = cartesian_to_polar(XYZ_to_OSA74(intermediate_color));\n\t} else if (strcmp(target_format, \"sRGB\") == 0) {\n\t\ttarget_color = XYZ_to_sRGB(intermediate_color);\n\t} else if (strcmp(target_format, \"XYZ\") == 0) {\n\t\ttarget_color = intermediate_color;\n\t} else {\n\t\tfprintf(stderr, \"Invalid target format.\");\n\t\treturn EXIT_FAILURE;\n\t}\n\tif (errno == ERANGE) {\n\t\tfprintf(stderr, \"The requested color lies outside of the %s gamut.\\n\", target_format);\n\t\t/*return EXIT_FAILURE;*/\n\t\t/*printf(\"%d %d %d\\n\", 149, 149, 148);*/\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\t/* round RGB values to integers */\n\tif (strcmp(target_format, \"sRGB\") == 0) {\n\t\t/*printf(\"%.0f %.0f %.0f\\n\", target_color.value[0], target_color.value[1], target_color.value[2]);*/\n\t\tprintf(\"#%06x\\n\", RGB_to_hex(target_color));\n\t} else {\n\t\tprintf(\"%.4f %.4f %.4f\\n\", target_color.value[0], target_color.value[1], target_color.value[2]);\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "b944eba609700f51ced548743f216b4957b818bf", "size": 22262, "ext": "c", "lang": "C", "max_stars_repo_path": "converter.c", "max_stars_repo_name": "joshuakraemer/color-converter", "max_stars_repo_head_hexsha": "c4698edcd829881aa9cb40f5833d03cf3b9e8151", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "converter.c", "max_issues_repo_name": "joshuakraemer/color-converter", "max_issues_repo_head_hexsha": "c4698edcd829881aa9cb40f5833d03cf3b9e8151", "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": "converter.c", "max_forks_repo_name": "joshuakraemer/color-converter", "max_forks_repo_head_hexsha": "c4698edcd829881aa9cb40f5833d03cf3b9e8151", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9397417504, "max_line_length": 139, "alphanum_fraction": 0.6750067379, "num_tokens": 7841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870767, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.735789453109519}} {"text": "#include \n#include \n#include \n\nvoid evaluate(double x) {\n double probability = gsl_sf_erf(x);\n\n printf(\n \"The probability that Normal(0, 1) random variable has a value \"\n \"between %g and %g is: %g\\n\", -x, x, probability\n );\n\n double area = 1 - 2 * gsl_cdf_gaussian_P(-x, 1);\n\n printf(\n \"The integral of a Normal(0, 1) distribution \"\n \"between %g and %g is: %g\\n\", -x, x, area\n );\n}\n\nint main() {\n evaluate(0.25);\n evaluate(1.96);\n}\n", "meta": {"hexsha": "4e5748d489872be88b504747411a943d30235e7b", "size": 494, "ext": "c", "lang": "C", "max_stars_repo_path": "c/error_function/erf_gsl.c", "max_stars_repo_name": "tardate/LittleCodingKata", "max_stars_repo_head_hexsha": "25f37f2a422d1f63a7d03b25a7876d6fa707cf7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-06-02T05:12:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T02:50:55.000Z", "max_issues_repo_path": "c/error_function/erf_gsl.c", "max_issues_repo_name": "tardate/LittleCodingKata", "max_issues_repo_head_hexsha": "25f37f2a422d1f63a7d03b25a7876d6fa707cf7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2021-03-09T00:55:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T05:54:38.000Z", "max_forks_repo_path": "c/error_function/erf_gsl.c", "max_forks_repo_name": "tardate/LittleCodingKata", "max_forks_repo_head_hexsha": "25f37f2a422d1f63a7d03b25a7876d6fa707cf7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-06-15T10:13:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T02:51:16.000Z", "avg_line_length": 19.76, "max_line_length": 68, "alphanum_fraction": 0.6194331984, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7354792520661306}} {"text": "#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char *argv[]) {\n double mu = 1.0;\n if (argc > 1)\n mu = atof(argv[1]);\n int n = 1;\n if (argc > 2)\n n = atoi(argv[2]);\n unsigned long seed;\n if (argc > 3)\n seed = atol(argv[3]);\n else\n seed = time(NULL);\n gsl_rng_env_setup();\n gsl_rng *rng = gsl_rng_alloc(gsl_rng_default);\n gsl_rng_set(rng, seed);\n for (int i = 0; i < n; i++) {\n double x = gsl_ran_exponential(rng, mu);\n printf(\"%.12f\\n\", x);\n }\n gsl_rng_free(rng);\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "696e1222c789c36a59c17a307501c5c5b28e87a6", "size": 655, "ext": "c", "lang": "C", "max_stars_repo_path": "Math/GSL/RNGs/generate_exp_distr.c", "max_stars_repo_name": "Gjacquenot/training-material", "max_stars_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "Math/GSL/RNGs/generate_exp_distr.c", "max_issues_repo_name": "Gjacquenot/training-material", "max_issues_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "Math/GSL/RNGs/generate_exp_distr.c", "max_forks_repo_name": "Gjacquenot/training-material", "max_forks_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 22.5862068966, "max_line_length": 50, "alphanum_fraction": 0.5526717557, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7354280907771328}} {"text": "/**\n * Finite element method solver. This solver solves laplace(u) = 6 on square\n * [0, 1]x[0, 1]. Boundary conditions are set to be 1 + x^2 + 2y^2.\n *\n * Exact solution of this problem is 1 + x^2 + 2y^2. We will test against this\n * solution in the end.\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define F -6.0\n\n#define likely(x) __builtin_expect(!!(x), 1)\n#define unlikely(x) __builtin_expect(!!(x), 0)\n\nstatic void compute_local_a(uint *point_id, REAL *pointlist, REAL *matrix);\nstatic void compute_local_f(uint *point_id, REAL *pointlist, REAL *matrix);\nstatic void generate_mesh(struct triangulateio *io, struct triangulateio *out);\nstatic REAL boundary_condition(uint point_id, struct triangulateio *out);\nstatic REAL exact_solution(uint point_id, struct triangulateio *out);\n\nint main(int argc, char **argv)\n{\n struct triangulateio in, out;\n uint num_of_points;\n uint num_of_triangles;\n REAL *local_A, *local_F, *global_A, *global_F;\n\n /* generate geometry */\n generate_mesh(&in, &out);\n\n num_of_points = out.numberofpoints;\n num_of_triangles = out.numberoftriangles;\n\n /**\n * Allocate all matrix data structures\n */\n global_A = malloc(num_of_points * num_of_points * sizeof(REAL));\n global_F = malloc(num_of_points * sizeof(REAL));\n local_A = malloc(3 * 3 * sizeof(REAL));\n local_F = malloc(3 * 3 * sizeof(REAL));\n\n assert(global_A != NULL);\n assert(global_F != NULL);\n assert(local_A != NULL);\n assert(local_F != NULL);\n\n memset(global_A, 0, num_of_points * num_of_points * sizeof(REAL));\n memset(global_F, 0, num_of_points * sizeof(REAL));\n\n /**\n * Matrix assembly without boundary conditions\n */\n for (size_t n = 0; n < num_of_triangles; n++) {\n // three points that describe triangle\n uint point_id[3];\n memcpy(point_id, &out.trianglelist[n * 3], 3 * sizeof(int));\n compute_local_a(point_id, out.pointlist, local_A);\n compute_local_f(point_id, out.pointlist, local_F);\n\n for (size_t i = 0; i < 3; i++) {\n int i1 = point_id[i];\n for (int j = 0; j < 3; j++) {\n int j1 = point_id[j];\n global_A[i1 * num_of_points + j1] += local_A[i * 3 + j];\n global_F[i1] += local_F[i * 3 + j] * F;\n }\n }\n }\n\n for (size_t i = 0; i < num_of_points; i++) {\n if (out.pointmarkerlist[i] == 1) {\n for (size_t j = 0; j < num_of_points; j++) {\n global_F[j] -= global_A[j * num_of_points + i]\n * boundary_condition(i, &out);\n global_A[i * num_of_points + j] = 0;\n global_A[j * num_of_points + i] = 0;\n }\n global_A[i * num_of_points + i] = 1.0;\n global_F[i] = boundary_condition(i, &out);\n }\n }\n\n\n /*************************************************************************\n ************************ Solve Ax = b ***********************************\n *************************************************************************/\n int ipiv[num_of_points];\n int info = LAPACKE_dgesv(LAPACK_ROW_MAJOR,\n num_of_points,\n 1,\n global_A,\n num_of_points,\n ipiv,\n global_F,\n 1);\n if (info > 0) {\n printf(\"The factorization has been completed, but the factor U is\\n\");\n printf(\"exactly singular, so the solution could not be computed.\");\n goto mem_free;\n } else if (info < 0) {\n printf(\"%d-th argument had an illegal value\\n\", -info);\n goto mem_free;\n }\n\n //TODO: implement max error\n printf(\"\\nSolution in point vs exact solution\\n\");\n for (size_t i = 0; i < num_of_points; i++) {\n double temp = exact_solution(i, &out);\n printf(\n \"%lf \\t %lf \\t %lf\\n\", temp, global_F[i], temp - global_F[i]);\n }\n\nmem_free:\n /* free all Triangle data structures */\n free(out.edgelist);\n free(out.edgemarkerlist);\n free(out.neighborlist);\n free(out.pointlist);\n free(out.trianglelist);\n free(out.segmentlist);\n free(out.segmentmarkerlist);\n free(out.pointmarkerlist);\n\n /* free all input data structures */\n free(in.regionlist);\n free(in.pointlist);\n\n /* free all matrix arrays */\n free(global_A);\n free(local_A);\n free(global_F);\n free(local_F);\n\n return info;\n}\n\nstatic void generate_mesh(struct triangulateio *in, struct triangulateio *out)\n{\n in->numberofpoints = 4;\n in->numberofpointattributes = 0;\n in->pointattributelist = (REAL *) NULL;\n in->pointlist = malloc(in->numberofpoints * 2 * sizeof(REAL));\n\n in->pointlist[0] = 0.0;\n in->pointlist[1] = 0.0;\n\n in->pointlist[2] = 0.0;\n in->pointlist[3] = 1.0;\n\n in->pointlist[4] = 1.0;\n in->pointlist[5] = 1.0;\n\n in->pointlist[6] = 1.0;\n in->pointlist[7] = 0.0;\n\n in->pointmarkerlist = (int *) NULL;\n\n in->numberofsegments = 0;\n in->numberofholes = 0;\n in->numberofregions = 1;\n in->regionlist = malloc(in->numberofregions * 4 * sizeof(REAL));\n in->regionlist[0] = 0.5;\n in->regionlist[1] = 0.5;\n in->regionlist[2] = 7.0; /* Regional attribute (for whole mesh). */\n in->regionlist[3] = 0.1; /* Area constraint. */\n\n out->pointlist = (REAL *) NULL;\n out->pointmarkerlist = (int *) NULL;\n out->trianglelist = (int *) NULL;\n out->triangleattributelist = (REAL *) NULL;\n out->neighborlist = (int *) NULL;\n out->segmentlist = (int *) NULL;\n out->segmentmarkerlist = (int *) NULL;\n out->edgelist = (int *) NULL;\n out->edgemarkerlist = (int *) NULL;\n\n /* Triangulate the points. read and write a PSLG (p), preserve the\n * convex hull (c), zero index (z), produce edge list (e), produce\n * neighbor list (n), be quiet (Q), area should be less than 0.1 (a.1)\n * and generate triangle for FEM (q).\n */\n triangulate(\"pzceQna.1q\", in, out, (struct triangulateio *) NULL);\n}\n\nstatic void compute_local_a(uint *point_id, REAL *pointlist, REAL *matrix)\n{\n REAL dx23 = pointlist[2 * point_id[1]] - pointlist[2 * point_id[2]];\n REAL dx31 = pointlist[2 * point_id[2]] - pointlist[2 * point_id[0]];\n REAL dx12 = pointlist[2 * point_id[0]] - pointlist[2 * point_id[1]];\n REAL dy23 = pointlist[2 * point_id[1] + 1] - pointlist[2 * point_id[2] + 1];\n REAL dy31 = pointlist[2 * point_id[2] + 1] - pointlist[2 * point_id[0] + 1];\n REAL dy12 = pointlist[2 * point_id[0] + 1] - pointlist[2 * point_id[1] + 1];;\n\n REAL area = 0.5 * (dx31 * dy12 - dy31 * dx12);\n REAL _tmp_mult = 0.25 / area;\n matrix[0] = _tmp_mult * (dx23 * dx23 + dy23 * dy23);\n matrix[1] = _tmp_mult * (dx23 * dx31 + dy23 * dy31);\n matrix[2] = _tmp_mult * (dx23 * dx12 + dy23 * dy12);\n matrix[3] = _tmp_mult * (dx31 * dx23 + dy31 * dy23);\n matrix[4] = _tmp_mult * (dx31 * dx31 + dy31 * dy31);\n matrix[5] = _tmp_mult * (dx31 * dx12 + dy31 * dy12);\n matrix[6] = _tmp_mult * (dx12 * dx23 + dy12 * dy23);\n matrix[7] = _tmp_mult * (dx12 * dx31 + dy12 * dy31);\n matrix[8] = _tmp_mult * (dx12 * dx12 + dy12 * dy12);\n}\n\nstatic inline void compute_local_f(uint *point_id, REAL *pointlist, REAL *matrix)\n{\n REAL dx31 = pointlist[2 * point_id[2]] - pointlist[2 * point_id[0]];\n REAL dx12 = pointlist[2 * point_id[0]] - pointlist[2 * point_id[1]];\n REAL dy31 = pointlist[2 * point_id[2] + 1] - pointlist[2 * point_id[0] + 1];\n REAL dy12 = pointlist[2 * point_id[0] + 1] - pointlist[2 * point_id[1] + 1];\n\n REAL area = 0.5 * (dx31 * dy12 - dy31 * dx12);\n REAL c_diag = area / 6.0;\n REAL c_off = area / 12.0;\n\n matrix[0] = c_diag; matrix[1] = c_off; matrix[2] = c_off;\n matrix[3] = c_off; matrix[4] = c_diag; matrix[5] = c_off;\n matrix[6] = c_off; matrix[7] = c_off; matrix[8] = c_diag;\n}\n\nstatic inline REAL exact_solution(uint point_id, struct triangulateio *out)\n{\n REAL x = out->pointlist[2 * point_id];\n REAL y = out->pointlist[2 * point_id + 1];\n return (1.0 + x * x + 2.0 * y * y);\n}\n\nstatic inline REAL boundary_condition(uint point_id, struct triangulateio *out)\n{\n REAL x = out->pointlist[2 * point_id];\n REAL y = out->pointlist[2 * point_id + 1];\n return (1.0 + x * x + 2.0 * y * y);\n}\n", "meta": {"hexsha": "9961bb725ae4bc29648e9f3e59720b28fb921edc", "size": 8551, "ext": "c", "lang": "C", "max_stars_repo_path": "src/main.c", "max_stars_repo_name": "djanekovic/fem2d_poisson", "max_stars_repo_head_hexsha": "59b6f6e79f2852a8041013d029b388d90e555a21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.c", "max_issues_repo_name": "djanekovic/fem2d_poisson", "max_issues_repo_head_hexsha": "59b6f6e79f2852a8041013d029b388d90e555a21", "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/main.c", "max_forks_repo_name": "djanekovic/fem2d_poisson", "max_forks_repo_head_hexsha": "59b6f6e79f2852a8041013d029b388d90e555a21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0450819672, "max_line_length": 85, "alphanum_fraction": 0.5675359607, "num_tokens": 2536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7348244612558066}} {"text": "#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"qdm.h\"\n\nvoid\nqdm_mspline_vector(\n gsl_vector *result,\n const double tau,\n const size_t spline_df,\n const gsl_vector *knots\n)\n{\n size_t bin = qdm_vector_search(knots, tau);\n\n gsl_vector_set(result, 0, 0);\n\n for (size_t m = 0; m < result->size - 1; m++) {\n double v;\n\n if (bin < m) {\n v = 0;\n } else if (bin - spline_df + 1 > m) {\n v = 0;\n } else if (bin == m) {\n double n = 3 * gsl_sf_pow_int(tau - gsl_vector_get(knots, m), 2);\n double d1 = gsl_vector_get(knots, m + 1) - gsl_vector_get(knots, m);\n double d2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m);\n double d3 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);\n\n v = n / (d1 * d2 * d3);\n } else if (bin == m + 1) {\n double i1 = 1 / (gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1));\n\n double i2n = gsl_sf_pow_int(tau - gsl_vector_get(knots, m), 2);\n double i2d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);\n double i2d2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m);\n double i2d3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);\n double i2 = i2n / (i2d1 * i2d2 * i2d3);\n\n double i3n = gsl_sf_pow_int(gsl_vector_get(knots, m + 3) - tau, 2);\n double i3d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);\n double i3d2 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1);\n double i3d3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);\n double i3 = i3n / (i3d1 * i3d2 * i3d3);\n\n v = 3 * (i1 - i2 - i3);\n } else {\n double n = 3 * gsl_sf_pow_int(gsl_vector_get(knots, m + 3) - tau, 2);\n double d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);\n double d2 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1);\n double d3 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 2);\n double d = d1 * d2 * d3;\n\n v = n / d;\n }\n\n gsl_vector_set(result, m + 1, v);\n }\n}\n\nvoid\nqdm_mspline_matrix(gsl_matrix *result, const size_t spline_df, const gsl_vector *x, const gsl_vector *knots)\n{\n for (size_t i = 0; i < result->size1; i++) {\n gsl_vector_view row = gsl_matrix_row(result, i);\n qdm_mspline_vector(&row.vector, gsl_vector_get(x, i), spline_df, knots);\n }\n}\n", "meta": {"hexsha": "eaf027bf8ed160f4d2116ab962cf56be5aec7883", "size": 2494, "ext": "c", "lang": "C", "max_stars_repo_path": "src/mspline.c", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mspline.c", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "src/mspline.c", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3896103896, "max_line_length": 108, "alphanum_fraction": 0.6142742582, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7339353018270031}} {"text": "/*\n * mixmax.c\n * MIXMAX, A Pseudo-Random Number Generator\n *\n * Copyright Konstantin Savvidy.\n *\n * Free to use, academic or commercial. Do not redistribute without permission.\n *\n *\tG.K.Savvidy and N.G.Ter-Arutyunian,\n * On the Monte Carlo simulation of physical systems,\n *\tJ.Comput.Phys. 97, 566 (1991);\n * Preprint EPI-865-16-86, Yerevan, Jan. 1986\n *\n * K.Savvidy\n * The MIXMAX random number generator\n * Comp. Phys. Commun. 196 (2015), pp 161–165\n * http://dx.doi.org/10.1016/j.cpc.2015.06.003\n *\n */\n\n#include \n#include \n\n#ifndef MIXMAX_H_\n#define MIXMAX_H_\n\n#define USE_INLINE_ASM\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\t\n#ifndef _N\n#define N 240\n/* The currently recommended generator is the three-parameter MIXMAX with\nN=240, s=487013230256099140, m=2^51+1\n\n Other newly recommended N are N=8, 17 and 240, \n as well as the ordinary MIXMAX with N=256 and s=487013230256099064\n\n Since the algorithm is linear in N, the cost per number is almost independent of N.\n */\n#else\n#define N _N\n#endif\n\n#ifndef __LP64__\ntypedef uint64_t myuint;\n//#warning but no problem, 'myuint' is 'uint64_t'\n#else\ntypedef unsigned long long int myuint;\n//#warning but no problem, 'myuint' is 'unsigned long long int'\n#endif\n\nstruct rng_state_st\n{\n myuint V[N];\n myuint sumtot;\n int counter;\n FILE* fh;\n};\n\ntypedef struct rng_state_st rng_state_t; // C struct alias\n\nint rng_get_N(void); // get the N programmatically, useful for checking the value for which the library was compiled\n\nrng_state_t *rng_alloc(); /* allocate the state */\nint rng_free(rng_state_t* X); /* free memory occupied by the state */\nrng_state_t *rng_copy(myuint *Y); /* init from vector, takes the vector Y, \n returns pointer to the newly allocated and initialized state */\nvoid read_state(rng_state_t* X, const char filename[] );\nvoid print_state(rng_state_t* X);\n int iterate(rng_state_t* X);\n myuint iterate_raw_vec(myuint* Y, myuint sumtotOld);\n\n\n// FUNCTIONS FOR SEEDING\n\ntypedef uint32_t myID_t;\n\nvoid seed_uniquestream(rng_state_t* X, myID_t clusterID, myID_t machineID, myID_t runID, myID_t streamID );\n/*\n best choice: will make a state vector from which you can get at least 10^100 numbers \n guaranteed mathematically to be non-colliding with any other stream prepared from another set of 32bit IDs,\n so long as it is different by at least one bit in at least one of the four IDs\n\t\t\t-- useful if you are running a parallel simulation with many clusters, many CPUs each\n */\n\nvoid seed_spbox(rng_state_t* X, myuint seed); // non-linear method, makes certified unique vectors, probability for streams to collide is < 1/10^4600\n\nvoid seed_vielbein(rng_state_t* X, unsigned int i); // seeds with the i-th unit vector, i = 0..N-1, for testing only\n\n\n\n// FUNCTIONS FOR GETTING RANDOM NUMBERS\n\n#ifdef __MIXMAX_C\n\tmyuint get_next(rng_state_t* X); // returns 64-bit int, which is between 1 and 2^61-1 inclusive\n\tdouble get_next_float(rng_state_t* X); // returns double precision floating point number in (0,1]\n#endif //__MIXMAX_C\n\nvoid fill_array(rng_state_t* X, unsigned int n, double *array); // fastest method: set n to a multiple of N (e.g. n=256)\n\nvoid iterate_and_fill_array(rng_state_t* X, double *array); // fills the array with N numbers\n\nmyuint precalc(rng_state_t* X);\n/* needed if the state has been changed by something other than iterate, but no worries, seeding functions call this for you when necessary */\nmyuint apply_bigskip(myuint* Vout, myuint* Vin, myID_t clusterID, myID_t machineID, myID_t runID, myID_t streamID );\n// applies a skip of some number of steps calculated from the four IDs\nvoid branch_inplace( rng_state_t* Xin, myID_t* ID ); // almost the same as apply_bigskip, but in-place and from a vector of IDs\n\n\n#define BITS 61\n\n/* magic with Mersenne Numbers */\n\n#define M61 2305843009213693951ULL\n\n myuint modadd(myuint foo, myuint bar);\n myuint modmulM61(myuint s, myuint a);\n myuint fmodmulM61(myuint cum, myuint s, myuint a);\n\n#define MERSBASE M61 //xSUFF(M61)\n#define MOD_PAYNE(k) ((((k)) & MERSBASE) + (((k)) >> BITS) ) // slightly faster than my old way, ok for addition\n#define MOD_REM(k) ((k) % MERSBASE ) // latest Intel CPU is supposed to do this in one CPU cycle, but on my machines it seems to be 20% slower than the best tricks\n#define MOD_MERSENNE(k) MOD_PAYNE(k)\n\n//#define INV_MERSBASE (0x1p-61)\n#define INV_MERSBASE (0.4336808689942017736029811203479766845703E-18)\n//const double INV_MERSBASE=(0.4336808689942017736029811203479766845703E-18); // gives \"duplicate symbol\" error\n \n// the charpoly is irreducible for the combinations of N and SPECIAL\n\n#if (N==256)\n#define SPECIALMUL 0\n#define SPECIAL 487013230256099064 // s=487013230256099064, m=1 -- good old MIXMAX\n#define MOD_MULSPEC(k) fmodmulM61( 0, SPECIAL , (k) )\n \n#elif (N==8)\n#define SPECIALMUL 53 // m=2^53+1\n#define SPECIAL 0\n \n#elif (N==17)\n#define SPECIALMUL 36 // m=2^36+1, other valid possibilities are m=2^13+1, m=2^19+1, m=2^24+1\n#define SPECIAL 0\n \n#elif (N==40)\n#define SPECIALMUL 42 // m=2^42+1\n#define SPECIAL 0\n\n#elif (N==60)\n#define SPECIALMUL 52 // m=2^52+1\n#define SPECIAL 0\n\n#elif (N==96)\n#define SPECIALMUL 55 // m=2^55+1\n#define SPECIAL 0\n \n#elif (N==120)\n#define SPECIALMUL 51 // m=2^51+1 and a SPECIAL=+1 (!!!)\n#define SPECIAL 1\n#define MOD_MULSPEC(k) (k)\n\n#elif (N==240)\n#define SPECIALMUL 51 // m=2^51+1 and a SPECIAL=487013230256099140\n#define SPECIAL 487013230256099140ULL\n#define MOD_MULSPEC(k) fmodmulM61( 0, SPECIAL , (k) )\n \n#elif (N==44851)\n#define SPECIALMUL 0\n#define SPECIAL -3\n#define MOD_MULSPEC(k) MOD_MERSENNE(3*(MERSBASE-(k)))\n\n\n#else\n#warning Not a verified N, you are on your own!\n#define SPECIALMUL 58\n#define SPECIAL 0\n \n#endif // list of interesting N for modulus M61 ends here\n\n inline \tmyuint get_next_inlined(rng_state_t* X) { // forward output\n int i;\n i=X->counter;\n \n if (i<=(N-1) ){\n X->counter++;\n return X->V[i];\n }else{\n X->sumtot = iterate_raw_vec(X->V, X->sumtot);\n X->counter=2;\n return X->V[1];\n }\n }\n \n// inline \tmyuint get_next_inlined(rng_state_t* X) { // backward output, slightly faster\n// int i;\n// i=X->counter;\n// \n// if ( i!=0 ){\n// X->counter--;\n// return X->V[i];\n// }else{\n// X->sumtot = iterate_raw_vec(X->V, X->sumtot);\n// X->counter=N-2;\n// return X->V[N-1];\n// }\n// }\n \n inline double get_next_float_inlined(rng_state_t* X){\n /* cast to signed int trick suggested by Andrzej Görlich */\n int64_t Z=(int64_t)get_next_inlined(X);\n double F;\n#if defined(__GNUC__) && (__GNUC__ < 5) && (!defined(__ICC)) && defined(__x86_64__) && defined(__SSE2_MATH__) && defined(USE_INLINE_ASM)\n#warning Using the inline assembler\n /* using SSE inline assemly to zero the xmm register, just before int64 -> double conversion,\n not really necessary in GCC-5 or better, but huge penalty on earlier compilers\n */\n __asm__ __volatile__(\"pxor %0, %0; \"\n :\"=x\"(F)\n );\n#endif\n F=Z;\n return F*INV_MERSBASE;\n }\n\n#ifndef __MIXMAX_C // c++ can put code into header files, why cant we? (with the inline declaration, should be safe from duplicate-symbol error)\n\t\n#define get_next(X) get_next_inlined(X)\n#define get_next_float(X) get_next_float_inlined(X) // get_next_float_packbits(X) //\n \n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wstrict-aliasing\"\n inline double convert1double(uint64_t u){\n const double one = 1;\n const uint64_t onemask = *(uint64_t*)&one;\n uint64_t tmp = (u>>9) | onemask; // must not have bits higher than 52 !\n double d = *(double*)&tmp;\n return d-1.0;\n }\n \n inline double get_next_float_packbits(rng_state_t* X){\n uint64_t Z=get_next_inlined(X); // must not have bits higher than 52 !\n return convert1double(Z);\n }\n#pragma GCC diagnostic pop\n\n#endif // __MIXMAX_C\n\n// ERROR CODES - exit() is called with these\n#define ARRAY_INDEX_OUT_OF_BOUNDS 0xFF01\n#define SEED_WAS_ZERO 0xFF02\n#define ERROR_READING_STATE_FILE 0xFF03\n#define ERROR_READING_STATE_COUNTER 0xFF04\n#define ERROR_READING_STATE_CHECKSUM 0xFF05\n\n#ifdef __cplusplus\n}\n#endif\n\n//#define HOOKUP_GSL 1\n\n#ifdef HOOKUP_GSL // if you need to use mixmax through GSL, pass -DHOOKUP_GSL=1 to the compiler\n#ifndef __MIXMAX_C\n\n#include \nunsigned long gsl_get_next(void *vstate);\ndouble gsl_get_next_float(void *vstate);\nvoid seed_for_gsl(void *vstate, unsigned long seed);\n\nstatic const gsl_rng_type mixmax_type =\n{\"MIXMAX\", /* name */\n MERSBASE, /* RAND_MAX */\n 1, /* RAND_MIN */\n sizeof (rng_state_t),\n &seed_for_gsl,\n &gsl_get_next,\n &gsl_get_next_float\n};\n\nunsigned long gsl_get_next(void *vstate) {\n rng_state_t* X= (rng_state_t*)vstate;\n return (unsigned long)get_next(X);\n}\n\ndouble gsl_get_next_float(void *vstate) {\n rng_state_t* X= (rng_state_t*)vstate;\n return ( (double)get_next(X)) * INV_MERSBASE;\n}\n\nvoid seed_for_gsl(void *vstate, unsigned long seed){\n rng_state_t* X= (rng_state_t*)vstate;\n seed_spbox(X,(myuint)seed);\n}\n\nconst gsl_rng_type *gsl_rng_mixmax = &mixmax_type;\n\n\n#endif // HOOKUP_GSL\n#endif // not inside __MIXMAX_C\n#endif // closing MIXMAX_H_\n", "meta": {"hexsha": "8669c377f29ba438f9c85d1a60007d215adf75fe", "size": 9691, "ext": "h", "lang": "C", "max_stars_repo_path": "MontyCarlo/external/mixmax_release_200final/mixmax.h", "max_stars_repo_name": "ruicamposcolabpt/MontyCarlo", "max_stars_repo_head_hexsha": "8f9e7af78f010f44fda81a4ab064e32421a205f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MontyCarlo/external/mixmax_release_200final/mixmax.h", "max_issues_repo_name": "ruicamposcolabpt/MontyCarlo", "max_issues_repo_head_hexsha": "8f9e7af78f010f44fda81a4ab064e32421a205f9", "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": "MontyCarlo/external/mixmax_release_200final/mixmax.h", "max_forks_repo_name": "ruicamposcolabpt/MontyCarlo", "max_forks_repo_head_hexsha": "8f9e7af78f010f44fda81a4ab064e32421a205f9", "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": 32.0894039735, "max_line_length": 164, "alphanum_fraction": 0.6719636776, "num_tokens": 2755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8031737916455819, "lm_q1q2_score": 0.7338410451993936}} {"text": "#include \n#include \n#include \n#define NMAX 100\n\n\ndouble f (double x, void *params);\ndouble f (double x, void *params)\n{\n double n = *(double *) params;\n double f = exp (-x) * pow (x, n);\n\n return f;\n}\nvoid integralGen (int nmin, int nmax, double vals[]);\nvoid integralGen (int nmin, int nmax, double vals[])\n{\n double result, error;\n double a = 0., b = 1.;\n double abserr = 1.e-9, relerr = 1.e-9;\n double n;\n size_t np = 1000;\n gsl_integration_workspace *w = gsl_integration_workspace_alloc (np);\n\n gsl_function F;\n\n F.function = &f;\n\n for (int i = nmin; i <= nmax; i++)\n {\n n = (double) i;\n F.params = &n;\n\n gsl_integration_qag (&F, a, b, abserr, relerr, np, GSL_INTEG_GAUSS15,\n w, &result, &error);\n vals[i] = result;\n\n }\n\n gsl_integration_workspace_free (w);\n}\n", "meta": {"hexsha": "cacee6151909f4903a3d3bb7ad443c1dd85dfd6f", "size": 888, "ext": "c", "lang": "C", "max_stars_repo_path": "gslInt.c", "max_stars_repo_name": "hrwhitelock/hw07", "max_stars_repo_head_hexsha": "fe6323433f9d5736a2b9e0a4e681a5954d8489d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gslInt.c", "max_issues_repo_name": "hrwhitelock/hw07", "max_issues_repo_head_hexsha": "fe6323433f9d5736a2b9e0a4e681a5954d8489d7", "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": "gslInt.c", "max_forks_repo_name": "hrwhitelock/hw07", "max_forks_repo_head_hexsha": "fe6323433f9d5736a2b9e0a4e681a5954d8489d7", "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": 21.1428571429, "max_line_length": 77, "alphanum_fraction": 0.5900900901, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7326337653053475}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"tc_mat.h\"\n\n\nstruct tc_mat *tc_mat_ctr(uint32_t nr_, uint32_t nc_) \n{\n\tstruct tc_mat *A = (struct tc_mat *) malloc(sizeof(struct tc_mat));\n\tmemset(A, 0, sizeof(struct tc_mat));\n\ttc_mat_resize(A, nr_, nc_);\n\treturn A;\n}\n\nvoid tc_mat_dtr(struct tc_mat *A)\n{\n\tif (!A)\n\t\treturn;\n\ttc_mat_clear(A);\n\tfree(A);\n}\n\nvoid tc_mat_clear(struct tc_mat *A)\n{\n\tif (!A)\n\t\treturn;\n\tif (A->a) {\n\t\tfor(uint32_t r=0; r < A->nr; r++)\n\t\t\tif (A->a[r])\n\t\t\t\tfree(A->a[r]);\n\t\tfree(A->a);\n\t}\n\tA->a = NULL;\n\tA->nr = 0;\n\tA->nc = 0;\n}\n\nvoid tc_mat_print(const struct tc_mat *A)\n{\n\tif (!A)\n\t\treturn;\n\tfor(uint32_t i=0; i < A->nr; i++) {\n\t\tfor (uint32_t j=0; j < A->nc; j++)\n\t\t\tprintf(\" %13.10f\", A->a[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n}\n\nvoid tc_mat_resize(struct tc_mat *A, uint32_t nr_, uint32_t nc_)\n{\n\tif ((A->nr == nr_) && (A->nc == nc_))\n\t\treturn;\n\ttc_mat_clear(A);\n\tA->nr = nr_;\n\tA->nc = nc_;\n\tA->a = (double **) malloc(sizeof(double *) * nr_);\n\tfor(uint32_t r=0; r < nr_; r++)\n\t\tA->a[r] = (double *) malloc(sizeof(double) * nc_);\n}\n\nvoid tc_mat_copy(struct tc_mat *B, const struct tc_mat *A)\n{\n\tif (A == B)\n\t\treturn;\n\tif ((B->nr != A->nr) || (B->nc != A->nc))\n\t\ttc_mat_resize(B, A->nr, A->nc);\n\tfor(uint32_t i=0; i < A->nr; i++)\n\t\tfor(uint32_t j=0; j < A->nc; j++)\n\t\t\tB->a[i][j] = A->a[i][j];\n}\n\nvoid tc_mat_identity(struct tc_mat *A)\n{\n\tfor(uint32_t i=0; i < A->nr; i++)\n\t\tfor(uint32_t j=0; j < A->nc; j++)\n\t\t\tA->a[i][j] = (i==j)? 1.0: 0.0;\n}\n\nvoid tc_mat_transpose(struct tc_mat *B, const struct tc_mat *A)\n{\n\tif (A == B) {\n\t\tstruct tc_mat *b = tc_mat_ctr(A->nc, A->nr);\n\t\tfor(uint32_t i=0; i < A->nr; i++) \n\t\t\tfor(uint32_t j=0; j < A->nc; j++) \n\t\t\t\tb->a[j][i] = A->a[i][j];\n\t\ttc_mat_copy(B, b);\n\t\ttc_mat_dtr(b);\n\t\treturn;\n\t}\n\tif ((B->nr != A->nc) || (B->nc != A->nr))\n\t\ttc_mat_resize(B, A->nc, A->nr);\n\tfor(uint32_t i=0; i < A->nr; i++) \n\t\tfor(uint32_t j=0; j < A->nc; j++) \n\t\t\tB->a[j][i] = A->a[i][j];\n}\n\nint tc_mat_add(struct tc_mat *C, const struct tc_mat *A, const struct tc_mat *B)\n{\n\tif (!C || !A || !B || (A->nr != B->nr) || (A->nc != B->nc))\n\t\treturn -1;\n\tif ((C->nr != A->nr) || (C->nc != A->nc))\n\t\ttc_mat_resize(C, A->nr, B->nc);\n\tfor(uint32_t i=0; i < C->nr; i++)\n\t\tfor(uint32_t j=0; j < C->nc; j++)\n\t\t\tC->a[i][j] = A->a[i][j] + B->a[i][j];\n\treturn 0;\n}\n\nint tc_mat_mult(struct tc_mat *C, const struct tc_mat *A, const struct tc_mat *B)\n{\n\tif (!C || !A || !B || (A->nc != B->nr))\n\t\treturn -1;\n\tif ((C == A) || (C == B)) {\n\t\tstruct tc_mat *c = tc_mat_ctr(A->nr, B->nr);\n\t\ttc_mat_mult(c, A, B);\n\t\ttc_mat_copy(C, c);\n\t\ttc_mat_dtr(c);\n\t\treturn 0;\n\t}\n\tif ((C->nc != B->nc) || (C->nr != A->nr))\n\t\ttc_mat_resize(C, A->nr, B->nc);\n\tfor(uint32_t i=0; i < C->nr; i++) {\n\t\tfor(uint32_t j=0; j < C->nc; j++) {\n\t\t\tC->a[i][j] = 0.0;\n\t\t\tfor(uint32_t k=0; k < A->nc; k++)\n\t\t\t\tC->a[i][j] += A->a[i][k] * B->a[k][j];\n\t\t}\n\t}\n\treturn 0;\n}\n\nint tc_mat_mult_scalar(struct tc_mat *C, double a, const struct tc_mat *B)\n{\n\tif (!C || !B)\n\t\treturn -1;\n\tif ((C->nr != B->nr) || (C->nc != B->nc))\n\t\ttc_mat_resize(C, B->nr, B->nc);\n\tfor(uint32_t i=0; i < C->nr; i++)\n\t\tfor(uint32_t j=0; j < C->nc; j++)\n\t\t\tC->a[i][j] = a * B->a[i][j];\n\treturn 0;\n}\n\n/* Householder Reduction to Bidiagonal Form\n * Input m x n matrix A \n * Output: m x n matrix U, products of Householder matrices \n * m x n matrix B, bidiagonal\n * m x n matrix V, products of Householder matrices\n * such that A = U B V^T\n *\n * A Householder matrix P is a reflection transformation of the form\n * I - tau u u^T where tau = 2 / (u^T u). P is orthonormal since \n * P^T P = (I - tau u u^T)^T (I - tau u u^T)\n * = (I - tau u u^T) (I - tau u u^T)\n * = I - 2 tau u u^T + tau^2 u (u^T u) u^T\n * = I - 2 tau u u^T + tau^2 u (2 / tau) u^T\n * = I \n * Products of orthonomal matrices are orthonormal so U and V will be \n * orthonormal.\n *\n * B is constructed via the algorithm\n * 1. B <-- A\n * 2. U <-- I m x n\n * 3. V <-- I n x n\n * 4. For k = 1, ..., n\n * a. construct a Householder matrix P such that \n * i. P is the identity on the first k-1 components, and\n * ii. the k-th column of P B is zero below the diagonal.\n * b. B <--- P B\n * c. U <--- U P\n * d. If k < n - 2, increment k and repeat steps a-c for the\n * operation from the right (the row of B P will be zero\n * to the right of the superdiagonal).\n * \n * Step 4a(i) is equivalent to setting the first k-1 components of u \n * to be zero. Let v be the k-th column of P B. Since\n * P v = (I - tau u u^T) v\n * = (I - tau u u^T) v\n * = v - tau (u^T v) u (Eq. 1)\n * we have that step 4a(ii) is equivalent to setting u to be an appropriate\n * scalar multiple of v for all components above k. The previous steps \n * would have zeroed out the first k-2 components of v. Let \n * b^2 = Sum_{i>=k} (v_i)^2\n * and choose the sign of b to ensure s = v_k - b is nonzero. Set u = v/s \n * on all components larger than k and set u_k = 1. Then\n * tau = 2 / (u^T u) \n * = 2 / (1 + (b^2 - (v_k)^2) / s^2 ) \n * = (2 s) / (s + (b^2 - (v_k)^2) / s)\n * = (2 s) / (s - (b + v_k))\n * = (2 s) / ((v_k - b) - (b + v_k))\n * = (2 s) / (- 2 b)\n * = -s / b\n * This leads to the zeroing out of the lower components of P v since\n * u^T v = v_k + (b^2 - (v_k)^2) / s\n * = v_k - (b + v_k)\n * = b\n * meaning that Eq 1 is simply \n * P v = v - (-s/b) (b) u \n * = v + s u\n * and so P v is zero on all components larger than k.\n * \n * Side note on efficiency 1 (not implemented):\n * Step c produces U and V as products of Housholder matrices. The actual \n * computation of these products is not the most computationally efficient \n * method. A Housholder matrix acts on a vector v as\n * P v = (I - tau u u^T) v \n * = v - tau u (v^T u)^T (Eq. 2)\n * Thus if we've recorded all u's and tau's, we can find U, the product of \n * all the P's, by sequentially applying Eq 2 to the components e1, e2, etc.\n *\n * Side note on efficiency 2 (not implemented):\n * Since each iteration of B leads to known places where its terms have zeros,\n * all matrix multiplications involving B can be restricted to the nonzero\n * terms.\n * \n * Side note on efficiency 3 (not implemented):\n * Since the u's have more zeros in each iteration, the collection of u's\n * can be stored in the original matrix A (and hence B) so long as the \n * Side note on efficiency #2 was implemented.\n */ \nint tc_mat_bidiag_decomp(\n\tconst struct tc_mat *A,\n\tstruct tc_mat *U,\n\tstruct tc_mat *B,\n\tstruct tc_mat *V)\n{\n\tif (!A || !U || !B || !V)\n\t\treturn -1;\n\tif ((U->nr != A->nr) || (U->nc != A->nr))\n\t\ttc_mat_resize(U, A->nr, A->nr);\n\tif ((V->nr != A->nc) || (V->nc != A->nc))\n\t\ttc_mat_resize(V, A->nc, A->nc);\n\tif ((B->nr != A->nr) || (B->nc != A->nc))\n\t\ttc_mat_resize(B, A->nr, A->nc);\n\ttc_mat_copy(B, A);\n\ttc_mat_identity(U);\n\ttc_mat_identity(V);\n\tstruct tc_mat *Ic = tc_mat_ctr(A->nc, A->nc);\n\ttc_mat_identity(Ic);\n\tstruct tc_mat *Ir = tc_mat_ctr(A->nr, A->nr);\n\ttc_mat_identity(Ir);\n\tstruct tc_mat *u = tc_mat_ctr(0, 0);\n\tstruct tc_mat *uT = tc_mat_ctr(0, 0);\n\tstruct tc_mat *u_uT = tc_mat_ctr(0, 0);\n\tstruct tc_mat *P = tc_mat_ctr(0, 0);\n\tfor(uint32_t k=0; (k < A->nc) && (k+1 < A->nr); k++) {\n\t\t/* from the left */\n\t\tdouble b_k = B->a[k][k];\n\t\tdouble b = 0.0;\n\t\tfor(uint32_t i=k; i < A->nr; i++)\n\t\t\tb += B->a[i][k] * B->a[i][k];\n\t\tif (b != 0.0) { /* if b = 0, there's nothing to do */\n\t\t\tb = ((b_k > 0)? -1.0: 1.0) * sqrt(b);\n\t\t\tdouble s = b_k - b;\n\t\t\tdouble tau = - s / b;\n\t\t\ttc_mat_resize(u, A->nr, 1);\n\t\t\tfor(uint32_t i=0; i < A->nr; i++)\n\t\t\t\tu->a[i][0] = (i > k)? B->a[i][k]/s: ((i==k)? 1.0: 0.0);\n\t\t\t/* P = I - tau u u^T */\n\t\t\ttc_mat_transpose(uT, u);\n\t\t\ttc_mat_mult(u_uT, u, uT);\n\t\t\ttc_mat_mult_scalar(P, -tau, u_uT);\n\t\t\ttc_mat_add(P, Ir, P);\n\t\t\t/* U B = (U P) (P B) */\n\t\t\ttc_mat_mult(B, P, B);\n\t\t\ttc_mat_mult(U, U, P);\n\t\t}\n\t\tif (k + 2 < A->nc) {\n\t\t\t/* from the right */\n\t\t\tdouble b_k = B->a[k][k+1];\n\t\t\tdouble b = 0.0;\n\t\t\tfor(uint32_t j=k+1; j < A->nc; j++)\n\t\t\t\tb += B->a[k][j] * B->a[k][j];\n\t\t\tb = ((b_k > 0)? -1.0: 1.0) * sqrt(b);\n\t\t\tif (b != 0.0) { /* if b = 0, there's nothing to do */\n\t\t\t\tdouble s = b_k - b;\n\t\t\t\tdouble tau = - s / b;\n\t\t\t\ttc_mat_resize(u, A->nc, 1);\n\t\t\t\tfor(uint32_t i=0; i < A->nc; i++)\n\t\t\t\t\tu->a[i][0] = (i > k+1)? B->a[k][i]/s: ((i==k+1)? 1.0: 0.0);\n\t\t\t\t/* P = I - tau u u^T */\n\t\t\t\ttc_mat_transpose(uT, u);\n\t\t\t\ttc_mat_mult(u_uT, u, uT);\n\t\t\t\ttc_mat_mult_scalar(P, -tau, u_uT);\n\t\t\t\ttc_mat_add(P, Ic, P);\n\t\t\t\t/* B V = (B P) (P V) */\n\t\t\t\ttc_mat_mult(B, B, P);\n\t\t\t\ttc_mat_mult(V, P, V);\n\t\t\t}\n\t\t}\n\t}\n\ttc_mat_dtr(P);\n\ttc_mat_dtr(u);\n\ttc_mat_dtr(uT);\n\ttc_mat_dtr(u_uT);\n\ttc_mat_dtr(Ic);\n\ttc_mat_dtr(Ir);\n\treturn 0;\n}\n\n/* tc_mat_eigenvalues\n * only implmented for 2x2 matrices\n * Input 2 x 2 matrix A \n * Output: 2 x 1 matrix E of eigenvalues\n * \n * If we set A = [ a b ] \n * [ c d ]\n * Then\n * 0 = det(A - x I)\n * = (a - x)(d - x) - bc\n * = x^2 - (a + d) x + (ad - bc) \n */\nint tc_mat_eigenvalues(struct tc_mat *E, const struct tc_mat *A)\n{\n\tif (!A || !E)\n\t\treturn -1;\n\tif ((A->nr != 2) || (A->nc != 2))\n\t\treturn -1;\n\tif (E->nr != A->nr) \n\t\ttc_mat_resize(E, A->nr, 1);\n\tdouble a = A->a[0][0];\n\tdouble b = A->a[1][0];\n\tdouble c = A->a[0][1];\n\tdouble d = A->a[1][1];\n\tdouble ad2 = (a + d)/2.0;\n\tdouble det = ad2*ad2 - (a*d - b*c);\n\tdouble s = (det <= 0.0)? 0.0: sqrt(det);\n\tE->a[0][0] = ad2 + s;\n\tE->a[1][0] = ad2 - s;\n\treturn 0;\n}\n\n\n/* Wilkinson Shift \n * Input: m x 2 matrix A \n * Output: the Wilkinson shift\n * \n * ei= trailing 2x2 matrix of D^T D */\ndouble tc_mat_wilkinson_shift(const struct tc_mat *A)\n{\n\tif (!A)\n\t\treturn 0.0;\n\tif (A->nc != 2)\n\t\treturn 0.0;\n\tstruct tc_mat *AT = tc_mat_ctr(2, A->nr);\n\ttc_mat_transpose(AT, A);\n\tstruct tc_mat *AT_A = tc_mat_ctr(2, 2);\n\ttc_mat_mult(AT_A, AT, A);\n\tstruct tc_mat *E = tc_mat_ctr(2, 1);\n\ttc_mat_eigenvalues(E, AT_A);\n\tdouble l0 = E->a[0][0];\n\tdouble l1 = E->a[1][0];\n\tdouble t22 = AT_A->a[1][1];\n\ttc_mat_dtr(AT);\n\ttc_mat_dtr(AT_A);\n\ttc_mat_dtr(E);\n\treturn (fabs(l0 - t22) < fabs(l1 - t22))? l0: l1;\n}\n\nint tc_mat_svd(\n\tconst struct tc_mat *A,\n\tstruct tc_mat *U,\n\tstruct tc_mat *D,\n\tstruct tc_mat *V)\n{\n\tif (!U || !D || !V || !A)\n\t\treturn -1;\n\tif ((U->nr != A->nr) || (U->nc != A->nc))\n\t\ttc_mat_resize(U, A->nr, A->nc);\n\tif ((V->nr != A->nc) || (V->nc != A->nc))\n\t\ttc_mat_resize(V, A->nc, A->nc);\n\tif ((D->nr != A->nc) || (D->nc != A->nc))\n\t\ttc_mat_resize(D, A->nc, A->nc);\n\tif (A->nr < A->nc)\n\t\treturn -2;\n\t/* case nc = 1 */\n\tif (A->nc == 1) {\n\t\tV->a[0][0] = 1.0;\n\t\tdouble normsq = 0.0;\n\t\tfor(uint32_t i=0; i < A->nr; i++)\n\t\t\tnormsq += A->a[i][0] * A->a[i][0];\n\t\tD->a[0][0] = sqrt(normsq);\n\t\tif (D->a[0][0] == 0.0)\n\t\t\ttc_mat_copy(U, A);\n\t\telse {\n\t\t\tdouble inv = 1.0 / D->a[0][0];\n\t\t\tfor(uint32_t i=0; i < A->nr; i++)\n\t\t\t\tU->a[i][0] = A->a[i][0] * inv;\n\t\t}\n\t\treturn 0;\n\t}\n\t/* Step1: A = U D V where D is bi-diagonal \n\t * A is nr x nc\n\t * U is nr x nr\n\t * D is nr x nc\n\t * V is nc x nc\n\t * \n\t * If A was not a square matrix, change U and D\n\t * U nr x nc\n\t * D nc x nc\n\t */\n\ttc_mat_bidiag_decomp(A, U, D, V);\n\tif (D->nr != D->nc) {\n\t\tstruct tc_mat *U0 = tc_mat_ctr(A->nr, A->nc);\n\t\tfor(uint32_t i=0; i < A->nr; i++)\n\t\t\tfor(uint32_t j=0; j < A->nc; j++)\n\t\t\t\tU0->a[i][j] = U->a[i][j];\n\t\ttc_mat_resize(U, A->nr, A->nc);\n\t\ttc_mat_copy(U, U0);\n\t\ttc_mat_dtr(U0);\n\n\t\tstruct tc_mat *D0 = tc_mat_ctr(A->nc, A->nc);\n\t\tfor(uint32_t i=0; i < A->nc; i++)\n\t\t\tfor(uint32_t j=0; j < A->nc; j++)\n\t\t\t\tD0->a[i][j] = D->a[i][j];\n\t\ttc_mat_resize(D, A->nc, A->nc);\n\t\ttc_mat_copy(D, D0);\n\t\ttc_mat_dtr(D0);\n\t}\n\t/* iterate until either max_iterations has been hit\n\t * or the largest superdiagonal entry is below the\n\t * threshold. Set threshold = 1-e8 * largest element.\n\t * Any term less than 0.1 threshold will be considered\n\t * to be zero.\n\t */\n\tconst uint32_t max_iterations = 100 * D->nc;\n\tdouble threshold = D->a[0][0];\n\tfor(uint32_t i=0; i < D->nc; i++)\n\t\tif (fabs(D->a[i][i]) > threshold)\n\t\t\tthreshold = fabs(D->a[i][i]);\n\tfor(uint32_t i=0; i+1 < D->nc; i++)\n\t\tif (fabs(D->a[i][i+1]) > threshold)\n\t\t\tthreshold = fabs(D->a[i][i+1]);\n\tthreshold *= 1e-12;\n\tconst double zero_threshold = 0.1 * threshold;\n\t/* Always reindex the components so that \n * D so that has the form \n\t * [D1, 0] where D1 is diagonal and \n\t * [ 0,D2] D2 is bidiagonal \n\t * Let i0 be the starting index of D2 \n\t */\n\tuint32_t i0 = 0;\n\tfor(uint32_t I=0; I < max_iterations; I++)\n\t{\n\t\t/* For any zeros on the diagonal, apply a series of \n\t\t * Givens rotations to also zero out its off-diagonal\n\t\t * term. Then move this component into D1.\n\t\t */\n\t\tfor(uint32_t i1=i0; i1 < D->nr; i1++) {\n\t\t\tif (fabs(D->a[i1][i1]) > zero_threshold)\n\t\t\t\tcontinue;\n\t\t\tif ((i1+1 == D->nr) && fabs(D->a[i1-1][i1]) > zero_threshold) \n\t\t\t\tcontinue;\n\t\t\tif ((i1+1 < D->nr) && (fabs(D->a[i1][i1+1]) > zero_threshold)) {\n\t\t\t\tfor(uint32_t i=i1; i+1 < D->nr; i++) {\n\t\t\t\t\t/* U D = (U G) (G^T D) */\n\t\t\t\t\tdouble alpha = D->a[i1][i+1];\n\t\t\t\t\tif (fabs(alpha) < zero_threshold)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdouble beta = D->a[i+1][i+1];\n\t\t\t\t\tdouble gamma = sqrt(alpha*alpha + beta*beta);\n\t\t\t\t\tdouble c = beta / gamma;\n\t\t\t\t\tdouble s = alpha / gamma;\n\t\t\t\t\tfor(uint32_t j=0; j < D->nr; j++) {\n\t\t\t\t\t\tdouble a = D->a[i1][j];\n\t\t\t\t\t\tdouble b = D->a[i+1][j];\n\t\t\t\t\t\tD->a[i1][j] = a*c - b*s;\n\t\t\t\t\t\tD->a[i+1][j] = a*s + b*c;\n\t\t\t\t\t}\n\t\t\t\t\tfor(uint32_t j=0; j < U->nr; j++) {\n\t\t\t\t\t\tdouble a = U->a[j][i1];\n\t\t\t\t\t\tdouble b = U->a[j][i+1];\n\t\t\t\t\t\tU->a[j][i1] = a*c - b*s;\n\t\t\t\t\t\tU->a[j][i+1] = a*s + b*c;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ti1++;\n\t\t\t}\n\t\t\t/* move (i0,i1-1) down, i1 -> i0 */\n\t\t\tfor(uint32_t j=0; j < D->nr; j++) {\n\t\t\t\tdouble tmp = V->a[i1][j];\n\t\t\t\tfor(uint32_t k=i1; k > i0; k--)\n\t\t\t\t\tV->a[k][j] = V->a[k-1][j];\n\t\t\t\tV->a[i0][j] = tmp;\n\t\t\t}\n\t\t\tfor(uint32_t j=0; j < D->nr; j++) {\n\t\t\t\tdouble tmp = U->a[j][i1];\n\t\t\t\tfor(uint32_t k=i1; k > i0; k--)\n\t\t\t\t\tU->a[j][k] = U->a[j][k-1];\n\t\t\t\tU->a[j][i0] = tmp;\n\t\t\t}\n\t\t\tdouble tmp = D->a[i1][i1];\n\t\t\tdouble tmp1 = D->a[i1][i1+1];\n\t\t\tfor(uint32_t k=i1; k > i0; k--) {\n\t\t\t\tD->a[k][k] = D->a[k-1][k-1];\n\t\t\t\tif (k+1 < D->nc)\n\t\t\t\t\tD->a[k][k+1] = D->a[k-1][k];\n\t\t\t}\n\t\t\tD->a[i0][i0] = tmp;\n\t\t\tD->a[i0][i0+1] = tmp1;\n\t\t\ti0++;\n\t\t}\n\t\t/* For any zeros on the superdiagonal, move the\n\t\t * component to D1.\n\t\t */\n\t\tfor(uint32_t i=i0; i+1 < D->nr; i++) {\n\t\t\tif (fabs(D->a[i][i+1]) >= zero_threshold)\n\t\t\t\tcontinue;\n\t\t\tif (i == i0) {\n\t\t\t\ti0++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (i+2 != D->nr)\n\t\t\t\tcontinue;\n\t\t\t/* move (i0,i) down, i+1 -> i0 */\n\t\t\tfor(uint32_t j=0; j < D->nr; j++) {\n\t\t\t\tdouble tmp = V->a[i+1][j];\n\t\t\t\tfor(uint32_t k=i+1; k > i0; k--)\n\t\t\t\t\tV->a[k][j] = V->a[k-1][j];\n\t\t\t\tV->a[i0][j] = tmp;\n\t\t\t}\n\t\t\tfor(uint32_t j=0; j < D->nr; j++) {\n\t\t\t\tdouble tmp = U->a[j][i+1];\n\t\t\t\tfor(uint32_t k=i+1; k > i0; k--)\n\t\t\t\t\tU->a[j][k] = U->a[j][k-1];\n\t\t\t\tU->a[j][i0] = tmp;\n\t\t\t}\n\t\t\tdouble tmp = D->a[i+1][i+1];\n\t\t\tdouble tmp1 = D->a[i][i+1];\n\t\t\tfor(uint32_t k=i+1; k > i0; k--) {\n\t\t\t\tD->a[k][k] = D->a[k-1][k-1];\n\t\t\t\tD->a[k-1][k] = (k-1==i0)? tmp1: D->a[k-2][k-1];\n\t\t\t}\n\t\t\tD->a[i0][i0] = tmp;\n\t\t\ti0++;\n\t\t\tif ((i+2 == D->nr) && (i0 != i))\n\t\t\t\ti--; /* retry last term */\n\t\t}\n\t\tif (i0 >= D->nr - 1)\n\t\t\tbreak;\n\t\t/* Find largest element on super diagonal.*/\n\t\t/* Break if less than threshold. */\n\t\tdouble largest_off_diag = 0.0;\n\t\tuint32_t n_zeros_on_off_diagonal = 0;\n\t\tfor(uint32_t i=i0; i+1 < D->nr; i++) {\n\t\t\tif (fabs(D->a[i][i+1]) > largest_off_diag)\n\t\t\t\tlargest_off_diag = fabs(D->a[i][i+1]);\n\t\t\tif (fabs(D->a[i][i+1]) < zero_threshold)\n\t\t\t\tn_zeros_on_off_diagonal++;\n\t\t}\n\t\tif (largest_off_diag < threshold)\n\t\t\tbreak;\n\t\t/* Find the next zero on the uper diagonal*/\n\t\t/* Treat [i0,i1] as a block. */\n\t\tuint32_t i1 = i0;\n\t\tfor( ; i1+1 < D->nr; i1++)\n\t\t\tif (fabs(D->a[i1][i1+1]) < zero_threshold)\n\t\t\t\tbreak;\n\t\t/* Find Wilkerson shift. */\n\t\tstruct tc_mat *t = tc_mat_ctr(3, 2);\n\t\tfor(uint32_t i=0; i < 3; i++)\n\t\t\tfor(uint32_t j=0; j < 2; j++)\n\t\t\t\tt->a[i][j] = (i1+i>2)? D->a[i1+i-2][i1+j-1]: 0.0;\n\t\tdouble mu = tc_mat_wilkinson_shift(t);\n\t\ttc_mat_dtr(t);\n\t\tdouble alpha = D->a[i0][i0] * D->a[i0][i0] - mu;\n\t\tdouble beta = D->a[i0][i0] * D->a[i0][i0+1];\n\t\t/* Apply Givens rotations G from i0 to the bottom,\n\t\t * chasing the nonzero element until off the matrix \n\t\t */\n\t\tfor(uint32_t i=i0; i < i1; i++) {\n\t\t\t/* D V = (D G) (G^T V) */\n\t\t\tdouble gamma = sqrt(alpha*alpha + beta*beta);\n\t\t\tdouble c = alpha / gamma;\n\t\t\tdouble s = -beta / gamma;\n\t\t\tfor(uint32_t j=0; j < D->nr; j++) {\n\t\t\t\tdouble a = D->a[j][i+0];\n\t\t\t\tdouble b = D->a[j][i+1];\n\t\t\t\tD->a[j][i+0] = a*c - b*s;\n\t\t\t\tD->a[j][i+1] = a*s + b*c;\n\t\t\t}\n\t\t\tfor(uint32_t j=0; j < D->nc; j++) {\n\t\t\t\tdouble a = V->a[i+0][j];\n\t\t\t\tdouble b = V->a[i+1][j];\n\t\t\t\tV->a[i+0][j] = a*c - b*s;\n\t\t\t\tV->a[i+1][j] = a*s + b*c;\n\t\t\t}\n\t\t\t/* U D = (U G) (G^T D) */ \n\t\t\talpha = D->a[i+0][i];\n\t\t\tbeta = D->a[i+1][i];\n\t\t\tgamma = sqrt(alpha*alpha + beta*beta);\n\t\t\tif (fabs(gamma) > 0.0) {\n\t\t\t\tc = alpha / gamma;\n\t\t\t\ts = -beta / gamma;\n\t\t\t\tfor(uint32_t j=0; j < D->nc; j++) {\n\t\t\t\t\tdouble a = D->a[i+0][j];\n\t\t\t\t\tdouble b = D->a[i+1][j];\n\t\t\t\t\tD->a[i+0][j] = a*c - b*s;\n\t\t\t\t\tD->a[i+1][j] = a*s + b*c;\n\t\t\t\t}\n\t\t\t\tfor(uint32_t j=0; j < U->nr; j++) {\n\t\t\t\t\tdouble a = U->a[j][i+0];\n\t\t\t\t\tdouble b = U->a[j][i+1];\n\t\t\t\t\tU->a[j][i+0] = a*c - b*s;\n\t\t\t\t\tU->a[j][i+1] = a*s + b*c;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (i + 2 < D->nr) {\n\t\t\t\talpha = D->a[i][i+1];\n\t\t\t\tbeta = D->a[i][i+2];\n\t\t\t}\n\t\t}\n\t}\n\t/* now swap components to order the diagonal terms\n\t * from largest to smallest \n\t */\n\tfor(uint32_t i=0; i+1 < D->nr; i++) {\n\t\tdouble largest = fabs(D->a[i][i]);\n\t\tuint32_t largest_i = i;\n\t\tfor(uint32_t j=i+1; j < D->nr; j++) {\n\t\t\tif (fabs(D->a[j][j]) > largest) {\n\t\t\t\tlargest_i = j;\n\t\t\t\tlargest = fabs(D->a[j][j]);\n\t\t\t}\n\t\t}\n\t\tif (largest_i != i) {\n\t\t\tfor(uint32_t j=0; j < D->nr; j++) {\n\t\t\t\tdouble tmp = V->a[i][j];\n\t\t\t\tV->a[i][j] = V->a[largest_i][j];\n\t\t\t\tV->a[largest_i][j] = tmp;\n\t\t\t\ttmp = U->a[j][i];\n\t\t\t\tU->a[j][i] = U->a[j][largest_i];\n\t\t\t\tU->a[j][largest_i] = tmp;\n\t\t\t}\n\t\t\tdouble tmp = D->a[i][i];\n\t\t\tD->a[i][i] = D->a[largest_i][largest_i];\n\t\t\tD->a[largest_i][largest_i] = tmp;\n\t\t}\n\t\tif (D->a[i][i] < 0) { \n\t\t\tD->a[i][i] = -D->a[i][i];\n\t\t\tfor(uint32_t j=0; j < D->nr; j++)\n\t\t\t\tV->a[i][j] = -V->a[i][j];\n\t\t}\n\t}\n\t/* just to be sure, zero out all off-diagonal terms of D */\n\tfor(uint32_t i=0; i < D->nr; i++) \n\t\tfor(uint32_t j=0; j < D->nc; j++) \n\t\t\tif (i != j)\n\t\t\t\tD->a[i][j] = 0.0;\n\t/* transpose V */\n\ttc_mat_transpose(V, V);\n\treturn 0;\n}\n\n", "meta": {"hexsha": "912336c4fa250c9bd27f002d354b6a2fcadf8be3", "size": 18780, "ext": "c", "lang": "C", "max_stars_repo_path": "lib-other/cpplib/tc_mat.c", "max_stars_repo_name": "endolith/Truthcoin", "max_stars_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 161.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T20:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:44:13.000Z", "max_issues_repo_path": "lib-other/cpplib/tc_mat.c", "max_issues_repo_name": "endolith/Truthcoin", "max_issues_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-04-21T10:17:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-09T14:38:06.000Z", "max_forks_repo_path": "lib-other/cpplib/tc_mat.c", "max_forks_repo_name": "endolith/Truthcoin", "max_forks_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T16:44:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T14:09:49.000Z", "avg_line_length": 28.4545454545, "max_line_length": 81, "alphanum_fraction": 0.5112353568, "num_tokens": 7516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8056321913146128, "lm_q1q2_score": 0.7320118313607901}} {"text": "/*\n** compute histogram density function\n**\n** G.Lohmann, Nov 2012\n*/\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define SQR(x) ((x)*(x))\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\n\n/* kernel density estimation */\ndouble GaussKernel(double x)\n{\n return exp(-0.5*x*x)/sqrt(2.0*M_PI);\n}\n\ndouble VKernelDensity(double x,double h,double nh,gsl_histogram *histogram)\n{\n size_t i;\n double sum,upper,lower;\n\n sum = 0;\n for (i=0; i hmax-tiny) u = hmax-tiny;\n gsl_histogram_increment (hist,u);\n }\n }\n}\n", "meta": {"hexsha": "d48db6ddd54bb09d8f03f8fbe4cf2da03d337199", "size": 2296, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ted/vted/Histogram.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/ted/vted/Histogram.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/ted/vted/Histogram.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 24.4255319149, "max_line_length": 75, "alphanum_fraction": 0.6493902439, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7300500555138457}} {"text": "#include \n#include \n#include \n\nvoid integral_gen (int nmin, int nmax, double vals[]);\ndouble f (double x, void *params);\n\ndouble f (double x, void *params)\n{\n double n = (double) *(int *) params;\n double f = exp (-x) * pow (x, n);\n\n return f;\n}\n\nvoid integral_gen (int nmin, int nmax, double vals[])\n{\n\n double a = 0., b = 1.; // limits of integration\n double abserr = 0., relerr = 1.e-8; // requested errors\n double result; // the integral value\n double error; // the error estimate\n int n;\n\n size_t np = 1000; // work area size\n gsl_integration_workspace *w = gsl_integration_workspace_alloc (np);\n\n gsl_function F;\n\n F.function = &f;\n F.params = &n;\n\n for (n = nmin; n <= nmax; n++)\n {\n gsl_integration_qag (&F, a, b, abserr, relerr, np, GSL_INTEG_GAUSS15,\n w, &result, &error);\n vals[n] = result;\n }\n\n gsl_integration_workspace_free (w);\n}\n", "meta": {"hexsha": "6944771946bc5fe578df5825ef36bb4f5d7e9559", "size": 1002, "ext": "c", "lang": "C", "max_stars_repo_path": "integral_gen.c", "max_stars_repo_name": "mtariq1994/hw07", "max_stars_repo_head_hexsha": "66be149e44bf9f0fcf17ffd5c1a99eafaf1a8b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "integral_gen.c", "max_issues_repo_name": "mtariq1994/hw07", "max_issues_repo_head_hexsha": "66be149e44bf9f0fcf17ffd5c1a99eafaf1a8b96", "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": "integral_gen.c", "max_forks_repo_name": "mtariq1994/hw07", "max_forks_repo_head_hexsha": "66be149e44bf9f0fcf17ffd5c1a99eafaf1a8b96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8571428571, "max_line_length": 77, "alphanum_fraction": 0.5828343313, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7282944872952567}} {"text": "/* sample.c\n * written by Sanghyuk Moon\n * Last update: 2020 July 24\n *\n * DESCRIPTION:\n * Generate 3D particle distribution that is consistent with prescribed density.\n * Density is assumed to be axisymmetric and normalized such that rho(R,z) ~ [0,1].\n * R, z coordinates are generated by rejection sampling using the Halton's pseudo-random\n * sequence, while phi coordinates are uniformly spaced between [0,2pi].\n *\n * RETURN:\n * Particle positions in Cartesian coordinates (x,y,z).\n *\n * REQUIREMENTS:\n * GNU Scientific Library ($sudo apt install libgsl-dev)\n *\n * USAGE:\n * $gcc sample.c -lgsl -lm\n * $a.out > out.txt\n */\n\n#include \n#include \n#include \n#include \n\nconst unsigned int dim=2;\n\ndouble density(double R, double z) {\n double rho, scaleh, Rmin;\n Rmin = 0.1;\n scaleh = 0.1; // Gaussian scale height of the disk\n rho = Rmin/R*exp(-z*z/scaleh/scaleh/2);\n return rho;\n}\n\nvoid sample_particles(long int ngas, double x1min, double x1max, double x3min, double x3max) {\n long id=0;\n double pos[dim], u4;\n double x1,x2,x3; // particle position in cylindrical coordinates\n double den; // desired gas density\n gsl_qrng *qrng;\n gsl_rng *rng;\n\n // GSL random number generator setup\n qrng = gsl_qrng_alloc(gsl_qrng_halton, dim);\n rng = gsl_rng_alloc(gsl_rng_ranlxd2);\n\n while (id < ngas) {\n gsl_qrng_get(qrng, pos);\n x1 = x1min + (x1max-x1min)*pos[0];\n x3 = x3min + (x3max-x3min)*pos[1];\n u4 = x1max*gsl_rng_uniform(rng); // uniform random number in [0, x1max]\n den = density(x1, x3);\n\n // accept if u4 < R*density.\n // additional weighting by R compensates the R*d\\phi volume factor.\n if (u4 <= x1*den) {\n x2 = 2.0*M_PI*(double)id/(double)ngas;\n printf(\"%le %le %le\\n\", x1*cos(x2), x1*sin(x2), x3);\n id++;\n }\n }\n gsl_qrng_free(qrng);\n gsl_rng_free(rng);\n}\n\nint main() {\n long int ngas; // number of particles\n double x1min, x1max, x3min, x3max;\n\n // set domain info\n ngas = pow(10,6);\n x1min = 0.1;\n x1max = 1.0;\n x3min = -0.5;\n x3max = 0.5;\n\n // run rejection samplig\n sample_particles(ngas, x1min, x1max, x3min, x3max);\n return 0;\n}\n", "meta": {"hexsha": "69a6e14caee25348e4bcdb19e43a809b88b97d03", "size": 2171, "ext": "c", "lang": "C", "max_stars_repo_path": "sample.c", "max_stars_repo_name": "aviator24/icgen", "max_stars_repo_head_hexsha": "b8eda013a9d57a7e15405be253b68cd743636904", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sample.c", "max_issues_repo_name": "aviator24/icgen", "max_issues_repo_head_hexsha": "b8eda013a9d57a7e15405be253b68cd743636904", "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": "sample.c", "max_forks_repo_name": "aviator24/icgen", "max_forks_repo_head_hexsha": "b8eda013a9d57a7e15405be253b68cd743636904", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.156626506, "max_line_length": 94, "alphanum_fraction": 0.6582220175, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7281601616014975}} {"text": "#include \n#include \n#include \n#define COMPEARTH_PRIVATE_GEM3 1\n#include \"compearth.h\"\n#ifdef DEBUG\n#ifdef COMPEARTH_USE_MKL\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#pragma clang diagnostic ignored \"-Wstrict-prototypes\"\n#endif\n#include \n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include \n#endif\n#endif\n\n/*!\n * @brief Compute a rotation matrix given an axis and angle\n *\n * @param[in] n Number of matrices to generate.\n * @param[in] v Rotation axis. This is an array of dimension [3 x n]\n * with leading dimension 3.\n * @param[in] xi Rotation angles (degrees). This is an array of\n * dimension [n].\n *\n * @param[in] U Rotation matrices. This is an array of dimension\n * [3 x 3 x n] where each leading [3 x 3] matrix is\n * in column major format.\n *\n * @result 0 indicates success.\n *\n * @date 2016 - Ben Baker translated Carl Tape's rotmat_gen.m to C\n *\n * @copyright MIT\n *\n */\nint compearth_eulerUtil_rotmatGen(const int n,\n const double *__restrict__ v,\n const double *__restrict__ xi,\n double *__restrict__ U)\n{\n double R1[9], R2[9], R3[9], R4[9], R5[9], R54[9], R543[9], R5432[9];\n double ele, nvph_deg, nvth_deg, rho, vph, vth, vph_deg, vth_deg;\n int i, ierr;\n const double pi180i = 180.0/M_PI;\n ierr = 0;\n for (i=0; i 1.e-14)\n {\n printf(\"Computation failed: %f %f\\n\", U9[k], U[9*i+k]);\n ierr = ierr + 1;\n }\n }\n#endif\n }\n return ierr;\n}\n\n", "meta": {"hexsha": "99ec0fea8173d14a381d05bc5691706756d9b5f7", "size": 3369, "ext": "c", "lang": "C", "max_stars_repo_path": "c_src/eulerUtil_rotmatGen.c", "max_stars_repo_name": "OUCyf/mtbeach", "max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z", "max_issues_repo_path": "c_src/eulerUtil_rotmatGen.c", "max_issues_repo_name": "carltape/mtbeach", "max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z", "max_forks_repo_path": "c_src/eulerUtil_rotmatGen.c", "max_forks_repo_name": "carltape/mtbeach", "max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z", "avg_line_length": 34.3775510204, "max_line_length": 73, "alphanum_fraction": 0.5607005046, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7280693992632636}} {"text": "/* \n The following program solves the second-order nonlinear \n Van der Pol oscillator equation (see Landau/Paez 14.12, part 1),\n x\"(t) + \\mu x'(t) (x(t)^2 - 1) + x(t) = 0\n This can be converted into a first order system suitable for \n use with the library by introducing a separate variable for \n the velocity, v = x'(t). We assign x --> y[0] and v --> y[1].\n So the equations are:\n x' = v ==> dy[0]/dt = f[0] = y[1]\n v' = -x + \\mu v (1-x^2) ==> dy[1]/dt = f[1] = -y[0] + mu*y[1]*(1-y[0]*y[0])\n x\"(t) = - \\mu x'(t) (x(t)^2 - 1) - x(t)\n\n x''(t) + x'(t) + x(t) = 0\n x''(t) = -x'(t) - x(t)\n\n x' = v ===> dy[0]/dt = f[0] = y[1]\n v' = -v - x\n*/\n\n#include \n#include \n#include \n#include \n\n/* function prototypes */\nint rhs (double t, const double y[], double f[], void *params_ptr);\n//int jacobian (double t, const double y[], double *dfdy, double dfdt[], void *params_ptr);\n\n/*************************** main program ****************************/\n\nint *jac;\n\nint\nmain (void)\n{\n int dimension = 2;\t\t/* number of differential equations */\n \n double eps_abs = 1.e-8;\t/* absolute error requested */\n double eps_rel = 1.e-10;\t/* relative error requested */\n\n /* define the type of routine for making steps: */\n const gsl_odeiv_step_type *type_ptr = gsl_odeiv_step_rkf45;\n /* some other possibilities (see GSL manual): \n = gsl_odeiv_step_rk4;\n = gsl_odeiv_step_rkck;\n = gsl_odeiv_step_rk8pd;\n = gsl_odeiv_step_rk4imp;\n = gsl_odeiv_step_bsimp; \n = gsl_odeiv_step_gear1;\n = gsl_odeiv_step_gear2;\n */\n\n /* \n allocate/initialize the stepper, the control function, and the\n evolution function.\n */\n\t// 룬게쿠타 방식의 2계 미분 방정식으로 stepping을 진행합니다.\n gsl_odeiv_step *step_ptr = gsl_odeiv_step_alloc (type_ptr, dimension);\n\t// 허용 오차\n gsl_odeiv_control *control_ptr = gsl_odeiv_control_y_new (eps_abs, eps_rel);\n\t// 계산하는 차원\n gsl_odeiv_evolve *evolve_ptr = gsl_odeiv_evolve_alloc (dimension);\n\n gsl_odeiv_system my_system;\t/* structure with the rhs function, etc. */\n\n double mu = 10;\t\t/* parameter for the diffeq */\n double y[2];\t\t\t/* current solution vector */\n\n double t, t_next;\t\t/* current and next independent variable */\n double tmin, tmax, delta_t;\t/* range of t and step size for output */\n\n double h = 1e-6;\t\t/* starting step size for ode solver */\n\n /* load values into the my_system structure */\n my_system.function = rhs;\t/* the right-hand-side functions dy[i]/dt */\n //my_system.jacobian = jacobian;\t/* the Jacobian df[i]/dy[j] */\n my_system.jacobian = NULL;\n my_system.dimension = dimension;\t/* number of diffeq's */\n //my_system.params = μ\t/* parameters to pass to rhs and jacobian */\n my_system.params = NULL;\n\n tmin = 0.;\t\t\t/* starting t value */\n tmax = 10.;\t\t\t/* final t value */\n delta_t = 1.;\n\n\t// 주의점이라면 2계 미분 방정식은 최소 2개의 초기값이 필요하다는 부분을 주의!\n y[0] = 1.;\t\t\t/* initial x value */\n y[1] = 0.;\t\t\t/* initial v value */\n\n t = tmin; /* initialize t */\n printf (\"%.5e %.5e %.5e\\n\", t, y[0], y[1]);\t/* initial values */\n\n /* step to tmax from tmin */\n for (t_next = tmin + delta_t; t_next <= tmax; t_next += delta_t)\n {\n while (t < t_next)\t/* evolve from t to t_next */\n {\n gsl_odeiv_evolve_apply (evolve_ptr, control_ptr, step_ptr,\n &my_system, &t, t_next, &h, y);\n }\n\t\t// y[0], y[1] 결과 확인이 필요함\n printf (\"%.5e %.5e %.5e\\n\", t, y[0], y[1]); /* print at t=t_next */\n }\n\n /* all done; free up the gsl_odeiv stuff */\n gsl_odeiv_evolve_free (evolve_ptr);\n gsl_odeiv_control_free (control_ptr);\n gsl_odeiv_step_free (step_ptr);\n\n return 0;\n}\n\n/*************************** rhs ****************************/\n/* \n x''(t) + x'(t) + x(t) = 0\n x''(t) = -x'(t) - x(t)\n\n x' = v ===> dy[0]/dt = f[0] = y[1]\n v' = -v - x ===> dy[1]/dt = f[1] = -y[1] - y[0]\n*/\n\n// https://www.wolframalpha.com/input/?i=y%27%27+%2B+y%27+%2B+y+%3D+0%2C+y%280%29+%3D+1%2C+y%27%280%29+%3D+0, y(0) = 1\n// https://www.wolframalpha.com/input/?i=%28sqrt%283%29+*+sin%28sqrt%283%29+%2F+2%29+%2B+3+*+cos%28sqrt%283%29+%2F+2%29%29+%2F+%283+*+sqrt%28e%29%29, y(1)\n// (sqrt(3) * sin(sqrt(3) / 2) + 3 * cos(sqrt(3) / 2)) / (3 * sqrt(e)), y(1) = 0.6597001...\nint\nrhs (double t, const double v[], double f[], void *params_ptr)\n//rhs (double t, const double y[], double f[], void *params_ptr)\n{\n\t/*\n f[0] = y[1];\n f[1] = -y[0] + mu * y[1] * (1. - y[0] * y[0]);\n\t*/\n\t// * 코드 작성 팁: 미분항은 f에 배치합니다.\n\t// 1계와 마찬가지로 반드시 표준형이어야 합니다!\n\t// 첫번째 1차 미분이 무엇(치환)입니다 ~\n\tf[0] = v[1];\n\t// 두번째 2차 미분을 치환을 기반으로 어떻게 표현해야 하는지를 기록합니다.\n\tf[1] = -v[1] - v[0];\n\t/* Tip: 배열의 인덱스는 결국 미분의 횟수라고 생각해도 좋습니다 */\n\t// 현재 초기값이 있으니까 두 개의 근이 나오지 않고 한 개의 근이 나옴!\n\n return GSL_SUCCESS;\t\t/* GSL_SUCCESS defined in gsl/errno.h as 0 */\n}\n\n/*************************** Jacobian ****************************/\n/*\n Define the Jacobian matrix using GSL matrix routines.\n (see the GSL manual under \"Ordinary Differential Equations\") \n \n * params is a void pointer that is used in many GSL routines\n to pass parameters to a function\n*/\n\n#if 0\nint\njacobian (double t, const double y[], double *dfdy,\n double dfdt[], void *params_ptr)\n{\n /* get parameter(s) from params_ptr; here, just a double */\n double mu = *(double *) params_ptr;\n\n gsl_matrix_view dfdy_mat = gsl_matrix_view_array (dfdy, 2, 2);\n\n gsl_matrix *m_ptr = &dfdy_mat.matrix;\t/* m_ptr points to the matrix */\n\n /* fill the Jacobian matrix as shown */\n gsl_matrix_set (m_ptr, 0, 0, 0.0);\t/* df[0]/dy[0] = 0 */\n gsl_matrix_set (m_ptr, 0, 1, 1.0);\t/* df[0]/dy[1] = 1 */\n gsl_matrix_set (m_ptr, 1, 0, -2.0 * mu * y[0] * y[1] - 1.0); /* df[1]/dy[0] */\n gsl_matrix_set (m_ptr, 1, 1, -mu * (y[0] * y[0] - 1.0)); /* df[1]/dy[1] */\n\n /* set explicit t dependence of f[i] */\n dfdt[0] = 0.0;\n dfdt[1] = 0.0;\n\n return GSL_SUCCESS;\t\t/* GSL_SUCCESS defined in gsl/errno.h as 0 */\n}\n#endif\n", "meta": {"hexsha": "a5b01333cdbddf1636a688e19c65379f33df0429", "size": 6094, "ext": "c", "lang": "C", "max_stars_repo_path": "ch5/src/main/second_ode.c", "max_stars_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_stars_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-22T00:39:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-22T00:39:04.000Z", "max_issues_repo_path": "ch5/src/main/second_ode.c", "max_issues_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_issues_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "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": "ch5/src/main/second_ode.c", "max_forks_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_forks_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-19T01:22:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T01:22:06.000Z", "avg_line_length": 34.0446927374, "max_line_length": 154, "alphanum_fraction": 0.5656383328, "num_tokens": 2259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7275630878467095}} {"text": "/* linalg/qrc.c\n *\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * Copyright (C) 2017 Christian Krueger\n * Copyright (C) 2020 Patrick Alken\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman, modified by C. Krueger */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* Factorise a general complex-valued M x N matrix A into\n *\n * A = Q R\n *\n * where Q is unitary (M x M) and R is upper triangular (M x N).\n *\n * Q is stored as a packed set of Householder transformations in the\n * strict lower triangular part of the input matrix.\n *\n * R is stored in the diagonal and upper triangle of the input matrix.\n *\n * The full matrix for Q can be obtained as the product\n *\n * Q = Q_k .. Q_2 Q_1\n *\n * where k = MIN(M,N) and\n *\n * Q_i = (I - tau_i * v_i * v_i')\n *\n * and where v_i is a Householder vector\n *\n * v_i = [1, m(i+1,i), m(i+2,i), ... , m(M,i)]\n *\n * This storage scheme is the same as in LAPACK. */\n\nint\ngsl_linalg_complex_QR_decomp (gsl_matrix_complex * A, gsl_vector_complex * tau)\n{\n const size_t M = A->size1;\n const size_t N = A->size2;\n\n if (tau->size != N)\n {\n GSL_ERROR (\"size of tau must be N\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n for (i = 0; i < GSL_MIN (M, N); i++)\n {\n /* Compute the Householder transformation to reduce the j-th\n column of the matrix to a multiple of the j-th unit vector */\n\n gsl_vector_complex_view c = gsl_matrix_complex_subcolumn (A, i, i, M - i);\n gsl_complex tau_i = gsl_linalg_complex_householder_transform (&(c.vector));\n\n gsl_vector_complex_set (tau, i, tau_i);\n\n /* apply the transformation to the remaining columns and update the norms */\n\n if (i + 1 < N)\n {\n gsl_matrix_complex_view m = gsl_matrix_complex_submatrix (A, i, i + 1, M - i, N - i - 1);\n gsl_complex tau_i_conj = gsl_complex_conjugate(tau_i);\n gsl_vector_complex_view work = gsl_vector_complex_subvector(tau, i + 1, N - i - 1);\n\n gsl_linalg_complex_householder_left(tau_i_conj, &(c.vector), &(m.matrix), &(work.vector));\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/* Solves the system A x = b using the QR factorisation,\n\n * R x = Q^H b\n *\n * to obtain x.\n */\n\nint\ngsl_linalg_complex_QR_solve (const gsl_matrix_complex * QR, const gsl_vector_complex * tau,\n const gsl_vector_complex * b, gsl_vector_complex * x)\n{\n if (QR->size1 != QR->size2)\n {\n GSL_ERROR (\"QR matrix must be square\", GSL_ENOTSQR);\n }\n else if (QR->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (QR->size2 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* copy x <- b */\n gsl_vector_complex_memcpy (x, b);\n\n /* solve for x */\n gsl_linalg_complex_QR_svx (QR, tau, x);\n\n return GSL_SUCCESS;\n }\n}\n\n/* Solves the system A x = b in place using the QR factorisation,\n\n * R x = Q^H b\n *\n * to obtain x.\n */\n\nint\ngsl_linalg_complex_QR_svx (const gsl_matrix_complex * QR, const gsl_vector_complex * tau, gsl_vector_complex * x)\n{\n\n if (QR->size1 != QR->size2)\n {\n GSL_ERROR (\"QR matrix must be square\", GSL_ENOTSQR);\n }\n else if (QR->size1 != x->size)\n {\n GSL_ERROR (\"matrix size must match x/rhs size\", GSL_EBADLEN);\n }\n else\n {\n /* compute rhs = Q^H b */\n gsl_linalg_complex_QR_QHvec (QR, tau, x);\n\n /* solve R x = rhs, storing x in-place */\n gsl_blas_ztrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\n/* Find the least squares solution to the overdetermined system\n *\n * A x = b\n *\n * for M >= N using the QR factorization A = Q R.\n */\n\nint\ngsl_linalg_complex_QR_lssolve (const gsl_matrix_complex * QR, const gsl_vector_complex * tau,\n const gsl_vector_complex * b, gsl_vector_complex * x,\n gsl_vector_complex * residual)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (M < N)\n {\n GSL_ERROR (\"QR matrix must have M>=N\", GSL_EBADLEN);\n }\n else if (M != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (N != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else if (M != residual->size)\n {\n GSL_ERROR (\"matrix size must match residual size\", GSL_EBADLEN);\n }\n else\n {\n gsl_matrix_complex_const_view R = gsl_matrix_complex_const_submatrix (QR, 0, 0, N, N);\n gsl_vector_complex_view c = gsl_vector_complex_subvector(residual, 0, N);\n\n gsl_vector_complex_memcpy(residual, b);\n\n /* compute rhs = Q^H b */\n gsl_linalg_complex_QR_QHvec (QR, tau, residual);\n\n /* solve R x = rhs */\n gsl_vector_complex_memcpy(x, &(c.vector));\n gsl_blas_ztrsv (CblasUpper, CblasNoTrans, CblasNonUnit, &(R.matrix), x);\n\n /* compute residual = b - A x = Q (Q^H b - R x) */\n gsl_vector_complex_set_zero(&(c.vector));\n gsl_linalg_complex_QR_Qvec(QR, tau, residual);\n\n return GSL_SUCCESS;\n }\n}\n\n/* form the product v := Q^H v from a QR factorized matrix */\n\nint\ngsl_linalg_complex_QR_QHvec (const gsl_matrix_complex * QR, const gsl_vector_complex * tau, gsl_vector_complex * v)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (tau->size != N)\n {\n GSL_ERROR (\"size of tau must be N\", GSL_EBADLEN);\n }\n else if (v->size != M)\n {\n GSL_ERROR (\"vector size must be M\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n /* compute Q^H v */\n\n for (i = 0; i < GSL_MIN (M, N); i++)\n {\n gsl_vector_complex_const_view h = gsl_matrix_complex_const_subcolumn (QR, i, i, M - i);\n gsl_vector_complex_view w = gsl_vector_complex_subvector (v, i, M - i);\n gsl_complex ti = gsl_vector_complex_get (tau, i);\n gsl_complex ti_conj = gsl_complex_conjugate(ti);\n gsl_linalg_complex_householder_hv (ti_conj, &(h.vector), &(w.vector));\n }\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_complex_QR_Qvec (const gsl_matrix_complex * QR, const gsl_vector_complex * tau, gsl_vector_complex * v)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (tau->size != GSL_MIN (M, N))\n {\n GSL_ERROR (\"size of tau must be MIN(M,N)\", GSL_EBADLEN);\n }\n else if (v->size != M)\n {\n GSL_ERROR (\"vector size must be M\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n /* compute Q v */\n\n for (i = GSL_MIN (M, N); i-- > 0;)\n {\n gsl_vector_complex_const_view c = gsl_matrix_complex_const_column (QR, i);\n gsl_vector_complex_const_view h = gsl_vector_complex_const_subvector (&(c.vector),\n i, M - i);\n gsl_vector_complex_view w = gsl_vector_complex_subvector (v, i, M - i);\n gsl_complex ti = gsl_vector_complex_get (tau, i);\n /* we do not need the conjugate of ti here */\n gsl_linalg_complex_householder_hv (ti, &h.vector, &w.vector);\n }\n return GSL_SUCCESS;\n }\n}\n\n/* form the unitary matrix Q from the packed QR matrix */\nint\ngsl_linalg_complex_QR_unpack (const gsl_matrix_complex * QR, const gsl_vector_complex * tau,\n gsl_matrix_complex * Q, gsl_matrix_complex * R)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (Q->size1 != M || Q->size2 != M)\n {\n GSL_ERROR (\"Q matrix must be M x M\", GSL_ENOTSQR);\n }\n else if (R->size1 != M || R->size2 != N)\n {\n GSL_ERROR (\"R matrix must be M x N\", GSL_ENOTSQR);\n }\n else if (tau->size != N)\n {\n GSL_ERROR (\"size of tau must be N\", GSL_EBADLEN);\n }\n else\n {\n size_t i, j;\n\n /* initialize Q to the identity */\n gsl_matrix_complex_set_identity (Q);\n\n for (i = GSL_MIN (M, N); i-- > 0;)\n {\n gsl_vector_complex_const_view c = gsl_matrix_complex_const_column (QR, i);\n gsl_vector_complex_const_view h = gsl_vector_complex_const_subvector (&c.vector, i, M - i);\n gsl_matrix_complex_view m = gsl_matrix_complex_submatrix (Q, i, i, M - i, M - i);\n gsl_complex ti = gsl_vector_complex_get (tau, i);\n gsl_vector_complex_view work = gsl_matrix_complex_subcolumn(R, 0, 0, M - i);\n\n /* we do not need the conjugate of ti here */\n gsl_linalg_complex_householder_left (ti, &h.vector, &m.matrix, &work.vector);\n }\n\n /* form the right triangular matrix R from a packed QR matrix */\n\n for (i = 0; i < M; i++)\n {\n for (j = 0; j < i && j < N; j++)\n gsl_matrix_complex_set (R, i, j, GSL_COMPLEX_ZERO);\n\n for (j = i; j < N; j++)\n gsl_matrix_complex_set (R, i, j, gsl_matrix_complex_get (QR, i, j));\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "e24193735efe36de4357d177b37a27f87af7a858", "size": 9897, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qrc.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qrc.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qrc.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 28.8542274052, "max_line_length": 115, "alphanum_fraction": 0.6138223704, "num_tokens": 2754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7273451001612766}} {"text": "#include \n#include \n#include \n\ndouble f (double x, void *params);\nvoid integral_gen (int nmin, int nmax, double vals[]);\n\ndouble f (double x, void *params)\n{\n double n = *(double *) params;\n double f = exp (-x) *pow (x, n);\n \n return f;\n}\n\nvoid integral_gen (int nmin, int nmax, double vals[])\n{\n double result;\n double error;\n size_t np = 1000;\n gsl_integration_workspace *w = gsl_integration_workspace_alloc (np);\n gsl_function F;\n\n for (double n = nmin; n <= nmax; n++)\n {\n F.function = &f;\n F.params = &n;\n \n gsl_integration_qag( &F, 0., 1., 0., 1.e-7, np, GSL_INTEG_GAUSS15, w, &result, &error);\n vals[(int) n] = result;\n }\n}\n\n\n", "meta": {"hexsha": "0d09cfefb24e0ea9fccea7cc34bc2dc896b1bd03", "size": 789, "ext": "c", "lang": "C", "max_stars_repo_path": "integral_gen.c", "max_stars_repo_name": "Paulther/hw7", "max_stars_repo_head_hexsha": "3dc878517e9b97125b2896092912d7cdbe1610ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "integral_gen.c", "max_issues_repo_name": "Paulther/hw7", "max_issues_repo_head_hexsha": "3dc878517e9b97125b2896092912d7cdbe1610ad", "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": "integral_gen.c", "max_forks_repo_name": "Paulther/hw7", "max_forks_repo_head_hexsha": "3dc878517e9b97125b2896092912d7cdbe1610ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5428571429, "max_line_length": 99, "alphanum_fraction": 0.5538656527, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191309994467, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7266641205098291}} {"text": "#include \n#include \n#include \n#include \"compearth.h\"\n#ifdef COMPEARTH_USE_MKL\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#pragma clang diagnostic ignored \"-Wstrict-prototypes\"\n#endif\n#include \n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include \n#endif\n\n/*!\n * @brief Converts v-w coordinates to lune coordinates.\n *\n * @param[in] nv Number of v coordinates.\n * @param[in] v v coordinates s.t. \\f$ v \\in [-1/3, 1/3] \\f$. This\n * an array of dimension [nv].\n * @param[in] nw Number of w coordinates.\n * @param[in] w w coordinates (similar to lune latitudes) s.t. \n * \\f$ w \\in [-3\\pi/8, 3/pi/8] \\f$. This is an\n * array of dimension [nw].\n *\n * @param[out] gamma Longitude (degrees) \\f$ \\gamma \\in [-30,30] \\f$.\n * This is an array of dimension [nv].\n * @param[out] delta lune latitude (degrees) \\f$ \\delta \\in [-90,90] \\f$.\n * This is an array of dimension [nw].\n *\n * @result 0 indicates success.\n *\n * @author Carl Tape and converted to C by Ben Baker\n *\n * @date 2016\n *\n * @copyright MIT\n *\n */\nint compearth_rect2lune(const int nv, const double *__restrict__ v,\n const int nw, const double *__restrict__ w,\n double *__restrict__ gamma,\n double *__restrict__ delta) \n \n{\n double u[CE_CHUNKSIZE] __attribute__((aligned(64)));\n int i, j, ierr, nuLoc;\n/*\n const int maxit = 20;\n const int useHalley = 2;\n const double tol = 1.e-12;\n*/\n const double pi38 = 3.0*M_PI/8.0;\n const double pi180i = 180.0/M_PI;\n ierr = 0;\n // convert v -> gamma \n compearth_v2gamma(nv, v, gamma);\n // convert latitude to colatitude\n for (i=0; i beta\n ierr = compearth_u2beta(nuLoc, u, &delta[i]);\n //ierr = compearth_u2beta(nuLoc, maxit, useHalley, u, tol, &delta[i]);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Computing u2beta\\n\", __func__);\n return -1;\n }\n }\n // convert to gamma to degrees\n cblas_dscal(nv, pi180i, gamma, 1);\n // convert delta from colatitude to latitude and radians to degrees\n #pragma omp simd\n for (i=0; i\n\nextern PetscErrorCode formdirichletlaplacian(DM, Mat);\nextern PetscErrorCode formExactAndRHS(DM, Vec, Vec);\n\nint main(int argc,char **args) {\n PetscErrorCode ierr;\n DM da;\n KSP ksp;\n Mat A;\n Vec b,u,uexact;\n PetscReal errnorm;\n DMDALocalInfo info;\n\n PetscInitialize(&argc,&args,(char*)0,help);\n ierr = DMDACreate1d(PETSC_COMM_WORLD,\n DM_BOUNDARY_NONE,\n 9,1,1,NULL,\n &da); CHKERRQ(ierr);\n ierr = DMSetFromOptions(da); CHKERRQ(ierr);\n ierr = DMSetUp(da); CHKERRQ(ierr);\n ierr = DMDASetUniformCoordinates(da,0.0,1.0,-1.0,-1.0,-1.0,-1.0); CHKERRQ(ierr);\n ierr = DMCreateMatrix(da,&A);CHKERRQ(ierr);\n ierr = MatSetOptionsPrefix(A,\"a_\"); CHKERRQ(ierr);\n ierr = MatSetFromOptions(A); CHKERRQ(ierr);\n ierr = DMCreateGlobalVector(da,&b);CHKERRQ(ierr);\n ierr = VecDuplicate(b,&u); CHKERRQ(ierr);\n ierr = VecDuplicate(b,&uexact); CHKERRQ(ierr);\n ierr = formExactAndRHS(da,uexact,b); CHKERRQ(ierr);\n ierr = formdirichletlaplacian(da,A); CHKERRQ(ierr);\n ierr = KSPCreate(PETSC_COMM_WORLD,&ksp); CHKERRQ(ierr);\n ierr = KSPSetOperators(ksp,A,A); CHKERRQ(ierr);\n ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr);\n ierr = KSPSolve(ksp,b,u); CHKERRQ(ierr);\n ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uxact\n ierr = VecNorm(u,NORM_INFINITY,&errnorm); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info);CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"on %d point grid: error |u-uexact|_inf = %g\\n\",\n info.mx,errnorm); CHKERRQ(ierr);\n VecDestroy(&u); VecDestroy(&uexact); VecDestroy(&b);\n MatDestroy(&A); KSPDestroy(&ksp); DMDestroy(&da);\n return PetscFinalize();\n}\n\nPetscErrorCode formdirichletlaplacian(DM da, Mat A) {\n PetscErrorCode ierr;\n DMDALocalInfo info;\n PetscInt i;\n\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n for (i=info.xs; i0) {\n col[ncols] = i-1; v[ncols++] = -1.0; }\n if (i+10) && (i\n#include \n\n#include \n#include \n\ntypedef struct {\n gsl_vector *alpha, *center;\n double offset;\n} Params;\n\n/*\n * Function implements a 2-D parabola centered on center, with minimum\n * at offset.\n * */\ndouble parabola(const gsl_vector *v, void *params) {\n double x = gsl_vector_get(v, 0);\n double y = gsl_vector_get(v, 1);\n Params *p = (Params *) params;\n double a = gsl_vector_get(p->alpha, 0);\n double b = gsl_vector_get(p->alpha, 1);\n double c = p->offset;\n x -= gsl_vector_get(p->center, 0);\n y -= gsl_vector_get(p->center, 1);\n return a*x*x + b*y*y + c;\n}\n\nint main(int argc, char *argv[]) {\n const int nr_dims = 2, nr_iters = 100;\n /* Use Nelder & Mead simplex method */\n const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex2;\n gsl_multimin_fminimizer *multimin;\n gsl_multimin_function f;\n gsl_vector *x, *step_size;\n Params params;\n int iter_nr = 0, status;\n double size;\n\n /* Initialize the parameters */\n params.alpha = gsl_vector_alloc(nr_dims);\n gsl_vector_set(params.alpha, 0, 1.0);\n gsl_vector_set(params.alpha, 1, 2.0);\n params.center = gsl_vector_alloc(nr_dims);\n gsl_vector_set(params.center, 0, 1.5);\n gsl_vector_set(params.center, 1, -0.5);\n params.offset = 3.4;\n f.n = nr_dims;\n f.f = parabola;\n f.params = ¶ms;\n\n /* Initiallize the initial position */\n x = gsl_vector_alloc(nr_dims);\n gsl_vector_set(x, 0, 2.3);\n gsl_vector_set(x, 1, -1.5);\n\n /* Initialize the simplex step sizes */\n step_size = gsl_vector_alloc(nr_dims);\n gsl_vector_set_all(step_size, 1.0);\n\n /* Initialize the minimizer */\n multimin = gsl_multimin_fminimizer_alloc(T, 2);\n gsl_multimin_fminimizer_set(multimin, &f, x, step_size);\n\n /* Do the iterations until success, or the maximum number of iterations\n * is exceeded. */\n do {\n iter_nr++;\n /* Do an iteration step */\n status = gsl_multimin_fminimizer_iterate(multimin);\n if (status)\n break;\n /* Determine the step size to use a a stopping criterion */\n size = gsl_multimin_fminimizer_size(multimin);\n status = gsl_multimin_test_size(size, 1.0e-4);\n if (status == GSL_SUCCESS) {\n printf(\"Minimum:\\n\");\n printf(\"%4d: f(%.5f, %.5f) = %.5f, last step size = %.5f\\n\",\n iter_nr,\n gsl_vector_get(multimin->x, 0),\n gsl_vector_get(multimin->x, 1),\n multimin->fval,\n size);\n printf(\"Expected:\\n\");\n printf(\" f(%.5f, %.5f) = %.5f\\n\",\n gsl_vector_get(params.center, 0),\n gsl_vector_get(params.center, 1),\n params.offset);\n } else {\n fprintf(stderr, \"%4d: f(%.5f, %.5f) = %.5f, step size = %.5f\\n\",\n iter_nr,\n gsl_vector_get(multimin->x, 0),\n gsl_vector_get(multimin->x, 1),\n multimin->fval,\n size);\n }\n } while (status == GSL_CONTINUE && iter_nr < nr_iters);\n\n /* Free everything that was allocated */\n gsl_multimin_fminimizer_free(multimin);\n gsl_vector_free(x);\n gsl_vector_free(step_size);\n gsl_vector_free(params.alpha);\n gsl_vector_free(params.center);\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "3ee080e4646ab5a51da87c10bfb82e436b8c2d77", "size": 3438, "ext": "c", "lang": "C", "max_stars_repo_path": "Math/GSL/Multimin/multimin.c", "max_stars_repo_name": "Gjacquenot/training-material", "max_stars_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "Math/GSL/Multimin/multimin.c", "max_issues_repo_name": "Gjacquenot/training-material", "max_issues_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "Math/GSL/Multimin/multimin.c", "max_forks_repo_name": "Gjacquenot/training-material", "max_forks_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 32.4339622642, "max_line_length": 79, "alphanum_fraction": 0.592495637, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7241817882003665}} {"text": "#include \n#include \n#include \n\n/* Find a minimum in x=[0,1] of the interpolating quadratic through\n * (0,f0) (1,f1) with derivative fp0 at x=0. The interpolating\n * polynomial is q(x) = f0 + fp0 * z + (f1-f0-fp0) * z^2\n */\n\nstatic double\ninterp_quad (double f0, double fp0, double f1, double zl, double zh)\n{\n double fl = f0 + zl*(fp0 + zl*(f1 - f0 -fp0));\n double fh = f0 + zh*(fp0 + zh*(f1 - f0 -fp0));\n double c = 2 * (f1 - f0 - fp0); /* curvature */\n\n double zmin = zl, fmin = fl;\n\n if (fh < fmin) { zmin = zh; fmin = fh; } \n\n if (c > 0) /* positive curvature required for a minimum */\n {\n double z = -fp0 / c; /* location of minimum */\n if (z > zl && z < zh) {\n double f = f0 + z*(fp0 + z*(f1 - f0 -fp0));\n if (f < fmin) { zmin = z; fmin = f; };\n }\n }\n\n return zmin;\n}\n\n/* Find a minimum in x=[0,1] of the interpolating cubic through\n * (0,f0) (1,f1) with derivatives fp0 at x=0 and fp1 at x=1.\n *\n * The interpolating polynomial is:\n *\n * c(x) = f0 + fp0 * z + eta * z^2 + xi * z^3\n *\n * where eta=3*(f1-f0)-2*fp0-fp1, xi=fp0+fp1-2*(f1-f0). \n */\n\nstatic double\ncubic (double c0, double c1, double c2, double c3, double z)\n{\n return c0 + z * (c1 + z * (c2 + z * c3));\n}\n\nstatic void\ncheck_extremum (double c0, double c1, double c2, double c3, double z,\n double *zmin, double *fmin)\n{\n /* could make an early return by testing curvature >0 for minimum */\n\n double y = cubic (c0, c1, c2, c3, z);\n\n if (y < *fmin) \n {\n *zmin = z; /* accepted new point*/\n *fmin = y;\n }\n}\n\nstatic double\ninterp_cubic (double f0, double fp0, double f1, double fp1, double zl, double zh)\n{\n double eta = 3 * (f1 - f0) - 2 * fp0 - fp1;\n double xi = fp0 + fp1 - 2 * (f1 - f0);\n double c0 = f0, c1 = fp0, c2 = eta, c3 = xi;\n double zmin, fmin;\n double z0, z1;\n\n zmin = zl; fmin = cubic(c0, c1, c2, c3, zl);\n check_extremum (c0, c1, c2, c3, zh, &zmin, &fmin);\n\n {\n int n = gsl_poly_solve_quadratic (3 * c3, 2 * c2, c1, &z0, &z1);\n \n if (n == 2) /* found 2 roots */\n {\n if (z0 > zl && z0 < zh) \n check_extremum (c0, c1, c2, c3, z0, &zmin, &fmin);\n if (z1 > zl && z1 < zh) \n check_extremum (c0, c1, c2, c3, z1, &zmin, &fmin);\n }\n else if (n == 1) /* found 1 root */\n {\n if (z0 > zl && z0 < zh) \n check_extremum (c0, c1, c2, c3, z0, &zmin, &fmin);\n }\n }\n\n return zmin;\n}\n\n\nstatic double\ninterpolate (double a, double fa, double fpa,\n double b, double fb, double fpb, double xmin, double xmax,\n int order)\n{\n /* Map [a,b] to [0,1] */\n double z, alpha, zmin, zmax;\n\n zmin = (xmin - a) / (b - a);\n zmax = (xmax - a) / (b - a);\n\n if (zmin > zmax)\n {\n double tmp = zmin;\n zmin = zmax;\n zmax = tmp;\n };\n \n if (order > 2 && GSL_IS_REAL(fpb)) {\n z = interp_cubic (fa, fpa * (b - a), fb, fpb * (b - a), zmin, zmax);\n } else {\n z = interp_quad (fa, fpa * (b - a), fb, zmin, zmax);\n }\n\n alpha = a + z * (b - a);\n\n return alpha;\n}\n\n/* recommended values from Fletcher are \n rho = 0.01, sigma = 0.1, tau1 = 9, tau2 = 0.05, tau3 = 0.5 */\n\nstatic int\nminimize (gsl_function_fdf * fn, double rho, double sigma, \n double tau1, double tau2, double tau3,\n int order, double alpha1, double *alpha_new)\n{\n double f0, fp0, falpha, falpha_prev, fpalpha, fpalpha_prev, delta,\n alpha_next;\n double alpha = alpha1, alpha_prev = 0.0;\n double a, b, fa, fb, fpa, fpb;\n const size_t bracket_iters = 100, section_iters = 100;\n size_t i = 0;\n\n GSL_FN_FDF_EVAL_F_DF (fn, 0.0, &f0, &fp0);\n falpha_prev = f0;\n fpalpha_prev = fp0;\n\n /* Avoid uninitialized variables morning */\n a = 0.0; b = alpha;\n fa = f0; fb = 0.0;\n fpa = fp0; fpb = 0.0;\n\n /* Begin bracketing */ \n\n while (i++ < bracket_iters)\n {\n falpha = GSL_FN_FDF_EVAL_F (fn, alpha);\n\n /* Fletcher's rho test */\n\n if (falpha > f0 + alpha * rho * fp0 || falpha >= falpha_prev)\n {\n a = alpha_prev; fa = falpha_prev; fpa = fpalpha_prev;\n b = alpha; fb = falpha; fpb = GSL_NAN;\n break; /* goto sectioning */\n }\n\n fpalpha = GSL_FN_FDF_EVAL_DF (fn, alpha);\n\n /* Fletcher's sigma test */\n\n if (fabs (fpalpha) <= -sigma * fp0)\n {\n *alpha_new = alpha;\n return GSL_SUCCESS;\n }\n\n if (fpalpha >= 0)\n {\n a = alpha; fa = falpha; fpa = fpalpha;\n b = alpha_prev; fb = falpha_prev; fpb = fpalpha_prev;\n break; /* goto sectioning */\n }\n\n delta = alpha - alpha_prev;\n\n {\n double lower = alpha + delta;\n double upper = alpha + tau1 * delta;\n\n alpha_next = interpolate (alpha_prev, falpha_prev, fpalpha_prev,\n alpha, falpha, fpalpha, lower, upper, order);\n\n }\n\n alpha_prev = alpha;\n falpha_prev = falpha;\n fpalpha_prev = fpalpha;\n alpha = alpha_next;\n }\n\n /* Sectioning of bracket [a,b] */\n \n while (i++ < section_iters)\n {\n delta = b - a;\n \n {\n double lower = a + tau2 * delta;\n double upper = b - tau3 * delta;\n \n alpha = interpolate (a, fa, fpa, b, fb, fpb, lower, upper, order);\n }\n \n falpha = GSL_FN_FDF_EVAL_F (fn, alpha);\n \n if ((a-alpha)*fpa <= GSL_DBL_EPSILON) {\n /* roundoff prevents progress */\n return GSL_ENOPROG;\n };\n\n if (falpha > f0 + rho * alpha * fp0 || falpha >= fa)\n {\n /* a_next = a; */\n b = alpha; fb = falpha; fpb = GSL_NAN;\n }\n else\n {\n fpalpha = GSL_FN_FDF_EVAL_DF (fn, alpha);\n \n if (fabs(fpalpha) <= -sigma * fp0)\n {\n *alpha_new = alpha;\n return GSL_SUCCESS; /* terminate */\n }\n \n if ( ((b-a) >= 0 && fpalpha >= 0) || ((b-a) <=0 && fpalpha <= 0))\n {\n b = a; fb = fa; fpb = fpa;\n a = alpha; fa = falpha; fpa = fpalpha;\n }\n else\n {\n a = alpha; fa = falpha; fpa = fpalpha;\n }\n }\n }\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "60677d63b358b9fc81e00eccc79eb6931dbfd3a5", "size": 6248, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/multimin/linear_minimize.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multimin/linear_minimize.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multimin/linear_minimize.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 25.1935483871, "max_line_length": 81, "alphanum_fraction": 0.5113636364, "num_tokens": 2127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7240084274048754}} {"text": "#pragma once\n\n#include \n#include \n\n#include \n\n\n#include \n#include \n\n\n#include \n\n\n#define MATRIX_AT(m, i, j) (*((m->data + ((i) * m->tda + (j)))))\n\nclass Vector3d;\n\n\n/*====================================================================================================================================================================*\n | This class will be used to represent matrices of arbitrary sizes (m rows by n columns) that have elements of type double. The underlying data strucutre used by |\n | this class is gsl's (Gnu Scientific Library) matrix class. This class also makes use of the ATLAS implementation of BLAS for some operations such as matrix-matrix |\n | multiplication. This class is meant to improve performance, not necessarily ease of use. |\n *====================================================================================================================================================================*/\n\nclass MATHLIB_DECLSPEC Matrix {\nfriend class Vector;\nfriend class ParticleEngine;\nprotected:\n\n\t//this data structure holds all the matrix data\n\tgsl_matrix *matrix;\n\n\npublic:\n\t/**\n\t\tconstructor - creates an m rows by n columns matrix that is not initialized to any particular values\n\t*/\n\tMatrix(int m, int n);\n\n\t/**\n\t\tdefault constructor\n\t*/\n\tMatrix();\n\n\t/**\n\t\tcopy constructor - performs a deep copy of the matrix passed in as a parameter.\n\t*/\n\tMatrix(const Matrix& other);\n\n\t/**\n\t\tdestructor.\n\t*/\n\t~Matrix();\n\n\t/**\n\t\tloads the matrix with all zero values.\n\t*/\n\tvoid loadZero();\n\n\t/**\n\t\tloads the matrix with 1's on the diagonal, 0's everywhere else - note: the matrix doesn't have to be square.\n\t*/\n\tvoid loadIdentity();\n\n\t/**\n\t\tthis method sets the current matrix to a 3x3 matrix that is equal to the outer product of the vectors a and b\n\t*/\n\tvoid setToOuterproduct(const Vector3d& a, const Vector3d& b);\n\n\t/**\n\t\tthis method resizes the current matrix to have m rows and n cols. If not enough space is allocated for it, then a new matrix of\n\t\tcorrect dimensions is allocated. There is no guarantee with regards to the data that is contained in the matrix after a resize operation.\n\t*/\n\tvoid resizeTo(int m, int n);\n\n\t/**\n\t\tcopy operator - performs a deep copy of the matrix passed in as a parameter.\n\t*/\n\tMatrix& operator=(const Matrix &other);\n\n\t/**\n\t\tthis method performs a shallow copy of the matrix that is passed in as a parameter.\n\t*/\n\tvoid shallowCopy(const Matrix& other, int startRow = 0, int startCol = 0, int endRow = -1, int endCol = -1);\n\n\t/**\n\t\tthis method performs a deep copy of the matrix that is passed in as a paramerer.\n\t*/\n\tvoid deepCopy(const Matrix& other);\n\n\t/**\n\t\tReturns the number of columns\n\t*/\n\tint getColumnCount() const;\n\n\t/**\n\t\tReturns the number of rows\n\t*/\n\tint getRowCount()const;\n\n\t/**\n\t\tMultiplies each element in the current matrix by a constant\n\t*/\n\tvoid multiplyBy(const double val);\n\n\t/**\n\t\tThis method sets the current matrix to be equal to one of the products: a * b, a'*b, a*b' or a'*b'.\n\t\tThe values of transA and transB indicate which of the matrices are tranposed and which ones are not.\n\t*/\n\tvoid setToProductOf(const Matrix& a, const Matrix& b, bool transA = false, bool transB = false);\n\n\t/**\n\t\tThis method computes the inverse of the matrix a and writes it over the current matrix. The implementation\n\t\tfor the inverse of a matrix was obtained from Graphite. The parameter t is used as a threshold value for\n\t\tdeterminants, etc so that we still get a result for the inverse of our matrix even if it is very poorly conditioned.\n\t*/\n\tvoid setToInverseOf(const Matrix &a, double t = 0);\n\n\t/**\n\t\tThis method prints the contents of the matrix - testing purpose only.\n\t*/\n\tvoid printMatrix() const;\n\n\t/**\n\t\tThis method sets the current matrix to be a sub-matrix (starting at (i,j) and ending at (i+rows, j+cols)\n\t\tof the one that is passed in as a parameter - shallow copy only.\n\t*/\n\tvoid setToSubmatrix(const Matrix &a, int i, int j, int rows, int cols);\n\n\t/**\n\t\tThis method returns a copy of the value of the matrix at (i,j)\n\t*/\n\tdouble get(int i, int j) const;\n\n\t/**\n\t\tThis method sets the value of the matrix at (i,j) to newVal.\n\t*/\n\tvoid set(int i, int j, double newVal);\n\n\n\t/**\n\t\tThis method is used to set the values in the matrix to the ones that are passed in the array of doubles.\n\t\tIt is assumed that the array contains the right number of elements and that there is no space between consecutive rows (tda == nrCols).\n\t*/\n\tvoid setValues(double* vals);\n\n\t/**\n\t\tthis method returns a pointer to its internal matrix data structure\n\t*/\n\tgsl_matrix* getMatrixPointer() const;\n\n\n\t/**\n\t\tImplement this operator to have a quick way of multiplying 3x3 matrices by vectors - used for dynamics for instance\n\t*/\n\tVector3d operator * (const Vector3d &other);\n\n\t/**\n\t\tImplement a potentially faster function for 3x3 matrix - vector3d multiplication. Result and v need to be different!!\n\t*/\n\tvoid postMultiplyVector(const Vector3d& v, Vector3d& result);\n\n\t/**\n\t\tStill need to do (if need be): get row/col vector. Initialize a matrix from a vector so that we can create a 1xn matrix easily.\n\t\tmake sure dgemv works properly, implement vector class, etc, swap, add, scale matrices, etc\n\t*/\n\n\t/**\n\t\tthis method adds the matrix that is passed in as a parameter to the current matrix. In addition, it scales, both matrices by the two\n\t\tnumbers that are passed in as parameters:\n\t\t*this = a * *this + b * other.\n\t*/\n\tvoid add(const Matrix& other, double scaleA = 1.0, double scaleB = 1.0);\n\n\t/**\n\t\tthis method subtracts the matrix that is passed in as a parameter from the current matrix. In addition, it scales, both matrices by the two\n\t\tnumbers that are passed in as parameters:\n\t\t*this = a * *this - b * other.\n\t*/\n\tvoid sub(const Matrix& other, double scaleA = 1.0, double scaleB = 1.0);\n\n};\n\n\n\nMATHLIB_DECLSPEC void testMatrixClass();", "meta": {"hexsha": "bf663bcf43c9e3e289f2cd6dc604eb6e650c2ab4", "size": 5992, "ext": "h", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/MathLib/Matrix.h", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/MathLib/Matrix.h", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "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": "Cartwheel/cartwheel-3d/MathLib/Matrix.h", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8723404255, "max_line_length": 168, "alphanum_fraction": 0.6652202937, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789547, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.7235428009677521}} {"text": "//\r\n// Created by karl_ on 2020-5-3.\r\n//\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n// ref: https://www.math.uci.edu/icamp/courses/math77c/demos/hist_eq.pdf\r\nstatic void histeq(double const *src, double *dst, size_t area, unsigned range) {\r\n unsigned *cdf;\r\n size_t i;\r\n cdf = calloc(range, sizeof(unsigned));\r\n for (i = 0; i < area; ++i) {\r\n cdf[(int) (src[i] * range)] += 1;\r\n }\r\n for (i = 1; i < range; ++i) {\r\n cdf[i] += cdf[i - 1];\r\n }\r\n for (i = 0; i < area; ++i) {\r\n dst[i] = floor((double) (range - 1) * cdf[(int) (src[i] * range)] / area) / range;\r\n }\r\n free(cdf);\r\n}\r\n\r\n\r\ngboolean imgproc_histogram_equalization(CoreImage *src, CoreImage **dst) {\r\n gdouble *src_data_cast = NULL;\r\n gdouble *dst_data_cast = NULL;\r\n gpointer src_data, dst_data;\r\n CoreSize *size = NULL;\r\n guint8 channel;\r\n gsize i, area;\r\n CoreColorSpace color_space;\r\n CorePixelType pixel_type;\r\n gdouble range, inv_range;\r\n g_return_val_if_fail(src != NULL, FALSE);\r\n g_return_val_if_fail(dst != NULL, FALSE);\r\n\r\n /* TODO: impl. for multiple channels */\r\n channel = core_image_get_channel(src);\r\n g_return_val_if_fail(channel == 1, FALSE);\r\n\r\n src = g_object_ref(src);\r\n src_data = core_image_get_data(src);\r\n size = core_image_get_size(src);\r\n area = core_size_get_area(size);\r\n color_space = core_image_get_color_space(src);\r\n pixel_type = core_image_get_pixel_type(src);\r\n range = core_pixel_get_range(pixel_type);\r\n inv_range = 1.0 / range;\r\n\r\n /* cast to double and normalize pixel data to [0, 1] */\r\n if (core_pixel_is_double(pixel_type)) {\r\n src_data_cast = src_data;\r\n } else if (core_pixel_is_uint8(pixel_type)) {\r\n src_data_cast = g_malloc(sizeof(gdouble) * area);\r\n for (i = 0; i < area; ++i) {\r\n src_data_cast[i] = ((guint8 *) src_data)[i] * inv_range;\r\n }\r\n } else {\r\n g_return_val_if_fail(FALSE, FALSE);\r\n }\r\n dst_data_cast = g_malloc(sizeof(gdouble) * area);\r\n\r\n /* run the algorithm */\r\n histeq(src_data_cast, dst_data_cast, area, 256);\r\n\r\n /* cast back to uchar */\r\n if (core_pixel_is_double(pixel_type)) {\r\n /* exactly do nothing */\r\n } else if (core_pixel_is_uint8(pixel_type)) {\r\n /* reuse allocated memory */\r\n for (i = 0; i < area; ++i) {\r\n ((guint8 *) dst_data_cast)[i] = dst_data_cast[i] * 255.0;\r\n }\r\n } else {\r\n g_return_val_if_fail(FALSE, FALSE);\r\n }\r\n dst_data = dst_data_cast;\r\n if (core_pixel_is_uint8(pixel_type)) {\r\n /* release useless memory, can be removed for speed */\r\n dst_data = g_realloc(dst_data, sizeof(guint8) * area);\r\n }\r\n\r\n if (*dst == NULL) {\r\n *dst = core_image_new_with_data(dst_data, color_space, pixel_type, size, FALSE);\r\n } else {\r\n core_image_assign_data(*dst, dst_data, color_space, pixel_type, size, FALSE);\r\n }\r\n\r\n /* free allocated additional memory */\r\n if (core_pixel_is_uint8(pixel_type)) {\r\n g_free(src_data_cast);\r\n }\r\n g_object_unref(size);\r\n g_object_unref(src);\r\n return TRUE;\r\n}\r\n", "meta": {"hexsha": "31586ad8c4d99e8454b1feb9ad0c6bd2fed6adcc", "size": 3243, "ext": "c", "lang": "C", "max_stars_repo_path": "imgproc/histogram-equalization.c", "max_stars_repo_name": "zhengbanbufengbi/EasyPhotoshop", "max_stars_repo_head_hexsha": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-30T14:58:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-30T14:58:05.000Z", "max_issues_repo_path": "imgproc/histogram-equalization.c", "max_issues_repo_name": "zhengbanbufengbi/EasyPhotoshop", "max_issues_repo_head_hexsha": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "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": "imgproc/histogram-equalization.c", "max_forks_repo_name": "zhengbanbufengbi/EasyPhotoshop", "max_forks_repo_head_hexsha": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4854368932, "max_line_length": 91, "alphanum_fraction": 0.6034535924, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.7232450776246291}} {"text": "/* fft/dft_complex.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"complex_internal.h\"\n\nint\ngsl_dft_complex_forward (const double data[], \n const size_t stride, const size_t n,\n double result[])\n{\n gsl_fft_direction sign = forward;\n int status = gsl_dft_complex (data, stride, n, result, sign);\n return status;\n}\n\nint\ngsl_dft_complex_backward (const double data[], \n const size_t stride, const size_t n,\n double result[])\n{\n gsl_fft_direction sign = backward;\n int status = gsl_dft_complex (data, stride, n, result, sign);\n return status;\n}\n\n\nint\ngsl_dft_complex_inverse (const double data[], \n const size_t stride, const size_t n,\n double result[])\n{\n gsl_fft_direction sign = backward;\n int status = gsl_dft_complex (data, stride, n, result, sign);\n\n /* normalize inverse fft with 1/n */\n\n {\n const ATOMIC norm = 1.0 / n;\n size_t i;\n for (i = 0; i < n; i++)\n {\n REAL(result,stride,i) *= norm;\n IMAG(result,stride,i) *= norm;\n }\n }\n return status;\n}\n\nint\ngsl_dft_complex (const double data[], \n const size_t stride, const size_t n,\n double result[],\n const gsl_fft_direction sign)\n{\n\n size_t i, j, exponent;\n\n const double d_theta = 2.0 * ((int) sign) * M_PI / (double) n;\n\n /* FIXME: check that input length == output length and give error */\n\n for (i = 0; i < n; i++)\n {\n ATOMIC sum_real = 0;\n ATOMIC sum_imag = 0;\n\n exponent = 0;\n\n for (j = 0; j < n; j++)\n {\n double theta = d_theta * (double) exponent;\n /* sum = exp(i theta) * data[j] */\n\n ATOMIC w_real = cos (theta);\n ATOMIC w_imag = sin (theta);\n\n ATOMIC data_real = REAL(data,stride,j);\n ATOMIC data_imag = IMAG(data,stride,j);\n\n sum_real += w_real * data_real - w_imag * data_imag;\n sum_imag += w_real * data_imag + w_imag * data_real;\n\n exponent = (exponent + i) % n;\n }\n REAL(result,stride,i) = sum_real;\n IMAG(result,stride,i) = sum_imag;\n }\n\n return 0;\n}\n", "meta": {"hexsha": "dcecf3e18d5f8696671b457e23c3ad09d4d69ce8", "size": 3083, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/dft_complex.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/dft_complex.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/dft_complex.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.0438596491, "max_line_length": 81, "alphanum_fraction": 0.6104443724, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7224281155338872}} {"text": "/* linalg/lu.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"gsl_linalg.h\"\n\n#define REAL double\n\n/* Factorise a general N x N matrix A into,\n *\n * P A = L U\n *\n * where P is a permutation matrix, L is unit lower triangular and U\n * is upper triangular.\n *\n * L is stored in the strict lower triangular part of the input\n * matrix. The diagonal elements of L are unity and are not stored.\n *\n * U is stored in the diagonal and upper triangular part of the\n * input matrix. \n * \n * P is stored in the permutation p. Column j of P is column k of the\n * identity matrix, where k = permutation->data[j]\n *\n * signum gives the sign of the permutation, (-1)^n, where n is the\n * number of interchanges in the permutation. \n *\n * See Golub & Van Loan, Matrix Computations, Algorithm 3.4.1 (Gauss\n * Elimination with Partial Pivoting).\n */\n\nint\ngsl_linalg_LU_decomp (gsl_matrix * A, gsl_permutation * p, int *signum)\n{\n if (A->size1 != A->size2)\n {\n GSL_ERROR (\"LU decomposition requires square matrix\", GSL_ENOTSQR);\n }\n else if (p->size != A->size1)\n {\n GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n }\n else\n {\n const size_t N = A->size1;\n size_t i, j, k;\n\n *signum = 1;\n gsl_permutation_init (p);\n\n for (j = 0; j < N - 1; j++)\n\t{\n\t /* Find maximum in the j-th column */\n\n\t REAL ajj, max = fabs (gsl_matrix_get (A, j, j));\n\t size_t i_pivot = j;\n\n\t for (i = j + 1; i < N; i++)\n\t {\n\t REAL aij = fabs (gsl_matrix_get (A, i, j));\n\n\t if (aij > max)\n\t\t{\n\t\t max = aij;\n\t\t i_pivot = i;\n\t\t}\n\t }\n\n\t if (i_pivot != j)\n\t {\n\t gsl_matrix_swap_rows (A, j, i_pivot);\n\t gsl_permutation_swap (p, j, i_pivot);\n\t *signum = -(*signum);\n\t }\n\n\t ajj = gsl_matrix_get (A, j, j);\n\n\t if (ajj != 0.0)\n\t {\n\t for (i = j + 1; i < N; i++)\n\t\t{\n\t\t REAL aij = gsl_matrix_get (A, i, j) / ajj;\n\t\t gsl_matrix_set (A, i, j, aij);\n\n\t\t for (k = j + 1; k < N; k++)\n\t\t {\n\t\t REAL aik = gsl_matrix_get (A, i, k);\n\t\t REAL ajk = gsl_matrix_get (A, j, k);\n\t\t gsl_matrix_set (A, i, k, aik - aij * ajk);\n\t\t }\n\t\t}\n\t }\n\t}\n \n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_LU_solve (const gsl_matrix * LU, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x)\n{\n if (LU->size1 != LU->size2)\n {\n GSL_ERROR (\"LU matrix must be square\", GSL_ENOTSQR);\n }\n else if (LU->size1 != p->size)\n {\n GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n }\n else if (LU->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (LU->size2 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* Copy x <- b */\n\n gsl_vector_memcpy (x, b);\n\n /* Solve for x */\n\n gsl_linalg_LU_svx (LU, p, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_LU_svx (const gsl_matrix * LU, const gsl_permutation * p, gsl_vector * x)\n{\n if (LU->size1 != LU->size2)\n {\n GSL_ERROR (\"LU matrix must be square\", GSL_ENOTSQR);\n }\n else if (LU->size1 != p->size)\n {\n GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n }\n else if (LU->size1 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution/rhs size\", GSL_EBADLEN);\n }\n else\n {\n /* Apply permutation to RHS */\n\n gsl_permute_vector (p, x);\n\n /* Solve for c using forward-substitution, L c = P b */\n\n gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasUnit, LU, x);\n\n /* Perform back-substitution, U x = c */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LU, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_LU_refine (const gsl_matrix * A, const gsl_matrix * LU, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x, gsl_vector * residual)\n{\n if (A->size1 != A->size2)\n {\n GSL_ERROR (\"matrix a must be square\", GSL_ENOTSQR);\n }\n if (LU->size1 != LU->size2)\n {\n GSL_ERROR (\"LU matrix must be square\", GSL_ENOTSQR);\n }\n else if (A->size1 != LU->size2)\n {\n GSL_ERROR (\"LU matrix must be decomposition of a\", GSL_ENOTSQR);\n }\n else if (LU->size1 != p->size)\n {\n GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n }\n else if (LU->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (LU->size1 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* Compute residual, residual = (A * x - b) */\n\n gsl_vector_memcpy (residual, b);\n gsl_blas_dgemv (CblasNoTrans, 1.0, A, x, -1.0, residual);\n\n /* Find correction, delta = - (A^-1) * residual, and apply it */\n\n gsl_linalg_LU_svx (LU, p, residual);\n gsl_blas_daxpy (-1.0, residual, x);\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_LU_invert (const gsl_matrix * LU, const gsl_permutation * p, gsl_matrix * inverse)\n{\n size_t i, n = LU->size1;\n\n int status = GSL_SUCCESS;\n\n gsl_matrix_set_identity (inverse);\n\n for (i = 0; i < n; i++)\n {\n gsl_vector_view c = gsl_matrix_column (inverse, i);\n int status_i = gsl_linalg_LU_svx (LU, p, &(c.vector));\n\n if (status_i)\n\tstatus = status_i;\n }\n\n return status;\n}\n\ndouble\ngsl_linalg_LU_det (gsl_matrix * LU, int signum)\n{\n size_t i, n = LU->size1;\n\n double det = (double) signum;\n\n for (i = 0; i < n; i++)\n {\n det *= gsl_matrix_get (LU, i, i);\n }\n\n return det;\n}\n\n\ndouble\ngsl_linalg_LU_lndet (gsl_matrix * LU)\n{\n size_t i, n = LU->size1;\n\n double lndet = 0.0;\n\n for (i = 0; i < n; i++)\n {\n lndet += log (fabs (gsl_matrix_get (LU, i, i)));\n }\n\n return lndet;\n}\n\n\nint\ngsl_linalg_LU_sgndet (gsl_matrix * LU, int signum)\n{\n size_t i, n = LU->size1;\n\n int s = signum;\n\n for (i = 0; i < n; i++)\n {\n double u = gsl_matrix_get (LU, i, i);\n\n if (u < 0)\n\t{\n\t s *= -1;\n\t}\n else if (u == 0)\n\t{\n\t s = 0;\n\t break;\n\t}\n }\n\n return s;\n}\n", "meta": {"hexsha": "4b83c82995844be4dc4e7dfa0d9f4ea195befcb2", "size": 6999, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/linalg/lu.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/linalg/lu.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/linalg/lu.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 22.3610223642, "max_line_length": 154, "alphanum_fraction": 0.6026575225, "num_tokens": 2185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7216718584279862}} {"text": "#include \n#include \n#include \n\n#include \n\n#include \"ccl.h\"\n\n/* ------- ROUTINE: ccl_linear spacing ------\nINPUTS: [xmin,xmax] of the interval to be divided in N bins\nOUTPUT: bin edges in range [xmin,xmax]\n*/\n\ndouble * ccl_linear_spacing(double xmin, double xmax, int N)\n{\n double dx = (xmax-xmin)/(N -1.);\n\n double * x = malloc(sizeof(double)*N);\n if (x==NULL) {\n ccl_raise_warning(\n CCL_ERROR_MEMORY,\n \"ERROR: Could not allocate memory for linear-spaced array (N=%d)\\n\", N);\n return x;\n }\n\n for (int i=0; i0 && xmin>0)) {\n ccl_raise_warning(\n CCL_ERROR_LINLOGSPACE,\n \"ERROR: Cannot make log-spaced array xminlog or xmin non-positive (had %le, %le)\\n\", xminlog, xmin);\n return NULL;\n }\n\n if (xminlog>xmin){\n ccl_raise_warning(CCL_ERROR_LINLOGSPACE, \"ERROR: xminlog must be smaller as xmin\");\n return NULL;\n }\n\n if (xmin>xmax){\n ccl_raise_warning(CCL_ERROR_LINLOGSPACE, \"ERROR: xmin must be smaller as xmax\");\n return NULL;\n }\n\n double * x = malloc(sizeof(double)*(Nlin+Nlog-1));\n if (x==NULL) {\n ccl_raise_warning(\n CCL_ERROR_MEMORY,\n \"ERROR: Could not allocate memory for array of size (Nlin+Nlog-1)=%d)\\n\", (Nlin+Nlog-1));\n return x;\n }\n\n double dx = (xmax-xmin)/(Nlin -1.);\n double log_xchange = log(xmin);\n double log_xmin = log(xminlog);\n double dlog_x = (log_xchange - log_xmin) / (Nlog-1.);\n\n for (int i=0; i=Nlog)\n x[i] = xmin + dx*(i-Nlog+1);\n }\n\n x[0]=xminlog; //Make sure roundoff errors don't spoil edges\n x[Nlog-1]=xmin; //Make sure roundoff errors don't spoil edges\n x[Nlin+Nlog-2]=xmax; //Make sure roundoff errors don't spoil edges\n\n return x;\n}\n\n/* ------- ROUTINE: ccl_log spacing ------\nINPUTS: [xmin,xmax] of the interval to be divided logarithmically in N bins\nTASK: divide an interval in N logarithmic bins\nOUTPUT: bin edges in range [xmin,xmax]\n*/\n\ndouble * ccl_log_spacing(double xmin, double xmax, int N)\n{\n if (N<2) {\n ccl_raise_warning(\n CCL_ERROR_LOGSPACE,\n \"ERROR: Cannot make log-spaced array with %d points - need at least 2\\n\", N);\n return NULL;\n }\n\n if (!(xmin>0 && xmax>0)) {\n ccl_raise_warning(\n CCL_ERROR_LOGSPACE,\n \"ERROR: Cannot make log-spaced array xmax or xmax non-positive (had %le, %le)\\n\", xmin, xmax);\n return NULL;\n }\n\n double log_xmax = log(xmax);\n double log_xmin = log(xmin);\n double dlog_x = (log_xmax - log_xmin) / (N-1.);\n\n double * x = malloc(sizeof(double)*N);\n if (x==NULL) {\n ccl_raise_warning(\n CCL_ERROR_MEMORY,\n \"ERROR: Could not allocate memory for log-spaced array (N=%d)\\n\", N);\n return x;\n }\n\n double xratio = exp(dlog_x);\n x[0] = xmin; //Make sure roundoff errors don't spoil edges\n for (int i=1; i number of points\n//x -> x-axis\n//y -> f(x)-axis\n//y0,yf -> values of f(x) to use beyond the interpolation range\nSplPar *ccl_spline_init(int n,double *x,double *y,double y0,double yf)\n{\n SplPar *spl=malloc(sizeof(SplPar));\n if(spl==NULL)\n return NULL;\n\n spl->intacc=gsl_interp_accel_alloc();\n spl->spline=gsl_spline_alloc(gsl_interp_cspline,n);\n int parstatus=gsl_spline_init(spl->spline,x,y,n);\n if(parstatus) {\n gsl_interp_accel_free(spl->intacc);\n gsl_spline_free(spl->spline);\n return NULL;\n }\n\n spl->x0=x[0];\n spl->xf=x[n-1];\n spl->y0=y0;\n spl->yf=yf;\n\n return spl;\n}\n\n//Evaluates spline at x checking for bound errors\ndouble ccl_spline_eval(double x,SplPar *spl)\n{\n if(x<=spl->x0)\n return spl->y0;\n else if(x>=spl->xf)\n return spl->yf;\n else {\n double y;\n int stat=gsl_spline_eval_e(spl->spline,x,spl->intacc,&y);\n if (stat!=GSL_SUCCESS) {\n ccl_raise_gsl_warning(stat, \"ccl_utils.c: ccl_splin_eval():\");\n return NAN;\n }\n return y;\n }\n}\n\n#define CCL_GAMMA1 2.6789385347077476336556 //Gamma(1/3)\n#define CCL_GAMMA2 1.3541179394264004169452 //Gamma(2/3)\n#define CCL_ROOTPI12 21.269446210866192327578 //12*sqrt(pi)\ndouble ccl_j_bessel(int l,double x)\n{\n double jl;\n double ax=fabs(x);\n double ax2=x*x;\n if(l<0) {\n fprintf(stderr,\"CosmoMas: l>0 for Bessel function\");\n exit(1);\n }\n\n if(l<7) {\n if(l==0) {\n if(ax<0.1) jl=1-ax2*(1-ax2/20.)/6.;\n else jl=sin(x)/x;\n }\n else if(l==1) {\n if(ax<0.2) jl=ax*(1-ax2*(1-ax2/28)/10)/3;\n else jl=(sin(x)/ax-cos(x))/ax;\n }\n else if(l==2) {\n if(ax<0.3) jl=ax2*(1-ax2*(1-ax2/36)/14)/15;\n else jl=(-3*cos(x)/ax-sin(x)*(1-3/ax2))/ax;\n }\n else if(l==3) {\n if(ax<0.4)\n\tjl=ax*ax2*(1-ax2*(1-ax2/44)/18)/105;\n else\n\tjl=(cos(x)*(1-15/ax2)-sin(x)*(6-15/ax2)/ax)/ax;\n }\n else if(l==4) {\n if(ax<0.6)\n\tjl=ax2*ax2*(1-ax2*(1-ax2/52)/22)/945;\n else\n\tjl=(sin(x)*(1-(45-105/ax2)/ax2)+cos(x)*(10-105/ax2)/ax)/ax;\n }\n else if(l==5) {\n if(ax<1.0)\n\tjl=ax2*ax2*ax*(1-ax2*(1-ax2/60)/26)/10395;\n else {\n\tjl=(sin(x)*(15-(420-945/ax2)/ax2)/ax-\n\t cos(x)*(1-(105-945/ax2)/ax2))/ax;\n }\n }\n else {\n if(ax<1.0)\n\tjl=ax2*ax2*ax2*(1-ax2*(1-ax2/68)/30)/135135;\n else {\n\tjl=(sin(x)*(-1+(210-(4725-10395/ax2)/ax2)/ax2)+\n\t cos(x)*(-21+(1260-10395/ax2)/ax2)/ax)/ax;\n }\n }\n }\n else {\n double nu=l+0.5;\n double nu2=nu*nu;\n\n if(ax<1.0E-40) jl=0;\n else if((ax2/l)<0.5) {\n jl=(exp(l*log(ax/nu)-M_LN2+nu*(1-M_LN2)-(1-(1-3.5/nu2)/(30*nu2))/(12*nu))/nu)*\n\t(1-ax2/(4*nu+4)*(1-ax2/(8*nu+16)*(1-ax2/(12*nu+36))));\n }\n else if((l*l/ax)<0.5) {\n double beta=ax-0.5*M_PI*(l+1);\n jl=(cos(beta)*(1-(nu2-0.25)*(nu2-2.25)/(8*ax2)*(1-(nu2-6.25)*(nu2-12.25)/(48*ax2)))-\n\t sin(beta)*(nu2-0.25)/(2*ax)*(1-(nu2-2.25)*(nu2-6.25)/(24*ax2)*\n\t\t\t\t (1-(nu2-12.25)*(nu2-20.25)/(80*ax2))))/ax;\n }\n else {\n double l3=pow(nu,0.325);\n if(axnu+1.48*l3) {\n\tdouble cosb=nu/ax;\n\tdouble sx=sqrt(ax2-nu2);\n\tdouble cotb=nu/sx;\n\tdouble secb=ax/nu;\n\tdouble beta=acos(cosb);\n\tdouble cot3b=cotb*cotb*cotb;\n\tdouble cot6b=cot3b*cot3b;\n\tdouble sec2b=secb*secb;\n\tdouble trigarg=nu/cotb-nu*beta-0.25*M_PI-\n\t ((2+3*sec2b)*cot3b/24+(16-(1512+(3654+375*sec2b)*sec2b)*sec2b)*\n\t cot3b*cot6b/(5760*nu2))/nu;\n\tdouble expterm=((4+sec2b)*sec2b*cot6b/16-\n\t\t\t(32+(288+(232+13*sec2b)*sec2b)*sec2b)*\n\t\t\tsec2b*cot6b*cot6b/(128*nu2))/nu2;\n\tjl=sqrt(cotb*cosb)/nu*exp(-expterm)*cos(trigarg);\n }\n else {\n\tdouble beta=ax-nu;\n\tdouble beta2=beta*beta;\n\tdouble sx=6/ax;\n\tdouble sx2=sx*sx;\n\tdouble secb=pow(sx,0.3333333333333333333333);\n\tdouble sec2b=secb*secb;\n\n\tjl=(CCL_GAMMA1*secb+beta*CCL_GAMMA2*sec2b\n\t -(beta2/18-1.0/45.0)*beta*sx*secb*CCL_GAMMA1\n\t -((beta2-1)*beta2/36+1.0/420.0)*sx*sec2b*CCL_GAMMA2\n\t +(((beta2/1620-7.0/3240.0)*beta2+1.0/648.0)*beta2-1.0/8100.0)*sx2*secb*CCL_GAMMA1\n\t +(((beta2/4536-1.0/810.0)*beta2+19.0/11340.0)*beta2-13.0/28350.0)*beta*sx2*sec2b*CCL_GAMMA2\n\t -((((beta2/349920-1.0/29160.0)*beta2+71.0/583200.0)*beta2-121.0/874800.0)*\n\t beta2+7939.0/224532000.0)*beta*sx2*sx*secb*CCL_GAMMA1)*sqrt(sx)/CCL_ROOTPI12;\n }\n }\n }\n if((x<0)&&(l%2!=0)) jl=-jl;\n\n return jl;\n}\n\n//Spline destructor\nvoid ccl_spline_free(SplPar *spl)\n{\n gsl_spline_free(spl->spline);\n gsl_interp_accel_free(spl->intacc);\n free(spl);\n}\n", "meta": {"hexsha": "2e7ff93830d093a30c5d0be7e55f89f92079cea3", "size": 8646, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_utils.c", "max_stars_repo_name": "Russell-Jones-OxPhys/CCL", "max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_utils.c", "max_issues_repo_name": "Russell-Jones-OxPhys/CCL", "max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccl_utils.c", "max_forks_repo_name": "Russell-Jones-OxPhys/CCL", "max_forks_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.850931677, "max_line_length": 106, "alphanum_fraction": 0.6139255147, "num_tokens": 3341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.720477440652254}} {"text": "//STARTWHOLE\nstatic char help[] = \"Newton's method for a two-variable system.\\n\"\n \"No analytical Jacobian. Run with -snes_fd or -snes_mf.\\n\\n\";\n\n#include \n\nextern PetscErrorCode FormFunction(SNES, Vec, Vec, void*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n SNES snes; // nonlinear solver context\n Vec x, r; // solution, residual vectors\n\n PetscInitialize(&argc,&argv,NULL,help);\n ierr = VecCreate(PETSC_COMM_WORLD,&x); CHKERRQ(ierr);\n ierr = VecSetSizes(x,PETSC_DECIDE,2); CHKERRQ(ierr);\n ierr = VecSetFromOptions(x); CHKERRQ(ierr);\n ierr = VecSet(x,1.0); CHKERRQ(ierr);\n ierr = VecDuplicate(x,&r); CHKERRQ(ierr);\n\n ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);\n ierr = SNESSetFunction(snes,r,FormFunction,NULL); CHKERRQ(ierr);\n ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);\n ierr = SNESSolve(snes,NULL,x); CHKERRQ(ierr);\n ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);\n\n VecDestroy(&x); VecDestroy(&r); SNESDestroy(&snes);\n return PetscFinalize();\n}\n\nPetscErrorCode FormFunction(SNES snes, Vec x, Vec F, void *ctx) {\n PetscErrorCode ierr;\n const double b = 2.0, *ax;\n double *aF;\n\n ierr = VecGetArrayRead(x,&ax);CHKERRQ(ierr);\n ierr = VecGetArray(F,&aF);CHKERRQ(ierr);\n aF[0] = (1.0 / b) * PetscExpReal(b * ax[0]) - ax[1];\n aF[1] = ax[0] * ax[0] + ax[1] * ax[1] - 1.0;\n ierr = VecRestoreArrayRead(x,&ax);CHKERRQ(ierr);\n ierr = VecRestoreArray(F,&aF);CHKERRQ(ierr);\n return 0;\n}\n//ENDWHOLE\n\n", "meta": {"hexsha": "fcd6b338bcc9ff6fada8885c201f20d27f6a1ed0", "size": 1553, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch4/expcircle.c", "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/ch4/expcircle.c", "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/ch4/expcircle.c", "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7608695652, "max_line_length": 68, "alphanum_fraction": 0.6497102382, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7200625615712817}} {"text": "/* randist/erlang.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n/* The sum of N samples from an exponential distribution gives an\n Erlang distribution\n\n p(x) dx = x^(n-1) exp (-x/a) / ((n-1)!a^n) dx\n\n for x = 0 ... +infty */\n\ndouble\ngsl_ran_erlang (const gsl_rng * r, const double a, const double n)\n{\n return gsl_ran_gamma (r, n, a);\n}\n\ndouble\ngsl_ran_erlang_pdf (const double x, const double a, const double n)\n{\n if (x <= 0) \n {\n return 0 ;\n }\n else\n {\n double p;\n double lngamma = gsl_sf_lngamma (n);\n\n p = exp ((n - 1) * log (x/a) - x/a - lngamma) / a;\n return p;\n }\n}\n", "meta": {"hexsha": "a990403dacb3dc7443eb534e6dd5b8684245ccb3", "size": 1505, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/erlang.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/randist/erlang.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/randist/erlang.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 27.3636363636, "max_line_length": 81, "alphanum_fraction": 0.673089701, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650403, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7180543981926256}} {"text": "#include \n#include \n#include \n#include \n\n#include \"demo_fn.h\"\n#include \"demo_fn.c\"\n\nint\nmain (void)\n{\n int status;\n int iter = 0, max_iter = 100;\n const gsl_root_fdfsolver_type *T;\n gsl_root_fdfsolver *s;\n double x0, x = 5.0, r_expected = sqrt (5.0);\n gsl_function_fdf FDF;\n struct quadratic_params params = {1.0, 0.0, -5.0};\n\n FDF.f = &quadratic;\n FDF.df = &quadratic_deriv;\n FDF.fdf = &quadratic_fdf;\n FDF.params = ¶ms;\n\n T = gsl_root_fdfsolver_newton;\n s = gsl_root_fdfsolver_alloc (T);\n gsl_root_fdfsolver_set (s, &FDF, x);\n\n printf (\"using %s method\\n\", \n gsl_root_fdfsolver_name (s));\n\n printf (\"%-5s %10s %10s %10s\\n\",\n \"iter\", \"root\", \"err\", \"err(est)\");\n do\n {\n iter++;\n status = gsl_root_fdfsolver_iterate (s);\n x0 = x;\n x = gsl_root_fdfsolver_root (s);\n status = gsl_root_test_delta (x, x0, 0, 1e-3);\n\n if (status == GSL_SUCCESS)\n printf (\"Converged:\\n\");\n\n printf (\"%5d %10.7f %+10.7f %10.7f\\n\",\n iter, x, x - r_expected, x - x0);\n }\n while (status == GSL_CONTINUE && iter < max_iter);\n\n gsl_root_fdfsolver_free (s);\n return status;\n}\n", "meta": {"hexsha": "fea5f110192870f94da343a123486f0c75ecfe68", "size": 1209, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/rootnewt.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/rootnewt.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/rootnewt.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 22.8113207547, "max_line_length": 52, "alphanum_fraction": 0.6104218362, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8333245932423309, "lm_q1q2_score": 0.7179409720117014}} {"text": "#include \n#include \n\n#include \n#include \n#include \n\nint main() {\n\tgsl_matrix* A;\n\tgsl_matrix* U;\n gsl_matrix* V;\n gsl_vector* S;\n gsl_vector* work;\n int i, j;\n int M, N;\n\n M = N = 2;\n\n work = gsl_vector_alloc(N);\n S = gsl_vector_alloc(N);\n A = gsl_matrix_alloc(M, N);\n V = gsl_matrix_alloc(N, N);\n\n gsl_matrix_set(A, 0, 0, -0.93);\n gsl_matrix_set(A, 0, 1, 1.80);\n gsl_matrix_set(A, 1, 0, 0);\n gsl_matrix_set(A, 1, 1, 0);\n\n gsl_linalg_SV_decomp(A, V, S, work);\n U = A;\n\n printf(\"S = [\");\n for (i=0; i\n#include \n#include \n#include \nint rosenbrock_f (const gsl_vector * x, void *params, \n\t\t gsl_vector * f);\nint print_state (size_t iter, gsl_multiroot_fsolver * s);\n\nstruct rparams\n {\n double a;\n double b;\n };\n\nint rosenbrock_f (const gsl_vector * x, void *params, \n gsl_vector * f)\n{\n double a = ((struct rparams *) params)->a;\n double b = ((struct rparams *) params)->b;\n\n const double x0 = gsl_vector_get (x, 0);\n const double x1 = gsl_vector_get (x, 1);\n\n const double y0 = a * (1 - x0);\n const double y1 = b * (x1 - x0 * x0);\n\n gsl_vector_set (f, 0, y0);\n gsl_vector_set (f, 1, y1);\n\n return GSL_SUCCESS;\n}\n\nint print_state (size_t iter, gsl_multiroot_fsolver * s)\n{\n printf (\"iter = %3u x = % .3f % .3f \"\n \"f(x) = % .3e % .3e\\n\",\n iter,\n gsl_vector_get (s->x, 0), \n gsl_vector_get (s->x, 1),\n gsl_vector_get (s->f, 0), \n gsl_vector_get (s->f, 1));\n return 0;\n}\n\nint main (void)\n{\n const gsl_multiroot_fsolver_type *T;\n gsl_multiroot_fsolver *s;\n\n int status;\n size_t iter = 0;\n\n const size_t n = 2;\n struct rparams p = {1.0, 10.0};\n gsl_multiroot_function f = {&rosenbrock_f, n, &p};\n\n double x_init[2] = {-10.0, -5.0};\n gsl_vector *x = gsl_vector_alloc (n);\n\n gsl_vector_set (x, 0, x_init[0]);\n gsl_vector_set (x, 1, x_init[1]);\n\n T = gsl_multiroot_fsolver_hybrids;\n s = gsl_multiroot_fsolver_alloc (T, 2);\n gsl_multiroot_fsolver_set (s, &f, x);\n\n print_state (iter, s);\n\n do\n {\n iter++;\n status = gsl_multiroot_fsolver_iterate (s);\n\n print_state (iter, s);\n\n if (status) /* check if solver is stuck */\n break;\n\n status = \n gsl_multiroot_test_residual (s->f, 1e-7);\n }\n while (status == GSL_CONTINUE && iter < 1000);\n\n printf (\"status = %s\\n\", gsl_strerror (status));\n\n gsl_multiroot_fsolver_free (s);\n gsl_vector_free (x);\n return 0;\n}\n\n\n", "meta": {"hexsha": "0852fadc566bcf9d0887e82c16b7e89783c0ac81", "size": 1968, "ext": "c", "lang": "C", "max_stars_repo_path": "function_solve.c", "max_stars_repo_name": "turtlewangbin/Meanfield", "max_stars_repo_head_hexsha": "7b21457d4cc05560976f8407e839d30a644468cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-18T14:05:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-18T14:05:49.000Z", "max_issues_repo_path": "function_solve.c", "max_issues_repo_name": "turtlewangbin/Meanfield", "max_issues_repo_head_hexsha": "7b21457d4cc05560976f8407e839d30a644468cb", "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": "function_solve.c", "max_forks_repo_name": "turtlewangbin/Meanfield", "max_forks_repo_head_hexsha": "7b21457d4cc05560976f8407e839d30a644468cb", "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": 21.3913043478, "max_line_length": 57, "alphanum_fraction": 0.606199187, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7166500951976846}} {"text": "static const char help[] =\n\"Solves time-dependent nonlinear ice sheet problem in 2D:\\n\"\n\"(*) H_t + div q = m\\n\"\n\"where q = (q^x,q^y) is the nonsliding shallow ice approximation (SIA) flux,\\n\"\n\" q = - Gamma H^{n+2} |grad s|^{n-1} grad s\\n\"\n\"always subject to the constraint\\n\"\n\" H(t,x,y) >= 0.\\n\"\n\"In these equations H(t,x,y) is ice thickness, b(x,y) is bed elevation,\\n\"\n\"s(t,x,y) = H(t,x,y) + b(x,y) is surface elevation, and m(x,y) is the\\n\"\n\"climatic mass balance. Constants are n > 1 and Gamma = 2 A (rho g)^n / (n+2).\\n\"\n\"The domain is square, Omega = [0,L] x [0,L], with periodic boundary conditions.\\n\"\n\"Equation (*) is semi-discretized in space by a Q1 structured-grid FVE method\\n\"\n\"(Bueler, 2016). The resulting method-of-lines ODE in time is in the form\\n\"\n\" F(t,H,H_t) = G(t,H)\\n\"\n\"For this ODE we define three callbacks:\\n\"\n\" FormIFunction() evaluates F(H,H_t) = H_t + div q\\n\"\n\" FormRHSFunction() evaluates G(t,H) = m\\n\"\n\" FormIJacobian() evaluates (shift) dF/dH_t + dF/dH.\\n\"\n\"Options -snes_fd_color works well but is slower than the default Jacobian\\n\"\n\"by a factor of two or so. Requires SNESVI types (i.e.\\n\"\n\"-snes_type vinewton{rsls|ssls}) because of constraint. With current PETSc\\n\"\n\"design, explicit TS types do not work.\\n\\n\";\n\n/* try:\n\n./ice -da_refine 3 # only meaningful at this res and higher\n\n./ice -snes_atol 1.0e-14 # CRITICAL; some lower bound on SNES norm is\n # critical to allowing convergence near steady state\n\n./ice # DEFAULT uses analytical jacobian\n./ice -snes_fd_color\n./ice -snes_type vinewtonrsls # DEFAULT\n./ice -snes_type vinewtonssls # slightly more robust?\n(other -snes_types like newtonls not allowed because don't support bounds)\n\n./ice -ts_type arkimex # DEFAULT\n./ice -ts_type beuler # robust\n./ice -ts_type cn # mis-behaves on long time steps\n./ice -ts_type cn -ts_theta_adapt # good\n./ice -ts_type theta -ts_theta_adapt # good\n./ice -ts_type bdf -ts_bdf_adapt -ts_bdf_order 2|3|4|5|6 # good\n\n# time-stepping control options\n-ts_adapt_type basic # DEFAULT\n-ts_adapt_basic_clip 0.5,1.2 # DEFAULT and recommended;\n doesn't lengthen too much, but allows\n significantly shorter, in response to estimate of\n local truncation error (vs default: 0.1,10.0)\n-ts_max_snes_failures -1 # recommended: do retry solve\n-ts_adapt_scale_solve_failed 0.9 # recommended: try a slightly-easier problem\n-ts_max_reject 50 # recommended?: keep trying if lte is too big\n\n./ice -ice_dtlimits # info on comparison to explicit\n./ice -ts_adapt_monitor # info on adapt\n\n# PC possibilities\n-ksp_type gmres # DEFAULT\n-pc_type ilu # DEFAULT\n-pc_type gamg -pc_gamg_threshold 0.0 -pc_gamg_agg_nsmooths 1 # these are GAMG defaults\n-pc_type gamg -pc_gamg_threshold 0.2 -pc_gamg_agg_nsmooths 1 # a little faster?\n-pc_type lu\n-pc_type asm -sub_pc_type lu\n-pc_type asm -sub_pc_type ilu\n-pc_type mg\n-pc_type mg -pc_mg_levels 4 -mg_levels_ksp_monitor\n\n# shows nontriviality converging ice caps on mountains:\nmpiexec -n 2 ./ice -da_refine 5 -ts_monitor_solution draw -snes_converged_reason -ice_tf 10000.0 -ice_dtinit 100.0 -ts_max_snes_failures -1 -ts_adapt_scale_solve_failed 0.9\n\n# start with short time step and it will find good time scale\n./ice -snes_converged_reason -da_refine 4 -ice_dtinit 0.1\n\n# recovery from convergence failures works! (failure here triggered by n=4):\n./ice -da_refine 3 -ice_n 4 -ts_max_snes_failures -1 -snes_converged_reason\n\nverif with dome=1, halfar=2:\nfor TEST in 1 2; do\n for N in 2 3 4 5 6; do\n mpiexec -n 2 ./ice -ice_monitor 0 -ice_verif $TEST -ice_eps 0.0 -ice_dtinit 50.0 -ice_tf 2000.0 -da_refine $N -ts_type beuler\n done\ndone\n\nactual test B from Bueler et al 2005:\n./ice -ice_verif 2 -ice_eps 0 -ice_dtinit 100 -ice_tf 25000 -ice_L 2200e3 -da_refine $N\n\nrecommended \"new PISM\":\nmpiexec -n N ./ice -da_refine M \\\n -snes_type vinewtonrsls \\\n -ts_type arkimex \\ #(OR -ts_type bdf -ts_bdf_adapt -ts_bdf_order 4)\n -ts_adapt_type basic -ts_adapt_basic_clip 0.5,1.2 \\\n -ts_max_snes_failures -1 -ts_adapt_scale_solve_failed 0.9 \\\n -pc_type gamg\n\nrun to generate final-time result in file ice_192_50000.dat:\nmpiexec -n 4 ./ice -da_refine 6 -pc_type mg -pc_mg_levels 4 -ice_dtlimits -ice_tf 50000 -ice_dtinit 1.0 -ts_max_snes_failures -1 -ts_adapt_scale_solve_failed 0.9 -ice_dump\n*/\n\n#include \n#include \"icecmb.h\"\n\n// context is entirely grid-independent info\ntypedef struct {\n double secpera,// number of seconds in a year\n L, // spatial domain is [0,L] x [0,L]\n tf, // final time; time domain is [0,tf]\n dtinit, // user-requested initial time step\n dtmax, // set TS maximum time step\n g, // acceleration of gravity\n rho_ice,// ice density\n n_ice, // Glen exponent for SIA flux term\n A_ice, // ice softness\n Gamma, // coefficient for SIA flux term\n D0, // representative value of diffusivity (used in regularizing D)\n eps, // regularization parameter for D\n delta, // dimensionless regularization for slope in SIA formulas\n lambda, // amount of upwinding; lambda=0 is none and lambda=1 is \"full\"\n locmaxD,// maximum of diffusivity from last residual evaluation\n dtexplicitsum;// running sum of explicit dt limit\n int verif; // 0 = not verification, 1 = dome, 2 = Halfar (1983)\n PetscBool monitor,// use -ice_monitor\n monitor_dt_limits,// also monitor time step limits for explicit schemes\n dump; // dump state (H,b) at final time\n CMBModel *cmb;// defined in cmbmodel.h\n} AppCtx;\n\n#include \"iceverif.h\"\n\nextern PetscErrorCode SetFromOptionsAppCtx(AppCtx*);\nextern PetscErrorCode IceMonitor(TS, int, double, Vec, void*);\nextern PetscErrorCode ExplicitLimitsMonitor(TS, int, double, Vec, void*);\nextern PetscErrorCode FormBedLocal(DMDALocalInfo*, int, double**, AppCtx*);\nextern PetscErrorCode FormBounds(SNES,Vec,Vec);\nextern PetscErrorCode FormIFunctionLocal(DMDALocalInfo*, double,\n double**, double**, double**, AppCtx*);\nextern PetscErrorCode FormIJacobianLocal(DMDALocalInfo*, double,\n double**, double**, double, Mat, Mat, AppCtx *user);\nextern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, double,\n double**, double**, AppCtx*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n DM da;\n TS ts;\n SNES snes; // no need to destroy (owned by TS)\n TSAdapt adapt;\n Vec H;\n AppCtx user;\n CMBModel cmb;\n DMDALocalInfo info;\n double dx,dy,**aH;\n\n PetscInitialize(&argc,&argv,(char*)0,help);\n\n ierr = SetFromOptionsAppCtx(&user); CHKERRQ(ierr);\n ierr = SetFromOptions_CMBModel(&cmb,user.secpera);\n user.cmb = &cmb;\n\n // this DMDA is the cell-centered grid\n ierr = DMDACreate2d(PETSC_COMM_WORLD,\n DM_BOUNDARY_PERIODIC,DM_BOUNDARY_PERIODIC,\n DMDA_STENCIL_BOX,\n 3,3,PETSC_DECIDE,PETSC_DECIDE,\n 1, 1, // dof=1, stencilwidth=1\n NULL,NULL,&da);\n ierr = DMSetFromOptions(da); CHKERRQ(ierr);\n ierr = DMSetUp(da); CHKERRQ(ierr); // this must be called BEFORE SetUniformCoordinates\n ierr = DMSetApplicationContext(da, &user);CHKERRQ(ierr);\n ierr = DMDASetUniformCoordinates(da, 0.0, user.L, 0.0, user.L, 0.0,1.0); CHKERRQ(ierr);\n\n // initialize the TS and configure its time-axis, including its TSAdapt\n ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);\n ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);\n ierr = TSSetType(ts,TSARKIMEX); CHKERRQ(ierr);\n ierr = TSSetTime(ts,0.0); CHKERRQ(ierr);\n ierr = TSSetMaxTime(ts,user.tf); CHKERRQ(ierr);\n ierr = TSSetTimeStep(ts,user.dtinit); CHKERRQ(ierr);\n ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);\n ierr = TSGetAdapt(ts,&adapt); CHKERRQ(ierr);\n ierr = TSAdaptSetType(adapt,TSADAPTBASIC); CHKERRQ(ierr);\n ierr = TSAdaptSetClip(adapt,0.5,1.2); CHKERRQ(ierr);\n ierr = TSAdaptSetStepLimits(adapt,0.0,user.dtmax); CHKERRQ(ierr);\n if (user.monitor) {\n ierr = TSMonitorSet(ts,IceMonitor,&user,NULL); CHKERRQ(ierr);\n }\n if (user.monitor_dt_limits) {\n ierr = TSMonitorSet(ts,ExplicitLimitsMonitor,&user,NULL); CHKERRQ(ierr);\n }\n\n // set methods to compute parts of ODE system, for the DMDA grid, for TS callback\n ierr = TSSetDM(ts,da); CHKERRQ(ierr);\n ierr = DMDATSSetIFunctionLocal(da,INSERT_VALUES,\n (DMDATSIFunctionLocal)FormIFunctionLocal,&user); CHKERRQ(ierr);\n ierr = DMDATSSetIJacobianLocal(da,\n (DMDATSIJacobianLocal)FormIJacobianLocal,&user); CHKERRQ(ierr);\n ierr = DMDATSSetRHSFunctionLocal(da,INSERT_VALUES,\n (DMDATSRHSFunctionLocal)FormRHSFunctionLocal,&user); CHKERRQ(ierr);\n\n // configure the SNES and DM to solve a NCP/VI at each step\n ierr = TSGetSNES(ts,&snes); CHKERRQ(ierr);\n ierr = SNESSetType(snes,SNESVINEWTONRSLS); CHKERRQ(ierr);\n ierr = SNESVISetComputeVariableBounds(snes,&FormBounds); CHKERRQ(ierr);\n\n // should be done setting up TS\n ierr = TSSetFromOptions(ts);CHKERRQ(ierr);\n\n // report on space-time grid\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n dx = user.L / (double)(info.mx);\n dy = user.L / (double)(info.my);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"solving on domain [0,L] x [0,L] (L=%.3f km) and time interval [0,tf] (tf=%.3f a)\\n\"\n \"grid: %d x %d points, spacing dx=%.3f km x dy=%.3f km, dtinit=%.3f a\\n\",\n user.L/1000.0,user.tf/user.secpera,\n info.mx,info.my,dx/1000.0,dy/1000.0,user.dtinit/user.secpera);\n\n // set up initial condition on fine grid\n ierr = DMCreateGlobalVector(da,&H);CHKERRQ(ierr);\n ierr = PetscObjectSetName((PetscObject)H,\"H\"); CHKERRQ(ierr);\n ierr = DMDAVecGetArray(da,H,&aH); CHKERRQ(ierr);\n if (user.verif == 1) {\n ierr = DomeThicknessLocal(&info,aH,&user); CHKERRQ(ierr);\n } else if (user.verif == 2) {\n double t0;\n ierr = TSGetTime(ts,&t0); CHKERRQ(ierr);\n ierr = HalfarThicknessLocal(&info,t0,aH,&user); CHKERRQ(ierr);\n } else {\n // fill H according to chop-scale-CMB\n ierr = FormBedLocal(&info,0,aH,&user); CHKERRQ(ierr); // H(x,y) <- b(x,y)\n ierr = ChopScaleInitialHLocal_CMBModel(&cmb,&info,aH,aH); CHKERRQ(ierr);\n }\n ierr = DMDAVecRestoreArray(da,H,&aH); CHKERRQ(ierr);\n\n // solve\n ierr = TSSolve(ts,H); CHKERRQ(ierr);\n\n // time-stepping summary if -ice_dtlimits\n if (user.monitor_dt_limits) {\n int count;\n ierr = TSGetStepNumber(ts,&count); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"average dt %.5f a, average dtexplicit %.5f a\\n\",\n (user.tf/user.secpera)/(double)count,\n (user.dtexplicitsum/user.secpera)/(double)count); CHKERRQ(ierr);\n }\n\n // dump state if requested\n if (user.dump) {\n char filename[1024];\n PetscViewer viewer;\n Vec b;\n double **ab;\n ierr = VecDuplicate(H,&b);CHKERRQ(ierr);\n ierr = PetscObjectSetName((PetscObject)b,\"b\"); CHKERRQ(ierr);\n ierr = DMDAVecGetArray(da,b,&ab); CHKERRQ(ierr);\n ierr = FormBedLocal(&info,0,ab,&user); CHKERRQ(ierr);\n ierr = DMDAVecRestoreArray(da,b,&ab); CHKERRQ(ierr);\n ierr = sprintf(filename,\"ice_%d_%d.dat\",info.mx,(int)(user.tf/user.secpera));\n ierr = PetscPrintf(PETSC_COMM_WORLD,\"writing PETSC binary file %s ...\\n\",filename); CHKERRQ(ierr);\n ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_WRITE,&viewer); CHKERRQ(ierr);\n ierr = VecView(b,viewer); CHKERRQ(ierr);\n ierr = VecView(H,viewer); CHKERRQ(ierr);\n ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr);\n VecDestroy(&b);\n }\n\n // compute error in verification case\n if (user.verif > 0) {\n Vec Hexact;\n double infnorm, onenorm;\n ierr = VecDuplicate(H,&Hexact); CHKERRQ(ierr);\n ierr = DMDAVecGetArray(da,Hexact,&aH); CHKERRQ(ierr);\n if (user.verif == 1) {\n ierr = DomeThicknessLocal(&info,aH,&user); CHKERRQ(ierr);\n } else if (user.verif == 2) {\n double tf;\n ierr = TSGetTime(ts,&tf); CHKERRQ(ierr);\n ierr = HalfarThicknessLocal(&info,tf,aH,&user); CHKERRQ(ierr);\n } else {\n SETERRQ(PETSC_COMM_WORLD,3,\"invalid user.verif ... how did I get here?\\n\");\n }\n ierr = DMDAVecRestoreArray(da,Hexact,&aH); CHKERRQ(ierr);\n ierr = VecAXPY(H,-1.0,Hexact); CHKERRQ(ierr); // H <- H + (-1.0) Hexact\n VecDestroy(&Hexact);\n ierr = VecNorm(H,NORM_INFINITY,&infnorm); CHKERRQ(ierr);\n ierr = VecNorm(H,NORM_1,&onenorm); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"errors on verif %d: |H-Hexact|_inf = %.3f, |H-Hexact|_average = %.3f\\n\",\n user.verif,infnorm,onenorm/(double)(info.mx*info.my)); CHKERRQ(ierr);\n }\n\n // clean up\n VecDestroy(&H); TSDestroy(&ts); DMDestroy(&da);\n return PetscFinalize();\n}\n\n\nPetscErrorCode SetFromOptionsAppCtx(AppCtx *user) {\n PetscErrorCode ierr;\n PetscBool set;\n\n user->secpera= 31556926.0; // number of seconds in a year\n user->L = 1800.0e3; // m; note domeL=750.0e3 is radius of verification ice sheet\n user->tf = 100.0 * user->secpera; // default to 100 years\n user->dtinit = 10.0 * user->secpera; // default to 10 year as initial step\n user->dtmax = 1.0e6 * user->secpera; // default to million years; huge\n user->g = 9.81; // m/s^2\n user->rho_ice= 910.0; // kg/m^3\n user->n_ice = 3.0;\n user->A_ice = 3.1689e-24; // 1/(Pa^3 s); EISMINT I value\n user->D0 = 1.0; // m^2 / s\n user->eps = 0.001;\n user->delta = 1.0e-4;\n user->lambda = 0.25;\n user->dtexplicitsum = 0.0;\n user->verif = 0;\n user->monitor = PETSC_TRUE;\n user->monitor_dt_limits = PETSC_FALSE;\n user->dump = PETSC_FALSE;\n user->cmb = NULL;\n\n PetscFunctionBeginUser;\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD,\"ice_\",\"options to ice\",\"\");CHKERRQ(ierr);\n ierr = PetscOptionsReal(\n \"-A\", \"set value of ice softness A in units Pa-3 s-1\",\n \"ice.c\",user->A_ice,&user->A_ice,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\n \"-D0\", \"representative value of diffusivity (used in regularizing D) in units m2 s-1\",\n \"ice.c\",user->D0,&user->D0,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\n \"-delta\", \"dimensionless regularization for slope in SIA formulas\",\n \"ice.c\",user->delta,&user->delta,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\n \"-dt_init\", \"initial time step; input units are years\",\n \"ice.c\",user->dtinit,&user->dtinit,&set);CHKERRQ(ierr);\n if (set) user->dtinit *= user->secpera;\n ierr = PetscOptionsReal(\n \"-dt_max\", \"maximum time step; input units are years\",\n \"ice.c\",user->dtmax,&user->dtmax,&set);CHKERRQ(ierr);\n if (set) user->dtmax *= user->secpera;\n ierr = PetscOptionsBool(\n \"-dump\", \"save final state (H, b)\",\n \"ice.c\",user->dump,&user->dump,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\n \"-eps\", \"dimensionless regularization for diffusivity D\",\n \"ice.c\",user->eps,&user->eps,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\n \"-L\", \"side length of domain in meters\",\n \"ice.c\",user->L,&user->L,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\n \"-lambda\", \"amount of upwinding; lambda=0 is none and lambda=1 is full\",\n \"ice.c\",user->lambda,&user->lambda,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsBool(\n \"-monitor\", \"use the ice monitor which shows ice sheet volume and area\",\n \"ice.c\",user->monitor,&user->monitor,&set);CHKERRQ(ierr);\n if (!set) user->monitor = PETSC_TRUE;\n ierr = PetscOptionsBool(\n \"-monitor_dt_limits\", \"monitor the time-step limits which would apply to an explicit scheme\",\n \"ice.c\",user->monitor_dt_limits,&user->monitor_dt_limits,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\n \"-n\", \"value of Glen exponent n\",\n \"ice.c\",user->n_ice,&user->n_ice,NULL);CHKERRQ(ierr);\n if (user->n_ice <= 1.0) {\n SETERRQ1(PETSC_COMM_WORLD,1,\n \"ERROR: n = %f not allowed ... n > 1 is required\\n\",user->n_ice);\n }\n ierr = PetscOptionsReal(\n \"-rho\", \"ice density in units kg m3\",\n \"ice.c\",user->rho_ice,&user->rho_ice,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\n \"-tf\", \"final time in seconds; input units are years\",\n \"ice.c\",user->tf,&user->tf,&set);CHKERRQ(ierr);\n if (set) user->tf *= user->secpera;\n ierr = PetscOptionsInt(\n \"-verif\",\"1 = dome exact solution; 2 = halfar exact solution\",\n \"ice.c\",user->verif,&(user->verif),&set);CHKERRQ(ierr);\n if ((set) && ((user->verif < 0) || (user->verif > 2))) {\n SETERRQ1(PETSC_COMM_WORLD,2,\n \"ERROR: verif = %d not allowed ... 0 <= verif <= 2 is required\\n\",\n user->verif);\n }\n ierr = PetscOptionsEnd();CHKERRQ(ierr);\n\n // derived constant computed after other ice properties are set\n user->Gamma = 2.0 * PetscPowReal(user->rho_ice*user->g,user->n_ice) \n * user->A_ice / (user->n_ice+2.0);\n\n PetscFunctionReturn(0);\n}\n\n\n// this basic monitor gives current time, volume, area\nPetscErrorCode IceMonitor(TS ts, int step, double time, Vec H, void *ctx) {\n PetscErrorCode ierr;\n AppCtx *user = (AppCtx*)ctx;\n double lvol = 0.0, vol, larea = 0.0, area, darea, **aH;\n int j, k;\n MPI_Comm com;\n DM da;\n DMDALocalInfo info;\n\n PetscFunctionBeginUser;\n ierr = TSGetDM(ts,&da);CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n darea = user->L * user->L / (double)(info.mx * info.my);\n ierr = DMDAVecGetArrayRead(da,H,&aH); CHKERRQ(ierr);\n for (k = info.ys; k < info.ys + info.ym; k++) {\n for (j = info.xs; j < info.xs + info.xm; j++) {\n if (aH[k][j] > 1.0) { // for volume/area its helpful to not count tinys\n larea += darea;\n lvol += aH[k][j];\n }\n }\n }\n ierr = DMDAVecRestoreArrayRead(da,H,&aH); CHKERRQ(ierr);\n lvol *= darea;\n ierr = PetscObjectGetComm((PetscObject)(da),&com); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&lvol,&vol,1,MPI_DOUBLE,MPI_SUM,com); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&larea,&area,1,MPI_DOUBLE,MPI_SUM,com); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"%3d: time %.3f a, volume %.1f 10^3 km^3, area %.1f 10^3 km^2\\n\",\n step,time/user->secpera,vol/1.0e12,area/1.0e9); CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n// this monitor reports on max diffusivity, velocity, explicit time-step limits (for comparison)\nPetscErrorCode ExplicitLimitsMonitor(TS ts, int step, double time, Vec H, void *ctx) {\n PetscErrorCode ierr;\n AppCtx *user = (AppCtx*)ctx;\n double maxD, dd, dtD=PETSC_INFINITY;\n MPI_Comm com;\n DM da;\n DMDALocalInfo info;\n\n PetscFunctionBeginUser;\n if (time <= 0.0) {\n PetscFunctionReturn(0);\n }\n // globalize maxD\n ierr = TSGetDM(ts,&da);CHKERRQ(ierr);\n ierr = PetscObjectGetComm((PetscObject)(da),&com); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&(user->locmaxD),&maxD,1,MPI_DOUBLE,MPI_MAX,com); CHKERRQ(ierr);\n // compute explicit limits\n if (maxD <= 0.0) {\n ierr = PetscPrintf(PETSC_COMM_WORLD,\" [NO -ice_monitor_dt_limits output because maxD is zero]\\n\"); CHKERRQ(ierr);\n } else {\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n dd = PetscMin(user->L / (double)(info.mx), user->L / (double)(info.my));\n dtD = dd * dd / (4.0*maxD);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\" max D_SIA %.3f m2s-1, dtD %.3e a\\n\",\n maxD,dtD/user->secpera); CHKERRQ(ierr);\n user->dtexplicitsum += dtD;\n }\n PetscFunctionReturn(0);\n}\n\nPetscErrorCode FormBedLocal(DMDALocalInfo *info, int stencilwidth, double **ab, AppCtx *user) {\n int j,k,r,s;\n const double dx = user->L / (double)(info->mx),\n dy = user->L / (double)(info->my),\n Z = PETSC_PI / user->L;\n double x, y, b;\n // vaguely-random frequencies and coeffs generated by fiddling; see randbed.py\n const int nc = 4,\n jc[4] = {1, 3, 6, 8},\n kc[4] = {1, 3, 4, 7};\n const double scalec = 750.0,\n C[4][4] = { { 2.00000000, 0.33000000, -0.55020034, 0.54495520},\n { 0.50000000, 0.45014486, 0.60551833, -0.52250644},\n { 0.93812068, 0.32638429, -0.24654812, 0.33887052},\n { 0.17592361, -0.35496741, 0.22694547, -0.05280704} };\n PetscFunctionBeginUser;\n // go through owned portion of grid and compute b(x,y)\n for (k = info->ys-stencilwidth; k < info->ys + info->ym+stencilwidth; k++) {\n y = k * dy;\n for (j = info->xs-stencilwidth; j < info->xs + info->xm+stencilwidth; j++) {\n x = j * dx;\n // b(x,y) is sum of a few sines\n b = 0.0;\n for (r = 0; r < nc; r++) {\n for (s = 0; s < nc; s++) {\n b += C[r][s] * sin(jc[r] * Z * x) * sin(kc[s] * Z * y);\n }\n }\n ab[k][j] = scalec * b;\n }\n }\n PetscFunctionReturn(0);\n}\n\n\n// for call-back: tell SNESVI (variational inequality) that we want\n// 0.0 <= H < +infinity\nPetscErrorCode FormBounds(SNES snes, Vec Xl, Vec Xu) {\n PetscErrorCode ierr;\n PetscFunctionBeginUser;\n ierr = VecSet(Xl,0.0); CHKERRQ(ierr);\n ierr = VecSet(Xu,PETSC_INFINITY); CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n\n// value of gradient at a point\ntypedef struct {\n double x,y;\n} Grad;\n\n\n/* We factor the SIA flux as\n q = - H^{n+2} sigma(|grad s|) grad s\nwhere sigma is the slope-dependent part\n sigma(z) = Gamma z^{n-1}.\nAlso\n D = H^{n+2} sigma(|grad s|)\nso that q = - D grad s. */\nstatic double sigma(Grad gH, Grad gb, const AppCtx *user) {\n const double n = user->n_ice;\n if (n > 1.0) {\n const double sx = gH.x + gb.x,\n sy = gH.y + gb.y,\n slopesqr = sx * sx + sy * sy + user->delta * user->delta;\n return user->Gamma * PetscPowReal(slopesqr,(n-1.0)/2);\n } else {\n return user->Gamma;\n }\n}\n\n/* Regularized derivative of sigma with respect to nodal value H_l:\n d sigma / dl = (d sigma / d gH.x) * (d gH.x / dl) + (d sigma / d gH.y) * (d gH.y / dl),\nbut\n d sigma / d gH.x = Gamma * (n-1) * |gH + gb|^{n-3.0} * (gH.x + gb.x)\n d sigma / d gH.y = Gamma * (n-1) * |gH + gb|^{n-3.0} * (gH.y + gb.y)\nHowever, power n-3.0 can be negative, which generates NaN in areas where the\nsurface gradient gH+gb is zero or tiny, so we add delta^2 to |grad s|^2. */\nstatic double DsigmaDl(Grad gH, Grad gb, Grad dgHdl, const AppCtx *user) {\n const double n = user->n_ice;\n if (n > 1.0) {\n const double sx = gH.x + gb.x,\n sy = gH.y + gb.y,\n slopesqr = sx * sx + sy * sy + user->delta * user->delta,\n tmp = user->Gamma * (n-1) * PetscPowReal(slopesqr,(n-3.0)/2);\n return tmp * sx * dgHdl.x + tmp * sy * dgHdl.y;\n } else {\n return 0.0;\n }\n}\n\n/* Pseudo-velocity from bed slope: W = - sigma * grad b. */\nstatic Grad W(double sigma, Grad gb) {\n Grad W;\n W.x = - sigma * gb.x;\n W.y = - sigma * gb.y;\n return W;\n}\n\n/* Derivative of pseudo-velocity W with respect to nodal value H_l. */\nstatic Grad DWDl(double dsigmadl, Grad gb) {\n Grad dWdl;\n dWdl.x = - dsigmadl * gb.x;\n dWdl.y = - dsigmadl * gb.y;\n return dWdl;\n}\n\n\n/* DCS = diffusivity from the continuation scheme:\n D(eps) = (1-eps) sigma H^{n+2} + eps D_0\nso D(1)=D_0 and D(0)=sigma H^{n+2}. */\nstatic double DCS(double sigma, double H, const AppCtx *user) {\n return (1.0 - user->eps) * sigma * PetscPowReal(PetscAbsReal(H),user->n_ice+2.0)\n + user->eps * user->D0;\n}\n\n\n/* Derivative of diffusivity D = DCS with respect to nodal value H_l. Since\n D = (1-eps) sigma H^{n+2} + eps D0\nit follows that\n d D / dl = (1-eps) [ (d sigma / dl) H^{n+2} + sigma (n+2) H^{n+1} (d H / dl) ]\n = (1-eps) H^{n+1} [ (d sigma / dl) H + sigma (n+2) (d H / dl) ] */\nstatic double DDCSDl(double sigma, double dsigmadl, double H, double dHdl,\n const AppCtx *user) {\n const double Hpow = PetscPowReal(PetscAbsReal(H),user->n_ice+1.0);\n return (1.0 - user->eps) * Hpow * ( dsigmadl * H + sigma * (user->n_ice+2.0) * dHdl );\n}\n\n\n/* Flux component from the non-sliding SIA on a general bed. */\nPetscErrorCode SIAflux(Grad gH, Grad gb, double H, double Hup, PetscBool xdir,\n double *D, double *q, const AppCtx *user) {\n const double mysig = sigma(gH,gb,user),\n myD = DCS(mysig,H,user);\n const Grad myW = W(mysig,gb);\n PetscFunctionBeginUser;\n if (D) {\n *D = myD;\n }\n if (xdir && q) {\n *q = - myD * gH.x + myW.x * PetscPowReal(PetscAbsReal(Hup),user->n_ice+2.0);\n } else {\n *q = - myD * gH.y + myW.y * PetscPowReal(PetscAbsReal(Hup),user->n_ice+2.0);\n }\n PetscFunctionReturn(0);\n}\n\n\nstatic double DSIAfluxDl(Grad gH, Grad gb, Grad dgHdl,\n double H, double dHdl, double Hup, double dHupdl,\n PetscBool xdir, const AppCtx *user) {\n const double Huppow = PetscPowReal(PetscAbsReal(Hup),user->n_ice+1.0),\n dHuppow = (user->n_ice+2.0) * Huppow * dHupdl,\n mysig = sigma(gH,gb,user),\n myD = DCS(mysig,H,user),\n dsigmadl = DsigmaDl(gH,gb,dgHdl,user),\n dDdl = DDCSDl(mysig,dsigmadl,H,dHdl,user);\n const Grad myW = W(mysig,gb),\n dWdl = DWDl(dsigmadl,gb);\n if (xdir)\n return - dDdl * gH.x - myD * dgHdl.x + dWdl.x * Huppow * Hup + myW.x * dHuppow;\n else\n return - dDdl * gH.y - myD * dgHdl.y + dWdl.y * Huppow * Hup + myW.y * dHuppow;\n}\n\n\n// gradients of weights for Q^1 interpolant\nstatic const double gx[4] = {-1.0, 1.0, 1.0, -1.0},\n gy[4] = {-1.0, -1.0, 1.0, 1.0};\n\n\nstatic double fieldatpt(double xi, double eta, double f[4]) {\n // weights for Q^1 interpolant\n double x[4] = { 1.0-xi, xi, xi, 1.0-xi},\n y[4] = {1.0-eta, 1.0-eta, eta, eta};\n return x[0] * y[0] * f[0] + x[1] * y[1] * f[1]\n + x[2] * y[2] * f[2] + x[3] * y[3] * f[3];\n}\n\n\nstatic double fieldatptArray(int u, int v, double xi, double eta, double **f) {\n double ff[4] = {f[v][u], f[v][u+1], f[v+1][u+1], f[v+1][u]};\n return fieldatpt(xi,eta,ff);\n}\n\n\nstatic double dfieldatpt(int l, double xi, double eta) {\n const double x[4] = { 1.0-xi, xi, xi, 1.0-xi},\n y[4] = {1.0-eta, 1.0-eta, eta, eta};\n return x[l] * y[l];\n}\n\n\nstatic Grad gradfatpt(double xi, double eta, double dx, double dy, double f[4]) {\n Grad gradf;\n double x[4] = { 1.0-xi, xi, xi, 1.0-xi},\n y[4] = {1.0-eta, 1.0-eta, eta, eta};\n gradf.x = gx[0] * y[0] * f[0] + gx[1] * y[1] * f[1]\n + gx[2] * y[2] * f[2] + gx[3] * y[3] * f[3];\n gradf.y = x[0] *gy[0] * f[0] + x[1] *gy[1] * f[1]\n + x[2] *gy[2] * f[2] + x[3] *gy[3] * f[3];\n gradf.x /= dx;\n gradf.y /= dy;\n return gradf;\n}\n\n\nstatic Grad gradfatptArray(int u, int v, double xi, double eta, double dx, double dy,\n double **f) {\n double ff[4] = {f[v][u], f[v][u+1], f[v+1][u+1], f[v+1][u]};\n return gradfatpt(xi,eta,dx,dy,ff);\n}\n\n\nstatic Grad dgradfatpt(int l, double xi, double eta, double dx, double dy) {\n Grad dgradfdl;\n const double x[4] = { 1.0-xi, xi, xi, 1.0-xi},\n y[4] = {1.0-eta, 1.0-eta, eta, eta},\n gx[4] = {-1.0, 1.0, 1.0, -1.0},\n gy[4] = {-1.0, -1.0, 1.0, 1.0};\n dgradfdl.x = gx[l] * y[l] / dx;\n dgradfdl.y = x[l] * gy[l] / dy;\n return dgradfdl;\n}\n\n\n// indexing of the 8 quadrature points along the boundary of the control volume in M*\n// point s=0,...,7 is in element (j,k) = (j+je[s],k+ke[s])\nstatic const int je[8] = {0, 0, -1, -1, -1, -1, 0, 0},\n ke[8] = {0, 0, 0, 0, -1, -1, -1, -1},\n ce[8] = {0, 3, 1, 0, 2, 1, 3, 2};\n\n\n// direction of flux at 4 points in each element\nstatic const PetscBool xdire[4] = {PETSC_TRUE, PETSC_FALSE, PETSC_TRUE, PETSC_FALSE};\n\n\n// local (element-wise) coords of quadrature points for M*\nstatic const double locx[4] = { 0.5, 0.75, 0.5, 0.25},\n locy[4] = { 0.25, 0.5, 0.75, 0.5};\n\n\n/* FormIFunctionLocal = IFunction call-back by TS using DMDA info.\n\nEvaluates residual FF on local process patch:\n FF_{j,k} = \\int_{\\partial V_{j,k}} \\mathbf{q} \\cdot \\mathbf{n}\n - m_{j,k} \\Delta x \\Delta y\nwhere V_{j,k} is the control volume centered at (x_j,y_k).\n\nRegarding indexing locations along the boundary of the control volume where\nflux is evaluated, this figure shows four elements and one control volume\ncentered at (x_j,y_k). The boundary of the control volume has 8 points,\nnumbered s=0,...,7:\n -------------------\n | | |\n | ..2..|..1.. |\n | 3: | :0 |\nk |--------- ---------|\n | 4: | :7 |\n | ..5..|..6.. |\n | | |\n -------------------\n j\n\nRegarding flux-component indexing on the element indexed by (j,k) node,\nthe value (aqquad[c])[k][j] for c=0,1,2,3 is an x-component at \"*\" and\na y-component at \"%\"; note (x_j,y_k) is lower-left corner:\n -------------------\n | : |\n | *2 |\n | 3 : 1 |\n |....%.... ....%....|\n | : |\n | *0 |\n | : |\n @-------------------\n(j,k)\n*/\nPetscErrorCode FormIFunctionLocal(DMDALocalInfo *info, double t,\n double **aH, double **aHdot, double **FF,\n AppCtx *user) {\n PetscErrorCode ierr;\n const double dx = user->L / (double)(info->mx),\n dy = user->L / (double)(info->my);\n // coefficients of quadrature evaluations along the boundary of the control volume in M*\n const double coeff[8] = {dy/2, dx/2, dx/2, -dy/2, -dy/2, -dx/2, -dx/2, dy/2};\n const PetscBool upwind = (user->lambda > 0.0);\n const double upmin = (1.0 - user->lambda) * 0.5,\n upmax = (1.0 + user->lambda) * 0.5;\n int c, j, k, s;\n double H, Hup, lxup, lyup, **aqquad[4], **ab, DSIA_ckj, qSIA_ckj;\n Grad gH, gb;\n Vec qquad[4], b;\n\n PetscFunctionBeginUser;\n\n#if 0\n // optionally check admissibility\n for (k = info->ys; k < info->ys + info->ym; k++) {\n for (j = info->xs; j < info->xs + info->xm; j++) {\n if (aH[k][j] < 0.0) {\n SETERRQ3(PETSC_COMM_WORLD,1,\"ERROR: non-admissible H[k][j] = %.3e < 0.0 detected at j,k = %d,%d ... stopping\\n\",aH[k][j],j,k);\n }\n }\n }\n#endif\n\n user->locmaxD = 0.0;\n ierr = DMGetLocalVector(info->da, &b); CHKERRQ(ierr);\n if (user->verif > 0) {\n ierr = VecSet(b,0.0); CHKERRQ(ierr);\n ierr = DMDAVecGetArray(info->da,b,&ab); CHKERRQ(ierr);\n } else {\n ierr = DMDAVecGetArray(info->da,b,&ab); CHKERRQ(ierr);\n ierr = FormBedLocal(info,1,ab,user); CHKERRQ(ierr); // get stencil width\n }\n for (c = 0; c < 4; c++) {\n ierr = DMGetLocalVector(info->da, &(qquad[c])); CHKERRQ(ierr);\n ierr = DMDAVecGetArray(info->da,qquad[c],&(aqquad[c])); CHKERRQ(ierr);\n }\n\n // loop over locally-owned elements, including ghosts, to get fluxes q at\n // c = 0,1,2,3 points in element; note start at (xs-1,ys-1)\n for (k = info->ys-1; k < info->ys + info->ym; k++) {\n for (j = info->xs-1; j < info->xs + info->xm; j++) {\n for (c=0; c<4; c++) {\n H = fieldatptArray(j,k,locx[c],locy[c],aH);\n gH = gradfatptArray(j,k,locx[c],locy[c],dx,dy,aH);\n gb = gradfatptArray(j,k,locx[c],locy[c],dx,dy,ab);\n if (upwind) {\n if (xdire[c] == PETSC_TRUE) {\n lxup = (gb.x <= 0.0) ? upmin : upmax;\n lyup = locy[c];\n } else {\n lxup = locx[c];\n lyup = (gb.y <= 0.0) ? upmin : upmax;\n }\n Hup = fieldatptArray(j,k,lxup,lyup,aH);\n } else\n Hup = H;\n ierr = SIAflux(gH,gb,H,Hup,xdire[c],\n &DSIA_ckj,&qSIA_ckj,user); CHKERRQ(ierr);\n aqquad[c][k][j] = qSIA_ckj;\n if (user->monitor_dt_limits) {\n user->locmaxD = PetscMax(user->locmaxD,DSIA_ckj);\n }\n }\n }\n }\n\n // loop over nodes, not including ghosts, to get function F(t,H,H') from quadature over\n // s = 0,1,...,7 points on boundary of control volume (rectangle) around node\n for (k=info->ys; kys+info->ym; k++) {\n for (j=info->xs; jxs+info->xm; j++) {\n FF[k][j] = aHdot[k][j];\n // now add integral over control volume boundary using two\n // quadrature points on each side\n for (s=0; s<8; s++)\n FF[k][j] += coeff[s] * aqquad[ce[s]][k+ke[s]][j+je[s]] / (dx * dy);\n }\n }\n\n for (c = 0; c < 4; c++) {\n ierr = DMDAVecRestoreArray(info->da,qquad[c],&(aqquad[c])); CHKERRQ(ierr);\n ierr = DMRestoreLocalVector(info->da, &(qquad[c])); CHKERRQ(ierr);\n }\n ierr = DMDAVecRestoreArray(info->da,b,&ab); CHKERRQ(ierr);\n ierr = DMRestoreLocalVector(info->da, &b); CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n\n// use j,k for x,y directions in loops and MatSetValuesStencil\ntypedef struct {\n PetscInt foo,k,j,bar;\n} MyStencil;\n\n\nPetscErrorCode FormIJacobianLocal(DMDALocalInfo *info, double t,\n double **aH, double **aHdot, double shift,\n Mat J, Mat P, AppCtx *user) {\n PetscErrorCode ierr;\n const double dx = user->L / (double)(info->mx),\n dy = user->L / (double)(info->my);\n const double coeff[8] = {dy/2, dx/2, dx/2, -dy/2, -dy/2, -dx/2, -dx/2, dy/2};\n const PetscBool upwind = (user->lambda > 0.0);\n const double upmin = (1.0 - user->lambda) * 0.5,\n upmax = (1.0 + user->lambda) * 0.5;\n int j, k, c, l, s, u, v;\n double H, Hup, **aDqDlquad[16], **ab, val[33], DqSIADl_clkj;\n Grad gH, gb;\n Vec DqDlquad[16], b;\n MyStencil col[33],row;\n\n PetscFunctionBeginUser;\n ierr = MatZeroEntries(P); CHKERRQ(ierr); // because using ADD_VALUES below\n\n ierr = DMGetLocalVector(info->da, &b); CHKERRQ(ierr);\n if (user->verif > 0) {\n ierr = VecSet(b,0.0); CHKERRQ(ierr);\n ierr = DMDAVecGetArray(info->da,b,&ab); CHKERRQ(ierr);\n } else {\n ierr = DMDAVecGetArray(info->da,b,&ab); CHKERRQ(ierr);\n ierr = FormBedLocal(info,1,ab,user); CHKERRQ(ierr); // get stencil width\n }\n for (c = 0; c < 16; c++) {\n ierr = DMGetLocalVector(info->da, &(DqDlquad[c])); CHKERRQ(ierr);\n ierr = DMDAVecGetArray(info->da,DqDlquad[c],&(aDqDlquad[c])); CHKERRQ(ierr);\n }\n\n // loop over locally-owned elements, including ghosts, to get DfluxDl for\n // l=0,1,2,3 at c=0,1,2,3 points in element; note start at (xs-1,ys-1)\n for (k = info->ys-1; k < info->ys + info->ym; k++) {\n for (j = info->xs-1; j < info->xs + info->xm; j++) {\n for (c=0; c<4; c++) {\n double lxup = locx[c], lyup = locy[c];\n H = fieldatptArray(j,k,locx[c],locy[c],aH);\n gH = gradfatptArray(j,k,locx[c],locy[c],dx,dy,aH);\n gb = gradfatptArray(j,k,locx[c],locy[c],dx,dy,ab);\n if (upwind) {\n if (xdire[c] == PETSC_TRUE) {\n lxup = (gb.x <= 0.0) ? upmin : upmax;\n lyup = locy[c];\n } else {\n lxup = locx[c];\n lyup = (gb.y <= 0.0) ? upmin : upmax;\n }\n Hup = fieldatptArray(j,k,lxup,lyup,aH);\n } else {\n Hup = H;\n }\n for (l=0; l<4; l++) {\n Grad dgHdl;\n double dHdl, dHupdl;\n dgHdl = dgradfatpt(l,locx[c],locy[c],dx,dy);\n dHdl = dfieldatpt(l,locx[c],locy[c]);\n dHupdl = (upwind) ? dfieldatpt(l,lxup,lyup) : dHdl;\n DqSIADl_clkj = DSIAfluxDl(gH,gb,dgHdl,H,dHdl,Hup,dHupdl,xdire[c],user);\n aDqDlquad[4*c+l][k][j] = DqSIADl_clkj;\n }\n }\n }\n }\n\n // loop over nodes, not including ghosts, to get derivative of residual\n // with respect to nodal value\n for (k=info->ys; kys+info->ym; k++) {\n row.k = k;\n for (j=info->xs; jxs+info->xm; j++) {\n row.j = j;\n for (s=0; s<8; s++) {\n u = j + je[s];\n v = k + ke[s];\n for (l=0; l<4; l++) {\n const int djfroml[4] = { 0, 1, 1, 0},\n dkfroml[4] = { 0, 0, 1, 1};\n col[4*s+l].j = u + djfroml[l];\n col[4*s+l].k = v + dkfroml[l];\n val[4*s+l] = coeff[s] * aDqDlquad[4*ce[s]+l][v][u] / (dx * dy);\n }\n }\n col[32].j = j;\n col[32].k = k;\n val[32] = shift;\n ierr = MatSetValuesStencil(P,1,(MatStencil*)&row,\n 33,(MatStencil*)col,val,ADD_VALUES);CHKERRQ(ierr);\n }\n }\n\n for (c = 0; c < 16; c++) {\n ierr = DMDAVecRestoreArray(info->da,DqDlquad[c],&(aDqDlquad[c])); CHKERRQ(ierr);\n ierr = DMRestoreLocalVector(info->da, &(DqDlquad[c])); CHKERRQ(ierr);\n }\n ierr = DMDAVecRestoreArray(info->da,b,&ab); CHKERRQ(ierr);\n ierr = DMRestoreLocalVector(info->da, &b); CHKERRQ(ierr);\n\n ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n if (J != P) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n }\n //ierr = MatView(J,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n\nPetscErrorCode FormRHSFunctionLocal(DMDALocalInfo *info, double t, double **aH,\n double **GG, AppCtx *user) {\n PetscErrorCode ierr;\n const double dx = user->L / (double)(info->mx),\n dy = user->L / (double)(info->my);\n int j, k;\n Vec b;\n double **ab, y, x, m;\n\n PetscFunctionBeginUser;\n ierr = DMGetLocalVector(info->da, &b); CHKERRQ(ierr);\n ierr = DMDAVecGetArray(info->da,b,&ab); CHKERRQ(ierr);\n ierr = FormBedLocal(info,0,ab,user); CHKERRQ(ierr); // stencil width NOT needed\n for (k=info->ys; kys+info->ym; k++) {\n y = k * dy;\n for (j=info->xs; jxs+info->xm; j++) {\n x = j * dx;\n if (user->verif == 1) {\n m = DomeCMB(x,y,user);\n } else if (user->verif == 2) {\n m = 0.0;\n } else {\n m = M_CMBModel(user->cmb,ab[k][j] + aH[k][j]); // s = b + H is surface elevation\n }\n GG[k][j] = m;\n }\n }\n ierr = DMDAVecRestoreArray(info->da,b,&ab); CHKERRQ(ierr);\n ierr = DMRestoreLocalVector(info->da, &b); CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n", "meta": {"hexsha": "1805ca468e5b71837d6f13431b9e4d2620130ca1", "size": 39736, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch12/icet/icet.c", "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/ch12/icet/icet.c", "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/ch12/icet/icet.c", "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7131147541, "max_line_length": 172, "alphanum_fraction": 0.5736611637, "num_tokens": 12897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7159711634220625}} {"text": "/* roots/steffenson.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Reid Priedhorsky, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* steffenson.c -- steffenson root finding algorithm \n\n This is Newton's method with an Aitken \"delta-squared\"\n acceleration of the iterates. This can improve the convergence on\n multiple roots where the ordinary Newton algorithm is slow.\n\n x[i+1] = x[i] - f(x[i]) / f'(x[i])\n\n x_accelerated[i] = x[i] - (x[i+1] - x[i])**2 / (x[i+2] - 2*x[i+1] + x[i])\n\n We can only use the accelerated estimate after three iterations,\n and use the unaccelerated value until then.\n\n */\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"roots.h\"\n\ntypedef struct\n {\n double f, df;\n double x;\n double x_1;\n double x_2;\n int count;\n }\nsteffenson_state_t;\n\nstatic int steffenson_init (void * vstate, gsl_function_fdf * fdf, double * root);\nstatic int steffenson_iterate (void * vstate, gsl_function_fdf * fdf, double * root);\n\nstatic int\nsteffenson_init (void * vstate, gsl_function_fdf * fdf, double * root)\n{\n steffenson_state_t * state = (steffenson_state_t *) vstate;\n\n const double x = *root ;\n\n state->f = GSL_FN_FDF_EVAL_F (fdf, x);\n state->df = GSL_FN_FDF_EVAL_DF (fdf, x) ;\n\n state->x = x;\n state->x_1 = 0.0;\n state->x_2 = 0.0;\n\n state->count = 1;\n\n return GSL_SUCCESS;\n\n}\n\nstatic int\nsteffenson_iterate (void * vstate, gsl_function_fdf * fdf, double * root)\n{\n steffenson_state_t * state = (steffenson_state_t *) vstate;\n \n double x_new, f_new, df_new;\n\n double x_1 = state->x_1 ;\n double x = state->x ;\n\n if (state->df == 0.0)\n {\n GSL_ERROR(\"derivative is zero\", GSL_EZERODIV);\n }\n\n x_new = x - (state->f / state->df);\n \n GSL_FN_FDF_EVAL_F_DF(fdf, x_new, &f_new, &df_new);\n\n state->x_2 = x_1 ;\n state->x_1 = x ;\n state->x = x_new;\n\n state->f = f_new ;\n state->df = df_new ;\n\n if (!finite (f_new))\n {\n GSL_ERROR (\"function value is not finite\", GSL_EBADFUNC);\n }\n\n if (state->count < 3)\n {\n *root = x_new ;\n state->count++ ;\n }\n else \n {\n double u = (x - x_1) ;\n double v = (x_new - 2 * x + x_1);\n\n if (v == 0)\n *root = x_new; /* avoid division by zero */\n else\n *root = x_1 - u * u / v ; /* accelerated value */\n }\n\n if (!finite (df_new))\n {\n GSL_ERROR (\"derivative value is not finite\", GSL_EBADFUNC);\n }\n \n return GSL_SUCCESS;\n}\n\n\nstatic const gsl_root_fdfsolver_type steffenson_type =\n{\"steffenson\", /* name */\n sizeof (steffenson_state_t),\n &steffenson_init,\n &steffenson_iterate};\n\nconst gsl_root_fdfsolver_type * gsl_root_fdfsolver_steffenson = &steffenson_type;\n", "meta": {"hexsha": "e4169f6f28d2d7b0c6c44842b023361e475438b1", "size": 3530, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/roots/steffenson.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/roots/steffenson.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/roots/steffenson.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 24.3448275862, "max_line_length": 85, "alphanum_fraction": 0.6532577904, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.8104789109591831, "lm_q1q2_score": 0.7151891812160065}} {"text": "#include \n#include \n\nint\nmain (void)\n{\n double c = GSL_CONST_MKS_SPEED_OF_LIGHT;\n double au = GSL_CONST_MKS_ASTRONOMICAL_UNIT;\n double min = GSL_CONST_MKS_MINUTE;\n\n double r_earth = 1.00 * au;\n double r_mars = 1.52 * au;\n\n double tmin, tmax;\n\n tmin = (r_mars - r_earth)/c;\n tmax = (r_mars + r_earth)/c;\n\n printf(\"light travel time from Earth to Mars:\\n\");\n printf(\"minimum = %.1f minutes\\n\", tmin/min);\n printf(\"maximum = %.1f minutes\\n\", tmax/min);\n}\n\n", "meta": {"hexsha": "5c302e9662456efa3df2dddb6959a5eb6257d431", "size": 497, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/const/demo.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/const/demo.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/const/demo.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 20.7083333333, "max_line_length": 52, "alphanum_fraction": 0.6720321932, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7145590044989133}} {"text": "#include \n#include \n#include \n#include \n#include \n\ndouble f1(double x, void *params) {\n (void) (params); /* avoid unused parameter warning */\n return pow(x, 2);\n}\n\ndouble fi1(double x) {\n return pow(x, 3) / 3;\n}\n\ndouble f2(double x, void *params) {\n (void) (params); /* avoid unused parameter warning */\n if (0 == x) {\n return 0;\n }\n return 1 / sqrt(x);\n}\n\ndouble fi2(double x) {\n return 2 * sqrt(x);\n}\n\ndouble pi(double (*fi)(double), double x1, double x2) {\n return fi(x2) - fi(x1);\n}\n\ndouble e(double p1, double p2) {\n return fabs(p1 - p2);\n}\n\nint main(int argc, char *argv[]) {\n double a, b, pg1, e1, pi1, pg2, e2, pi2;\n if (argc < 2) {\n errno = EINVAL;\n perror(\"\");\n return errno;\n }\n a = strtod(argv[1], NULL);\n b = strtod(argv[2], NULL);\n if (0 != errno) {\n perror(\"\");\n return errno;\n }\n gsl_integration_workspace *w1\n = gsl_integration_workspace_alloc(1000);\n gsl_function F1;\n F1.function = &f1;\n gsl_integration_qags(&F1, a, b, 0, 1e-7, 1000,\n w1, &pg1, &e1);\n pi1 = pi(fi1, a, b);\n gsl_integration_workspace *w2\n = gsl_integration_workspace_alloc(1000);\n gsl_function F2;\n F2.function = &f2;\n gsl_integration_qags(&F2, a, b, 0, 1e-7, 1000,\n w2, &pg2, &e2);\n pi2 = pi(fi2, a, b);\n printf(\"%f\\t%f\\n\", pg1, pg2);\n printf(\"%f\\t%f\\n\", pi1, pi2);\n printf(\"%e\\t%e\\n\", e(pg1, pi1), e(pg2, pi2));\n printf(\"%zu\\t%zu\\n\", w1->size, w2->size);\n gsl_integration_workspace_free(w1);\n gsl_integration_workspace_free(w2);\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "34b658de8ad7a7103fa47acc2e6d8d3bdcbeed08", "size": 1714, "ext": "c", "lang": "C", "max_stars_repo_path": "lab4/zad4.c", "max_stars_repo_name": "mistyfiky/agh-mownit", "max_stars_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab4/zad4.c", "max_issues_repo_name": "mistyfiky/agh-mownit", "max_issues_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "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": "lab4/zad4.c", "max_forks_repo_name": "mistyfiky/agh-mownit", "max_forks_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1408450704, "max_line_length": 57, "alphanum_fraction": 0.557176196, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7141053460338502}} {"text": "#ifndef SIMPROP_UTILS_GSL_H\n#define SIMPROP_UTILS_GSL_H\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace simprop {\nnamespace utils {\n\n// Axis\nstd::vector LinAxis(const double &min, const double &max, const size_t &size);\n\nstd::vector LogAxis(const double &min, const double &max, const size_t &size);\n\ninline bool isInside(double x, const std::vector &X) {\n return (x >= X.front() && x <= X.back());\n};\n\ndouble interpolate(double x, const std::vector &X, const std::vector &Y);\n\ndouble cspline(double x, const std::vector &X, const std::vector &Y);\n\ndouble interpolateEquidistant(double x, double lo, double hi, const std::vector &Y);\n\ndouble interpolate2d(double x, double y, const std::vector &X, const std::vector &Y,\n const std::vector &Z);\n\ntemplate \nT deriv(std::function f, T x, double rel_error = 1e-4) {\n double result;\n double abs_error = 0.0; // disabled\n gsl_function F;\n\n F.function = [](double x, void *vf) -> double {\n auto &func = *static_cast *>(vf);\n return func(x);\n };\n F.params = &f;\n\n gsl_deriv_central(&F, static_cast(x), rel_error, &result, &abs_error);\n\n return T(result);\n}\n\ntemplate \nT deriv5pt(std::function f, T x, T h) {\n auto result = -f(x + 2 * h) + 8 * f(x + h) - 8 * f(x - h) + f(x - 2 * h);\n return T(result) / 12 / h;\n}\n\ntemplate \nT QAGIntegration(std::function f, T start, T stop, int LIMIT, double rel_error = 1e-4) {\n double a = static_cast(start);\n double b = static_cast(stop);\n double abs_error = 0.0; // disabled\n int key = GSL_INTEG_GAUSS31;\n double result;\n double error;\n\n gsl_function F;\n F.function = [](double x, void *vf) -> double {\n auto &func = *static_cast *>(vf);\n return func(x);\n };\n F.params = &f;\n\n gsl_integration_workspace *workspace_ptr = gsl_integration_workspace_alloc(LIMIT);\n gsl_integration_qag(&F, a, b, abs_error, rel_error, LIMIT, key, workspace_ptr, &result, &error);\n gsl_integration_workspace_free(workspace_ptr);\n\n return T(result);\n}\n\ntemplate \nT QAGSIntegration(std::function f, T start, T stop, int LIMIT, double rel_error = 1e-4) {\n double a = static_cast(start);\n double b = static_cast(stop);\n double abs_error = 0.0; // disabled\n double result;\n double error;\n\n gsl_function F;\n F.function = [](double x, void *vf) -> double {\n auto &func = *static_cast *>(vf);\n return func(x);\n };\n F.params = &f;\n\n gsl_integration_workspace *workspace_ptr = gsl_integration_workspace_alloc(LIMIT);\n gsl_integration_qags(&F, a, b, abs_error, rel_error, LIMIT, workspace_ptr, &result, &error);\n gsl_integration_workspace_free(workspace_ptr);\n\n return T(result);\n}\n\ntemplate \nT simpsonIntegration(std::function f, T start, T stop, int N = 100) {\n const T a = start;\n const T b = stop;\n\n const T h = (b - a) / N;\n const T XI0 = f(a) + f(b);\n\n T XI1 = 0, XI2 = 0;\n\n for (int i = 1; i < N; ++i) {\n const T X = a + i * h;\n if (i % 2 == 0)\n XI2 = XI2 + f(X);\n else\n XI1 = XI1 + f(X);\n }\n\n return h * (XI0 + 2 * XI2 + 4 * XI1) / 3.0;\n}\n\ntemplate \nT rootFinder(std::function f, T xLower, T xUpper, int maxIter, double relError = 1e-4) {\n int status;\n int iter = 0;\n const gsl_root_fsolver_type *solverType;\n gsl_root_fsolver *solver;\n\n T r = 0;\n\n gsl_function F;\n F.function = [](double x, void *vf) -> double {\n auto &func = *static_cast *>(vf);\n return func(x);\n };\n F.params = &f;\n\n solverType = gsl_root_fsolver_brent;\n solver = gsl_root_fsolver_alloc(solverType);\n gsl_root_fsolver_set(solver, &F, xLower, xUpper);\n\n do {\n iter++;\n status = gsl_root_fsolver_iterate(solver);\n r = (T)gsl_root_fsolver_root(solver);\n xLower = gsl_root_fsolver_x_lower(solver);\n xUpper = gsl_root_fsolver_x_upper(solver);\n status = gsl_root_test_interval(xLower, xUpper, 0, relError);\n } while (status == GSL_CONTINUE && iter < maxIter);\n\n gsl_root_fsolver_free(solver);\n\n return r;\n}\n\ntemplate \nT rk4fixed(std::function dydx, T yStart, T xStart, T xEnd, T h) {\n size_t steps = (size_t)((xEnd - xStart) / h);\n T x = xStart;\n T y = yStart;\n while (steps--) {\n auto k1 = h * dydx(x, y);\n auto k2 = h * dydx(x + 0.5 * h, y + 0.5 * k1);\n auto k3 = h * dydx(x + 0.5 * h, y + 0.5 * k2);\n auto k4 = h * dydx(x + h, y + k3);\n y += (k1 + 2. * k2 + 2. * k3 + k4) / 6.;\n x += h;\n }\n return y;\n}\n\ntemplate \nT odeiv(std::function dydx, T yStart, T xStart, T xEnd, T rel_error = 1e-4) {\n const size_t NEQS = 1;\n double abs_error = 0.0; // disabled\n\n const gsl_odeiv2_step_type *stepType = gsl_odeiv2_step_rkf45;\n gsl_odeiv2_step *s = gsl_odeiv2_step_alloc(stepType, NEQS);\n gsl_odeiv2_control *c = gsl_odeiv2_control_y_new(abs_error, static_cast(rel_error));\n gsl_odeiv2_evolve *e = gsl_odeiv2_evolve_alloc(NEQS);\n\n double y[1] = {yStart};\n\n auto func = [](double t, const double *y, double *f, void *params) -> int {\n auto dydx = *static_cast *>(params);\n f[0] = dydx(t, y[0]);\n return GSL_SUCCESS;\n };\n\n gsl_odeiv2_system sys = {func, nullptr, NEQS, &dydx};\n\n double t = xStart, t1 = xEnd;\n double h = 1e-5 * (xEnd - xStart);\n\n while (t < t1) {\n int status = gsl_odeiv2_evolve_apply(e, c, s, &sys, &t, t1, &h, y);\n if (status != GSL_SUCCESS) break;\n }\n\n gsl_odeiv2_evolve_free(e);\n gsl_odeiv2_control_free(c);\n gsl_odeiv2_step_free(s);\n return y[0];\n}\n\n} // namespace utils\n} // namespace simprop\n\n#endif", "meta": {"hexsha": "9f6f58a6cd823f3169103a860e87eb30d725f31b", "size": 6040, "ext": "h", "lang": "C", "max_stars_repo_path": "include/simprop/utils/numeric.h", "max_stars_repo_name": "carmeloevoli/SimProp-beta", "max_stars_repo_head_hexsha": "6d3fce16b0d288abcd36b439ef181b50e96b1ee6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/simprop/utils/numeric.h", "max_issues_repo_name": "carmeloevoli/SimProp-beta", "max_issues_repo_head_hexsha": "6d3fce16b0d288abcd36b439ef181b50e96b1ee6", "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/simprop/utils/numeric.h", "max_forks_repo_name": "carmeloevoli/SimProp-beta", "max_forks_repo_head_hexsha": "6d3fce16b0d288abcd36b439ef181b50e96b1ee6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0930232558, "max_line_length": 100, "alphanum_fraction": 0.6518211921, "num_tokens": 1939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7140659753411585}} {"text": "\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n/* Gaussian function */\ndouble tgauss(double x,double sigma)\n{\n double y,z,a=2.506628273;\n z = x / sigma;\n y = exp((double)-z*z*0.5)/(sigma * a);\n return y;\n}\n\n\n\n/* create a Gaussian kernel for convolution */\ngsl_vector *CGaussKernel(double sigma)\n{\n int i,dim,n;\n double x,u,step;\n gsl_vector *kernel;\n\n /* no temporal smoothing */\n if (sigma < 0.001) return NULL;\n\n dim = 4.0 * sigma + 1;\n n = 2*dim+1;\n step = 1;\n\n kernel = gsl_vector_alloc(n);\n \n x = -(float)dim;\n for (i=0; isize/2;\n int i,j,k;\n gsl_matrix_set_zero(S);\n for (i=0; isize1; i++) {\n double sum = 0;\n for (j=0; jsize2; j++) {\n k = i-j+dim;\n if (k < 0 || k >= kernel->size) continue;\n double x = gsl_vector_get(kernel,k);\n sum += x;\n gsl_matrix_set(S,i,j,x);\n }\n /* normalize */\n for (j=0; jsize2; j++) {\n double x = gsl_matrix_get(S,i,j);\n gsl_matrix_set(S,i,j,x/sum);\n }\n }\n}\n\n\nvoid VectorConvolve(const double *src,gsl_vector *dst,gsl_vector *kernel)\n{\n int i,j,k,len,n,dim;\n double sum;\n\n dim = kernel->size/2;\n len = dst->size;\n n = len - dim;\n\n for (i=dim; idata[k];\n k++;\n }\n dst->data[i] = sum;\n }\n\n\n /* Randbehandlung */\n for (i=0; idata[i] = src[i];\n }\n for (i=n; idata[i] = src[i];\n }\n}\n", "meta": {"hexsha": "fe39a2b51ca32b065c3de6f4450be0f804e4f2dd", "size": 1772, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_precoloring/gauss.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_precoloring/gauss.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_precoloring/gauss.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 17.898989899, "max_line_length": 73, "alphanum_fraction": 0.5502257336, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.7140208616095751}} {"text": "#ifndef GSLMATRIX_H\r\n#define GSLMATRIX_H\r\n\r\n#include //Science Library header file\r\n#include \r\n#include \"Matrix.h\"\r\n\r\ntemplate\r\nclass GSLMatrix : public Matrix\r\n{\r\nprivate:\r\n\tgsl_matrix *_matrix; //Pointer to the gsl_matrix struct\r\n\tvoid setMatrix(gsl_matrix* newMatrix);\r\n\r\npublic:\r\n\tGSLMatrix(int nRow, int nCol);\r\n\t~GSLMatrix();\r\n\r\n\tvoid resize(int nRow, int nCol); //If the matrix has elements in it should it keep those elements or is it ok if they are lost?\r\n\t\r\n\tT getElement(int i, int j) const;\r\n\tvoid setElement(int i, int j, T value);\r\n\tgsl_matrix* getMatrix() const;\r\n\t\r\n\tint getSize() const;\r\n\tvoid setZero();\r\n\tvoid invert();\r\n\r\n\tMatrix* operator*(const Matrix* RHS); \r\n\tMatrix* operator+(const Matrix* RHS); \r\n\tMatrix* operator-(const Matrix* RHS);\r\n\tvoid operator=(const GSLMatrix* RHS);\r\n\r\n};\r\n\r\n\r\ntemplate\r\nGSLMatrix::GSLMatrix(int nRow, int nCol)\r\n{\r\n\t_matrix = gsl_matrix_alloc(nRow, nCol);\r\n}\r\n\r\n\r\ntemplate\r\nGSLMatrix::~GSLMatrix()\r\n{\r\n\tif(_matrix != NULL)\r\n\t\tgsl_matrix_free(_matrix);\r\n}\r\n\r\n\r\ntemplate\r\nvoid GSLMatrix::setMatrix(gsl_matrix* newMatrix)\r\n{\r\n\t//Free the old matrix, if there is one\r\n\tif(_matrix != NULL)\r\n\t\tgsl_matrix_free(_matrix);\r\n\r\n\t_matrix = newMatrix;\r\n}\r\n\r\n\r\ntemplate\r\nvoid GSLMatrix::resize(int nRow, int nCol)\r\n{\r\n\tif(_matrix != NULL)\r\n\t\tgsl_matrix_free(_matrix);\r\n\r\n\t_matrix = NULL;\r\n\r\n\t_matrix = gsl_matrix_alloc(nRow, nCol);\r\n}\r\n\r\n\r\ntemplate\r\nT GSLMatrix::getElement(int i, int j) const\r\n{\r\n\treturn gsl_matrix_get(_matrix, i, j);\r\n}\r\n\r\n\r\ntemplate\r\nvoid GSLMatrix::setElement(int i, int j, T value)\r\n{\r\n\tgsl_matrix_set(_matrix, i, j, value);\r\n}\r\n\r\n\r\ntemplate\r\nvoid GSLMatrix::invert()\r\n{\r\n\tint sigNum;\r\n\t\r\n\t//gsl_matrix for the output\r\n\tgsl_matrix* outputMatrix = gsl_matrix_alloc(_matrix->size1, _matrix->size1 );\r\n\r\n\t//Allocate permutation matrix\r\n\tgsl_permutation* permutationM = gsl_permutation_alloc(_matrix->size1);\r\n\r\n\t//get the LU decomposition of the matrix\r\n\tgsl_linalg_LU_decomp((gsl_matrix*) _matrix, permutationM, &sigNum);\r\n\r\n\t//invert the matrix\r\n\tgsl_linalg_LU_invert(_matrix, permutationM, outputMatrix);\r\n\r\n\tthis->setMatrix(outputMatrix);\r\n\t\r\n\tgsl_permutation_free(permutationM);\r\n}\r\n\r\n\r\n\r\ntemplate\r\ngsl_matrix* GSLMatrix::getMatrix() const\r\n{\r\n\treturn _matrix;\r\n}\r\n\r\n\r\ntemplate\r\nint GSLMatrix::getSize() const\r\n{\r\n\treturn _matrix->size1;\r\n}\r\n\r\ntemplate\r\nvoid GSLMatrix::setZero()\r\n{\r\n\tgsl_matrix_set_zero (_matrix);\r\n}\r\n\r\n\r\ntemplate\r\nMatrix* GSLMatrix::operator*(const Matrix* RHS)\r\n{\r\n //Check if its the same size\r\n if(_matrix->size1 != RHS->getSize() || _matrix->size1 != _matrix->size1)\r\n return NULL;\r\n\r\n //Check if its the same type (GSL Matrix)\r\n if(dynamic_cast*> (RHS) == NULL)\r\n throw Error (InvalidParam, \"GSLMatrix::operator*\",\r\n\t\t \"RHS is not a GSLMatrix\");\r\n\r\n //Create the new result matrix\r\n GSLMatrix *result = new GSLMatrix(_matrix->size1, _matrix->size1);\r\n result->setZero();\r\n\r\n //For each row\r\n for(int row = 0; row < _matrix->size1; row++)\r\n {\r\n //for each element in that row\r\n for(int element = 0; element < _matrix->size2; element++)\r\n {\r\n //calculate the value for the current element\r\n for(int i = 0; i < _matrix->size1; i++)\r\n {\r\n\tresult->setElement(row, element, (result->getElement(row, element) ) + this->getElement(row, i) * RHS->getElement(i,element));\r\n }\r\n }\r\n }\r\n \r\n return result;\r\n}\r\n\r\n\r\ntemplate\r\nMatrix* GSLMatrix::operator+(const Matrix* RHS)\r\n{\r\n //Check if its the same size\r\n if(_matrix->size1 != RHS->getSize() || _matrix->size1 != _matrix->size1)\r\n return NULL;\r\n\r\n //Check if its the same type (GSL Matrix)\r\n if(dynamic_cast*> (RHS) == NULL)\r\n throw Error (InvalidParam, \"GSLMatrix::operator*\",\r\n\t\t \"RHS is not a GSLMatrix\");\r\n\r\n\tGSLMatrix *result = new GSLMatrix(_matrix->size1, _matrix->size1); //Create the new result matrix\r\n\tresult->setZero();\r\n\r\n\t//For each row\r\n\tfor(int row = 0; row < _matrix->size1; row++)\r\n\t{\r\n\t\t//for each element in that row\r\n\t\tfor(int element = 0; element < _matrix->size1; element++)\r\n\t\t{\r\n\t\t\tresult->setElement(row, element, this->getElement(row, element) + RHS->getElement(row, element) );\r\n\t\t}\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\n\r\ntemplate\r\nMatrix* GSLMatrix::operator-(const Matrix* RHS)\r\n{\r\n\tif(_matrix->size1 != RHS->getSize() || _matrix->size1 != _matrix->size1) //Check if its the same size\r\n\t\t\treturn NULL;\r\n\r\n //Check if its the same type (GSL Matrix)\r\n if(dynamic_cast*> (RHS) == NULL)\r\n throw Error (InvalidParam, \"GSLMatrix::operator*\",\r\n\t\t \"RHS is not a GSLMatrix\");\r\n\r\n\tGSLMatrix *result = new GSLMatrix(RHS->getSize(), RHS->getSize()); //Create the new result matrix\r\n\tresult->setZero();\r\n\r\n\t//For each row\r\n\tfor(int row = 0; row < _matrix->size1; row++)\r\n\t{\r\n\t\t//for each element in that row\r\n\t\tfor(int element = 0; element < _matrix->size1; element++)\r\n\t\t{\r\n\t\t\tresult->setElement(row, element, this->getElement(row, element) - RHS->getElement(row, element) );\r\n\t\t}\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\n\r\ntemplate\r\nvoid GSLMatrix::operator=(const GSLMatrix* RHS)\r\n{\r\n\tif(_matrix->size1 != RHS->getSize() )\r\n\t{\r\n\t\tgsl_matrix_free(_matrix);\r\n\t\tgsl_matrix_alloc(RHS->getSize(), RHS->getSize());\r\n\t}\r\n\r\n\tgsl_matrix_memcpy(_matrix, RHS->getMatrix());\r\n}\r\n\r\n\r\n#endif\r\n", "meta": {"hexsha": "81d52449fa432881868ed385d6bf28eca0eacf6b", "size": 5570, "ext": "h", "lang": "C", "max_stars_repo_path": "More/MEAL/MEAL/GSLMatrix.h", "max_stars_repo_name": "xuanyuanstar/psrchive_CDFT", "max_stars_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_stars_repo_licenses": ["AFL-2.1"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "More/MEAL/MEAL/GSLMatrix.h", "max_issues_repo_name": "xuanyuanstar/psrchive_CDFT", "max_issues_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_issues_repo_licenses": ["AFL-2.1"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "More/MEAL/MEAL/GSLMatrix.h", "max_forks_repo_name": "xuanyuanstar/psrchive_CDFT", "max_forks_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_forks_repo_licenses": ["AFL-2.1"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T20:08:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T20:08:14.000Z", "avg_line_length": 23.4033613445, "max_line_length": 129, "alphanum_fraction": 0.6588868941, "num_tokens": 1498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7137738057498013}} {"text": "// cosmo.h\n// written by Suman Bhattacharya (https://github.com/bsuman79), modified by Samuel Flender\n// defines the cosmology and allows calculations of various cosmological params\n\n\n#ifndef cosmo_Header_included\n#define cosmo_Header_included\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n//double angdiam_func(double x, void * p);\n\n\nusing namespace std;\n\nclass cosmo {\n\t\nprotected:\n\tfloat H0, Omega_M, rho_crit, a, Omega_k, Omega_L, wt;\n\tfloat PI, m_sun, G, mpc, gnewt;\n\t\npublic:\n\t\n\tcosmo(float inp1, float inp2, float inp4, float inp5)\n\t{\n\t\t// cosmological params at z =0\n\t\tH0 = inp1;\n\t\tOmega_M = inp2;\n\t\tOmega_k = inp4;\n\t\tOmega_L = 1.0- Omega_M- Omega_k;\n\t\twt= inp5;\n\t\tPI = 4.*atan(1.);\n\t\tm_sun = 1.98892e30;\n\t\tG = 6.67e-11/1.0e9; // in km^3 kg^-1 s^-2\n\t\tmpc = 3.0857e19; // in km\n\t\tgnewt = G*m_sun/mpc; //for cosm params (in km^2 Mpc msun^-1 s^-2)\n\t}\n\t\n\tfloat get_H0() {\n\t\treturn H0;\n\t}\n\t\n\tfloat get_hubble70() {\n\t\treturn H0/70.0;\n\t}\n\t\n\tfloat scale_fact(float redshift) {\n\t\ta = 1.0/(1.0+redshift);\n\t\treturn a;\n\t}\n\t\n\tfloat hubblez(float redshift) {\n\t\tscale_fact(redshift);\n\t\treturn H0 * Efact(redshift);\n\t}\n\t\n\tfloat calc_rho_crit(float redshift) {\n\t\tfloat Hz = hubblez(redshift);\n\t\trho_crit = pow(Hz,2)*3./(8.*PI*gnewt);\n\t\treturn rho_crit;\n\t}\n\t\n\tfloat Omega_Mz(float redshift) {\n\t\tscale_fact(redshift);\n\t\tfloat Hz = hubblez(redshift);\n\t\treturn (Omega_M/pow(a,3))*pow(H0/Hz,2);\n\t}\n\t\n\tfloat Delta_vir(float redshift) {\n\t\tfloat x;\n\t\tx = Omega_Mz(redshift) - 1.0;\n\t\treturn (18*pow(PI,2)) + (82*x) - (39*pow(x,2));\n\t}\n\t\n\tfloat Efact(float redshift) {\n\t\tscale_fact(redshift);\n\t\treturn sqrt(Omega_M/pow(a,3) + Omega_L/pow(a, 3*wt+3) + (1.0-Omega_M-Omega_L)/pow(a,2));\n\t}\n\t\n\tfloat ang_diam(float redshift) {\n\t\t// note rcutoff is in units of Rvir\n\t\tint dummy;\n\t\tfloat result;\n\t\tdouble x[1000], y[1000];\n\t\tfloat speed_of_light = 2.9979e5; //km/s\n\t\tdouble units = scale_fact(redshift)*speed_of_light/H0;\n\n\t\t\n\t\tfor(dummy=0;dummy<1000;dummy++){\n\t\t\tx[dummy]= 0.0+ redshift/999*dummy;\n\t\t\ty[dummy] = 1.0/(sqrt( Omega_M*pow(1+x[dummy],3) + Omega_L*pow(1+x[dummy], 3*wt+3) + (1.0-Omega_M-Omega_L)*pow(1+x[dummy],2)));\n\t\t}\n\t\tif (redshift==0.0) return 0.0;\n\t\telse {\n\t\t\tgsl_interp_accel *acc \n\t\t\t= gsl_interp_accel_alloc ();\n\t\t\t\n\t\t\tgsl_spline *spline \n\t\t\t= gsl_spline_alloc (gsl_interp_cspline, 1000);\n\t\t\t\n\t\t\tgsl_spline_init (spline, x, y, 1000);\n\t\t\tresult=units*gsl_spline_eval_integ (spline, x[0], x[dummy-1], acc); \n\t\t\tgsl_spline_free (spline);\n\t\t\tgsl_interp_accel_free (acc);\n\t\t}\n\t\treturn result;\n\t}\n\n\tfloat comov_dist(float redshift) { //comoving distance to redshift z in Mpc\n\t\t// note rcutoff is in units of Rvir\n\t\tint dummy;\n\t\tfloat result;\n\t\tdouble x[1000], y[1000];\n\t\tfloat speed_of_light = 2.9979e5; //km/s\n\t\tdouble units = speed_of_light/H0;\n\n\t\t\n\t\tfor(dummy=0;dummy<1000;dummy++){\n\t\t\tx[dummy]= 0.0+ redshift/999*dummy;\n\t\t\ty[dummy] = 1.0/(sqrt( Omega_M*pow(1+x[dummy],3) + Omega_L*pow(1+x[dummy], 3*wt+3) + (1.0-Omega_M-Omega_L)*pow(1+x[dummy],2)));\n\t\t}\n\t\tif (redshift==0.0) return 0.0;\n\t\telse {\n\t\t\tgsl_interp_accel *acc \n\t\t\t= gsl_interp_accel_alloc ();\n\t\t\t\n\t\t\tgsl_spline *spline \n\t\t\t= gsl_spline_alloc (gsl_interp_cspline, 1000);\n\t\t\t\n\t\t\tgsl_spline_init (spline, x, y, 1000);\n\t\t\tresult=units*gsl_spline_eval_integ (spline, x[0], x[dummy-1], acc); \n\t\t\tgsl_spline_free (spline);\n\t\t\tgsl_interp_accel_free (acc);\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tfloat cosmic_time(float redshift) {\n\t\t// function to calculate cosmic time to redshift given cosmological model\n\t\t//good to ~1% for z<10\n\t\t\n\t\t// these are weight functions for solving the differential equation\n\t\tfloat x[16] = {0.0950,0.2816,0.4580,0.6179,0.7554,0.8656,0.9446,0.9894,-0.0950,-0.2816,-0.4580,-0.6179,-0.7554,-0.8656,-0.9446,-0.9894};\n\t\tfloat w[16] = {0.1895,0.1826,0.1692,0.1496,0.1246,0.0952,0.0623,0.0272,0.1895,0.1826,0.1692,0.1496,0.1246,0.0952,0.0623,0.0272};\n\t\t\n\t\tfloat a0 = 0.0, a1, Delta_a, h2, sum, cosm_h0, den0 = Omega_M, den1 = Omega_L, den2;\n\t\tfloat ss, ak, adot, cosm_t;\n\t\tfloat time_units, secperyr = 3.15569260e7, age_of_univ = 8.93120195E+17/2.0; // in seconds\n\t\tint Nsteps, i, k;\n\t\tNsteps = 10000;\n\t\ta1 = 1.0/(1.0+redshift);\n\t\tDelta_a = (a1-a0)/Nsteps;\n\t\th2 = Delta_a/2.0;\n\t\tsum = 0.0;\n\t\tcosm_h0 = sqrt(8.0*PI/3.0);\n\t\t\n\t\ttime_units = (age_of_univ*2/secperyr/1.0E9)*(1.0E2/H0); // converts to Gyr\n\t\t// now solve friedman eqn.\n\t\tfor (i=0;i\n\n#include \"easel.h\"\n#include \"esl_stats.h\"\n\n\n/*****************************************************************\n * 1. Summary statistics calculations (means, variances)\n *****************************************************************/\n\n/* Function: esl_stats_DMean()\n * Synopsis: Calculates mean and $\\sigma^2$ for samples $x_i$.\n *\n * Purpose: Calculates the sample mean and $s^2$, the unbiased\n * estimator of the population variance, for a\n * sample of numbers , and optionally\n * returns either or both through and\n * .\n * \n * and do the same,\n * for float and integer vectors.\n *\n * Args: x - samples x[0]..x[n-1]\n * n - number of samples\n * opt_mean - optRETURN: mean\n * opt_var - optRETURN: estimate of population variance \n *\n * Returns: on success.\n */\nint\nesl_stats_DMean(const double *x, int n, double *opt_mean, double *opt_var)\n{\n double sum = 0.;\n double sqsum = 0.;\n int i;\n\n for (i = 0; i < n; i++) \n { \n sum += x[i];\n sqsum += x[i]*x[i];\n }\n if (opt_mean != NULL) *opt_mean = sum / (double) n;\n if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);\n return eslOK;\n}\nint\nesl_stats_FMean(const float *x, int n, double *opt_mean, double *opt_var)\n{\n double sum = 0.;\n double sqsum = 0.;\n int i;\n\n for (i = 0; i < n; i++) \n { \n sum += x[i];\n sqsum += x[i]*x[i];\n }\n if (opt_mean != NULL) *opt_mean = sum / (double) n;\n if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);\n return eslOK;\n}\nint\nesl_stats_IMean(const int *x, int n, double *opt_mean, double *opt_var)\n{\n double sum = 0.;\n double sqsum = 0.;\n int i;\n\n for (i = 0; i < n; i++) \n { \n sum += x[i];\n sqsum += x[i]*x[i];\n }\n if (opt_mean != NULL) *opt_mean = sum / (double) n;\n if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);\n return eslOK;\n}\n/*--------------- end, summary statistics -----------------------*/\n\n\n\n/*****************************************************************\n * 2. Special functions.\n *****************************************************************/\n\n/* Function: esl_stats_LogGamma()\n * Synopsis: Calculates $\\log \\Gamma(x)$.\n *\n * Purpose: Returns natural log of $\\Gamma(x)$, for $x > 0$.\n * \n * Credit: Adapted from a public domain implementation in the\n * NCBI core math library. Thanks to John Spouge and\n * the NCBI. (According to NCBI, that's Dr. John\n * \"Gammas Galore\" Spouge to you, pal.)\n *\n * Args: x : argument, x > 0.0\n * ret_answer : RETURN: the answer\n *\n * Returns: Put the answer in ; returns .\n * \n * Throws: if $x <= 0$.\n */\nint\nesl_stats_LogGamma(double x, double *ret_answer)\n{\n int i;\n double xx, tx;\n double tmp, value;\n static double cof[11] = {\n 4.694580336184385e+04,\n -1.560605207784446e+05,\n 2.065049568014106e+05,\n -1.388934775095388e+05,\n 5.031796415085709e+04,\n -9.601592329182778e+03,\n 8.785855930895250e+02,\n -3.155153906098611e+01,\n 2.908143421162229e-01,\n -2.319827630494973e-04,\n 1.251639670050933e-10\n };\n \n /* Protect against invalid x<=0 */\n if (x <= 0.0) ESL_EXCEPTION(eslERANGE, \"invalid x <= 0 in esl_stats_LogGamma()\");\n\n xx = x - 1.0;\n tx = tmp = xx + 11.0;\n value = 1.0;\n for (i = 10; i >= 0; i--)\t/* sum least significant terms first */\n {\n value += cof[i] / tmp;\n tmp -= 1.0;\n }\n value = log(value);\n tx += 0.5;\n value += 0.918938533 + (xx+0.5)*log(tx) - tx;\n *ret_answer = value;\n return eslOK;\n}\n\n\n/* Function: esl_stats_Psi()\n * Synopsis: Calculates $\\Psi(x)$ (the digamma function).\n *\n * Purpose: Computes $\\Psi(x)$ (the \"digamma\" function), which is\n * the derivative of log of the Gamma function:\n * $d/dx \\log \\Gamma(x) = \\frac{\\Gamma'(x)}{\\Gamma(x)} = \\Psi(x)$.\n * Argument $x$ is $> 0$. \n * \n * This is J.M. Bernardo's \"Algorithm AS103\",\n * Appl. Stat. 25:315-317 (1976). \n */\nint\nesl_stats_Psi(double x, double *ret_answer)\n{\n double answer = 0.;\n double x2;\n\n if (x <= 0.0) ESL_EXCEPTION(eslERANGE, \"invalid x <= 0 in esl_stats_Psi()\");\n \n /* For small x, Psi(x) ~= -0.5772 - 1/x + O(x), we're done.\n */\n if (x <= 1e-5) {\n *ret_answer = -eslCONST_EULER - 1./x;\n return eslOK;\n }\n\n /* For medium x, use Psi(1+x) = \\Psi(x) + 1/x to c.o.v. x,\n * big enough for Stirling approximation to work...\n */\n while (x < 8.5) {\n answer = answer - 1./x;\n x += 1.;\n }\n \n /* For large X, use Stirling approximation\n */\n x2 = 1./x;\n answer += log(x) - 0.5 * x2;\n x2 = x2*x2;\n answer -= (1./12.)*x2;\n answer += (1./120.)*x2*x2;\n answer -= (1./252.)*x2*x2*x2;\n\n *ret_answer = answer;\n return eslOK;\n}\n\n\n\n/* Function: esl_stats_IncompleteGamma()\n * Synopsis: Calculates the incomplete Gamma function.\n * \n * Purpose: Returns $P(a,x)$ and $Q(a,x)$ where:\n *\n * \\begin{eqnarray*}\n * P(a,x) & = & \\frac{1}{\\Gamma(a)} \\int_{0}^{x} t^{a-1} e^{-t} dt \\\\\n * & = & \\frac{\\gamma(a,x)}{\\Gamma(a)} \\\\\n * Q(a,x) & = & \\frac{1}{\\Gamma(a)} \\int_{x}^{\\infty} t^{a-1} e^{-t} dt\\\\\n * & = & 1 - P(a,x) \\\\\n * \\end{eqnarray*}\n *\n * $P(a,x)$ is the CDF of a gamma density with $\\lambda = 1$,\n * and $Q(a,x)$ is the survival function.\n * \n * For $x \\simeq 0$, $P(a,x) \\simeq 0$ and $Q(a,x) \\simeq 1$; and\n * $P(a,x)$ is less prone to roundoff error. \n * \n * The opposite is the case for large $x >> a$, where\n * $P(a,x) \\simeq 1$ and $Q(a,x) \\simeq 0$; there, $Q(a,x)$ is\n * less prone to roundoff error.\n *\n * Method: Based on ideas from Numerical Recipes in C, Press et al.,\n * Cambridge University Press, 1988. \n * \n * Args: a - for instance, degrees of freedom / 2 [a > 0]\n * x - for instance, chi-squared statistic / 2 [x >= 0] \n * ret_pax - RETURN: P(a,x)\n * ret_qax - RETURN: Q(a,x)\n *\n * Return: on success.\n *\n * Throws: if or is out of accepted range.\n * if approximation fails to converge.\n */ \nint\nesl_stats_IncompleteGamma(double a, double x, double *ret_pax, double *ret_qax)\n{\n int iter;\t\t\t/* iteration counter */\n double pax;\t\t\t/* P(a,x) */\n double qax;\t\t\t/* Q(a,x) */\n\n if (a <= 0.) ESL_EXCEPTION(eslERANGE, \"esl_stats_IncompleteGamma(): a must be > 0\");\n if (x < 0.) ESL_EXCEPTION(eslERANGE, \"esl_stats_IncompleteGamma(): x must be >= 0\");\n\n /* For x > a + 1 the following gives rapid convergence;\n * calculate Q(a,x) = \\frac{\\Gamma(a,x)}{\\Gamma(a)},\n * using a continued fraction development for \\Gamma(a,x).\n */\n if (x > a+1) \n {\n double oldp;\t\t/* previous value of p */\n double nu0, nu1;\t\t/* numerators for continued fraction calc */\n double de0, de1;\t\t/* denominators for continued fraction calc */\n\n nu0 = 0.;\t\t\t/* A_0 = 0 */\n de0 = 1.;\t\t\t/* B_0 = 1 */\n nu1 = 1.;\t\t\t/* A_1 = 1 */\n de1 = x;\t\t\t/* B_1 = x */\n\n oldp = nu1;\n for (iter = 1; iter < 100; iter++)\n\t{\n\t /* Continued fraction development:\n\t * set A_j = b_j A_j-1 + a_j A_j-2\n\t * B_j = b_j B_j-1 + a_j B_j-2\n * We start with A_2, B_2.\n\t */\n\t\t\t\t/* j = even: a_j = iter-a, b_j = 1 */\n\t\t\t\t/* A,B_j-2 are in nu0, de0; A,B_j-1 are in nu1,de1 */\n\t nu0 = nu1 + ((double)iter - a) * nu0;\n\t de0 = de1 + ((double)iter - a) * de0;\n\t\t\t\t/* j = odd: a_j = iter, b_j = x */\n\t\t\t\t/* A,B_j-2 are in nu1, de1; A,B_j-1 in nu0,de0 */\n\t nu1 = x * nu0 + (double) iter * nu1;\n\t de1 = x * de0 + (double) iter * de1;\n\t\t\t\t/* rescale */\n\t if (de1 != 0.) \n\t { \n\t nu0 /= de1; \n\t de0 /= de1;\n\t nu1 /= de1;\n\t de1 = 1.;\n\t }\n\t\t\t\t/* check for convergence */\n\t if (fabs((nu1-oldp)/nu1) < 1.e-7)\n\t {\n\t esl_stats_LogGamma(a, &qax);\t \n\t qax = nu1 * exp(a * log(x) - x - qax);\n\n\t if (ret_pax != NULL) *ret_pax = 1 - qax;\n\t if (ret_qax != NULL) *ret_qax = qax;\n\t return eslOK;\n\t }\n\n\t oldp = nu1;\n\t}\n ESL_EXCEPTION(eslENOHALT,\n\t\t\"esl_stats_IncompleteGamma(): fraction failed to converge\");\n }\n else /* x <= a+1 */\n {\n double p;\t\t\t/* current sum */\n double val;\t\t/* current value used in sum */\n\n /* For x <= a+1 we use a convergent series instead:\n * P(a,x) = \\frac{\\gamma(a,x)}{\\Gamma(a)},\n * where\n * \\gamma(a,x) = e^{-x}x^a \\sum_{n=0}{\\infty} \\frac{\\Gamma{a}}{\\Gamma{a+1+n}} x^n\n * which looks appalling but the sum is in fact rearrangeable to\n * a simple series without the \\Gamma functions:\n * = \\frac{1}{a} + \\frac{x}{a(a+1)} + \\frac{x^2}{a(a+1)(a+2)} ...\n * and it's obvious that this should converge nicely for x <= a+1.\n */\n p = val = 1. / a;\n for (iter = 1; iter < 10000; iter++)\n\t{\n\t val *= x / (a+(double)iter);\n\t p += val;\n\t \n\t if (fabs(val/p) < 1.e-7)\n\t {\n\t esl_stats_LogGamma(a, &pax);\n\t pax = p * exp(a * log(x) - x - pax);\n\n\t if (ret_pax != NULL) *ret_pax = pax;\n\t if (ret_qax != NULL) *ret_qax = 1. - pax;\n\t return eslOK;\n\t }\n\t}\n ESL_EXCEPTION(eslENOHALT,\n\t\t\"esl_stats_IncompleteGamma(): series failed to converge\");\n }\n /*NOTREACHED*/\n return eslOK;\n}\n/*----------------- end, special functions ----------------------*/\n\n\n/*****************************************************************\n * 3. Standard statistical tests.\n *****************************************************************/\n\n/* Function: esl_stats_GTest()\n * Synopsis: Calculates a G-test on 2 vs. 1 binomials.\n *\n * Purpose: In experiment a, we've drawn successes in total\n * trials; in experiment b, we've drawn successes in\n * total trials. Are the counts different enough to\n * conclude that the two experiments are different? The\n * null hypothesis is that the successes in both experiments\n * were drawn from the same binomial distribution with\n * per-trial probability $p$. The tested hypothesis is that\n * experiments a,b have different binomial probabilities\n * $p_a,p_b$. The G-test is a log-likelihood-ratio statistic,\n * assuming maximum likelihood values for $p,p_a,p_b$. \n * $2G$ is distributed approximately as $X^2(1)$,\n * %\"X\" is \"Chi\"\n * which we use to calculate a P-value for the G statistic.\n * \n * Args: ca - number of positives in experiment a\n * na - total number in experiment a\n * cb - number of positives in experiment b\n * nb - total number in experiment b\n * ret_G - RETURN: G statistic, a log likelihood ratio, in nats \n * ret_P - RETURN: P-value for the G-statistic\n *\n * Returns: on success.\n *\n * Throws: (no abnormal error conditions)\n *\n * Xref: Archive1999/0906-sagescore/sagescore.c\n */\nint\nesl_stats_GTest(int ca, int na, int cb, int nb, double *ret_G, double *ret_P)\n{\n double a,b,c,d,n;\n double G = 0.;\n\n a = (double) ca;\n b = (double) (na - ca);\n c = (double) cb;\n d = (double) (nb - cb);\n n = (double) na+nb;\n\n /* Yes, the calculation here is correct; algebraic \n * rearrangement of the log-likelihood-ratio with \n * p_a = ca/na, p_b = cb/nb, and p = (ca+cb)/(na+nb).\n * Guard against 0 probabilities; assume 0 log 0 => 0. \n */\n if (a > 0.) G = a * log(a);\n if (b > 0.) G += b * log(b);\n if (c > 0.) G += c * log(c);\n if (d > 0.) G += d * log(d);\n if (n > 0.) G += n * log(n);\n if (a+b > 0.) G -= (a+b) * log(a+b);\n if (c+d > 0.) G -= (c+d) * log(c+d);\n if (a+c > 0.) G -= (a+c) * log(a+c);\n if (b+d > 0.) G -= (b+d) * log(b+d);\n\n *ret_G = G;\n return esl_stats_IncompleteGamma( 0.5, G, NULL, ret_P);\n}\n\n\n/* Function: esl_stats_ChiSquaredTest()\n * Synopsis: Calculates a $\\chi^2$ P-value.\n * Incept: SRE, Tue Jul 19 11:39:32 2005 [St. Louis]\n *\n * Purpose: Calculate the probability that a chi-squared statistic\n * with degrees of freedom would exceed the observed\n * chi-squared value ; return it in . If\n * this probability is less than some small threshold (say,\n * 0.05 or 0.01), then we may reject the hypothesis we're\n * testing.\n *\n * Args: v - degrees of freedom\n * x - observed chi-squared value\n * ret_answer - RETURN: P(\\chi^2 > x)\n *\n * Returns: on success.\n *\n * Throws: if or are out of valid range.\n * if iterative calculation fails.\n */\nint\nesl_stats_ChiSquaredTest(int v, double x, double *ret_answer)\n{\n return esl_stats_IncompleteGamma((double)v/2, x/2, NULL, ret_answer);\n}\n/*----------------- end, statistical tests ---------------------*/\n\n\n\n/*****************************************************************\n * 4. Data fitting.\n *****************************************************************/\n\n/* Function: esl_stats_LinearRegression()\n * Synopsis: Fit data to a straight line.\n * Incept: SRE, Sat May 26 11:33:46 2007 [Janelia]\n *\n * Purpose: Fit points , to a straight line\n * $y = a + bx$ by linear regression. \n * \n * The $x_i$ are taken to be known, and the $y_i$ are taken\n * to be observed quantities associated with a sampling\n * error $\\sigma_i$. If known, the standard deviations\n * $\\sigma_i$ for $y_i$ are provided in the array.\n * If they are unknown, pass , and the\n * routine will proceed with the assumption that $\\sigma_i\n * = 1$ for all $i$.\n * \n * The maximum likelihood estimates for $a$ and $b$ are\n * optionally returned in and .\n * \n * The estimated standard deviations of $a$ and $b$ and\n * their estimated covariance are optionally returned in\n * , , and .\n * \n * The Pearson correlation coefficient is optionally\n * returned in . \n * \n * The $\\chi^2$ P-value for the regression fit is\n * optionally returned in . This P-value may only be\n * obtained when the $\\sigma_i$ are known. If is\n * passed as and is requested, <*opt_Q> is\n * set to 1.0.\n * \n * This routine follows the description and algorithm in\n * \\citep[pp.661-666]{Press93}.\n *\n * must be greater than 2; at least two x[i] must\n * differ; and if is provided, all must\n * be $>0$. If any of these conditions isn't met, the\n * routine throws .\n *\n * Args: x - x[0..n-1]\n * y - y[0..n-1]\n * sigma - sample error in observed y_i\n * n - number of data points\n * opt_a - optRETURN: intercept estimate\t\t\n * opt_b - optRETURN: slope estimate\n * opt_sigma_a - optRETURN: error in estimate of a\n * opt_sigma_b - optRETURN: error in estimate of b\n * opt_cov_ab - optRETURN: covariance of a,b estimates\n * opt_cc - optRETURN: Pearson correlation coefficient for x,y\n * opt_Q - optRETURN: X^2 P-value for linear fit\n *\n * Returns: on success.\n *\n * Throws: on allocation error;\n * if a contract condition isn't met;\n * if the chi-squared test fails.\n * In these cases, all optional return values are set to 0.\n */\nint\nesl_stats_LinearRegression(const double *x, const double *y, const double *sigma, int n,\n\t\t\t double *opt_a, double *opt_b,\n\t\t\t double *opt_sigma_a, double *opt_sigma_b, double *opt_cov_ab,\n\t\t\t double *opt_cc, double *opt_Q)\n{\n int status;\n double *t = NULL;\n double S, Sx, Sy, Stt;\n double Sxy, Sxx, Syy;\n double a, b, sigma_a, sigma_b, cov_ab, cc, X2, Q;\n double xdev, ydev;\n double tmp;\n int i;\n\n /* Contract checks. */\n if (n <= 2) ESL_XEXCEPTION(eslEINVAL, \"n must be > 2 for linear regression fitting\");\n if (sigma != NULL) \n for (i = 0; i < n; i++) if (sigma[i] <= 0.) ESL_XEXCEPTION(eslEINVAL, \"sigma[%d] <= 0\", i);\n status = eslEINVAL;\n for (i = 0; i < n; i++) if (x[i] != 0.) { status = eslOK; break; }\n if (status != eslOK) ESL_XEXCEPTION(eslEINVAL, \"all x[i] are 0.\");\n\n /* Allocations */\n ESL_ALLOC(t, sizeof(double) * n);\n\n /* S = \\sum_{i=1}{n} \\frac{1}{\\sigma_i^2}. (S > 0.) */\n if (sigma != NULL) { for (S = 0., i = 0; i < n; i++) S += 1./ (sigma[i] * sigma[i]); }\n else S = (double) n;\n\n /* S_x = \\sum_{i=1}{n} \\frac{x[i]}{ \\sigma_i^2} (Sx real.) */\n for (Sx = 0., i = 0; i < n; i++) { \n if (sigma == NULL) Sx += x[i];\n else Sx += x[i] / (sigma[i] * sigma[i]);\n }\n\n /* S_y = \\sum_{i=1}{n} \\frac{y[i]}{\\sigma_i^2} (Sy real.) */\n for (Sy = 0., i = 0; i < n; i++) { \n if (sigma == NULL) Sy += y[i];\n else Sy += y[i] / (sigma[i] * sigma[i]);\n }\n\n /* t_i = \\frac{1}{\\sigma_i} \\left( x_i - \\frac{S_x}{S} \\right) (t_i real) */\n for (i = 0; i < n; i++) {\n t[i] = x[i] - Sx/S;\n if (sigma != NULL) t[i] /= sigma[i];\n }\n\n /* S_{tt} = \\sum_{i=1}^n t_i^2 (if at least one x is != 0, Stt > 0) */\n for (Stt = 0., i = 0; i < n; i++) { Stt += t[i] * t[i]; }\n\n /* b = \\frac{1}{S_{tt}} \\sum_{i=1}^{N} \\frac{t_i y_i}{\\sigma_i} */\n for (b = 0., i = 0; i < n; i++) {\n if (sigma != NULL) { b += t[i]*y[i] / sigma[i]; }\n else { b += t[i]*y[i]; }\n }\n b /= Stt;\n\n /* a = \\frac{ S_y - S_x b } {S} */\n a = (Sy - Sx * b) / S;\n \n /* \\sigma_a^2 = \\frac{1}{S} \\left( 1 + \\frac{ S_x^2 }{S S_{tt}} \\right) */\n sigma_a = sqrt ((1. + (Sx*Sx) / (S*Stt)) / S);\n\n /* \\sigma_b = \\frac{1}{S_{tt}} */\n sigma_b = sqrt (1. / Stt);\n\n /* Cov(a,b) = - \\frac{S_x}{S S_{tt}} */\n cov_ab = -Sx / (S * Stt);\n \n /* Pearson correlation coefficient */\n Sxy = Sxx = Syy = 0.;\n for (i = 0; i < n; i++) {\n if (sigma != NULL) { \n xdev = (x[i] / (sigma[i] * sigma[i])) - (Sx / n);\n ydev = (y[i] / (sigma[i] * sigma[i])) - (Sy / n);\n } else {\n xdev = x[i] - (Sx / n);\n ydev = y[i] - (Sy / n);\n }\n Sxy += xdev * ydev;\n Sxx += xdev * xdev;\n Syy += ydev * ydev;\n }\n cc = Sxy / (sqrt(Sxx) * sqrt(Syy));\n\n /* \\chi^2 */\n for (X2 = 0., i = 0; i < n; i++) {\n tmp = y[i] - a - b*x[i];\n if (sigma != NULL) tmp /= sigma[i];\n X2 += tmp*tmp;\n }\n \n /* We can calculate a goodness of fit if we know the \\sigma_i */\n if (sigma != NULL) {\n if (esl_stats_ChiSquaredTest(n-2, X2, &Q) != eslOK) { status = eslENORESULT; goto ERROR; }\n } else Q = 1.0;\n\n /* If we didn't use \\sigma_i, adjust the sigmas for a,b */\n if (sigma == NULL) {\n tmp = sqrt(X2 / (double)(n-2));\n sigma_a *= tmp;\n sigma_b *= tmp;\n }\n \n /* Done. Set up for normal return.\n */\n free(t);\n if (opt_a != NULL) *opt_a = a;\n if (opt_b != NULL) *opt_b = b;\n if (opt_sigma_a != NULL) *opt_sigma_a = sigma_a;\n if (opt_sigma_b != NULL) *opt_sigma_b = sigma_b;\n if (opt_cov_ab != NULL) *opt_cov_ab = cov_ab;\n if (opt_cc != NULL) *opt_cc = cc;\n if (opt_Q != NULL) *opt_Q = Q;\n return eslOK;\n \n ERROR:\n if (t != NULL) free(t);\n if (opt_a != NULL) *opt_a = 0.;\n if (opt_b != NULL) *opt_b = 0.;\n if (opt_sigma_a != NULL) *opt_sigma_a = 0.;\n if (opt_sigma_b != NULL) *opt_sigma_b = 0.;\n if (opt_cov_ab != NULL) *opt_cov_ab = 0.;\n if (opt_cc != NULL) *opt_cc = 0.;\n if (opt_Q != NULL) *opt_Q = 0.;\n return status;\n}\n/*------------------- end, data fitting -------------------------*/\n\n\n\n/*****************************************************************\n * 5. Unit tests.\n *****************************************************************/\n#ifdef eslSTATS_TESTDRIVE\n#include \"esl_random.h\"\n#include \"esl_stopwatch.h\"\n#ifdef HAVE_LIBGSL \n#include \n#endif\n\n/* The LogGamma() function is rate-limiting in hmmbuild, because it is\n * used so heavily in mixture Dirichlet calculations.\n * ./configure --with-gsl; [compile test driver]\n * ./stats_utest -v\n * runs a comparison of time/precision against GSL.\n * SRE, Sat May 23 10:04:41 2009, on home Mac:\n * LogGamma = 1.29u / N=1e8 = 13 nsec/call\n * gsl_sf_lngamma = 1.43u / N=1e8 = 14 nsec/call\n */\nstatic void\nutest_LogGamma(ESL_RANDOMNESS *r, int N, int be_verbose)\n{\n char *msg = \"esl_stats_LogGamma() unit test failed\";\n ESL_STOPWATCH *w = esl_stopwatch_Create();\n double *x = malloc(sizeof(double) * N);\n double *lg = malloc(sizeof(double) * N);\n double *lg2 = malloc(sizeof(double) * N);\n int i;\n\n for (i = 0; i < N; i++) \n x[i] = esl_random(r) * 100.;\n \n esl_stopwatch_Start(w);\n for (i = 0; i < N; i++) \n if (esl_stats_LogGamma(x[i], &(lg[i])) != eslOK) esl_fatal(msg);\n esl_stopwatch_Stop(w);\n\n if (be_verbose) esl_stopwatch_Display(stdout, w, \"esl_stats_LogGamma() timing: \");\n\n#ifdef HAVE_LIBGSL\n esl_stopwatch_Start(w);\n for (i = 0; i < N; i++) lg2[i] = gsl_sf_lngamma(x[i]);\n esl_stopwatch_Stop(w);\n\n if (be_verbose) esl_stopwatch_Display(stdout, w, \"gsl_sf_lngamma() timing: \");\n \n for (i = 0; i < N; i++)\n if (esl_DCompare(lg[i], lg2[i], 1e-2) != eslOK) esl_fatal(msg);\n#endif\n \n free(lg2);\n free(lg);\n free(x);\n esl_stopwatch_Destroy(w);\n}\n\n\n/* The test of esl_stats_LinearRegression() is a statistical test,\n * so we can't be too aggressive about testing results. \n * \n * Args:\n * r - a source of randomness\n * use_sigma - TRUE to pass sigma to the regression fit.\n * be_verbose - TRUE to print results (manual, not automated test mode)\n */\nstatic void\nutest_LinearRegression(ESL_RANDOMNESS *r, int use_sigma, int be_verbose)\n{\n char msg[] = \"linear regression unit test failed\";\n double a = -3.;\n double b = 1.;\n int n = 100;\n double xori = -20.;\n double xstep = 1.0;\n double setsigma = 1.0;\t\t/* sigma on all points */\n int i;\n double *x = NULL;\n double *y = NULL;\n double *sigma = NULL;\n double ae, be, siga, sigb, cov_ab, cc, Q;\n \n if ((x = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);\n if ((y = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);\n if ((sigma = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);\n \n /* Simulate some linear data */\n for (i = 0; i < n; i++)\n {\n sigma[i] = setsigma;\n x[i] = xori + i*xstep;\n y[i] = esl_rnd_Gaussian(r, a + b*x[i], sigma[i]);\n }\n \n if (use_sigma) {\n if (esl_stats_LinearRegression(x, y, sigma, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK) esl_fatal(msg);\n } else {\n if (esl_stats_LinearRegression(x, y, NULL, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK) esl_fatal(msg);\n }\n\n if (be_verbose) {\n printf(\"Linear regression test:\\n\");\n printf(\"estimated intercept a = %8.4f [true = %8.4f]\\n\", ae, a);\n printf(\"estimated slope b = %8.4f [true = %8.4f]\\n\", be, b);\n printf(\"estimated sigma on a = %8.4f\\n\", siga);\n printf(\"estimated sigma on b = %8.4f\\n\", sigb);\n printf(\"estimated cov(a,b) = %8.4f\\n\", cov_ab);\n printf(\"correlation coeff = %8.4f\\n\", cc);\n printf(\"P-value = %8.4f\\n\", Q);\n }\n\n /* The following tests are statistical.\n */\n if ( fabs(ae-a) > 2*siga ) esl_fatal(msg);\n if ( fabs(be-b) > 2*sigb ) esl_fatal(msg);\n if ( cc < 0.95) esl_fatal(msg);\n if (use_sigma) {\n if (Q < 0.001) esl_fatal(msg);\n } else {\n if (Q != 1.0) esl_fatal(msg);\n }\n\n free(x);\n free(y);\n free(sigma);\n}\n#endif /*eslSTATS_TESTDRIVE*/\n/*-------------------- end of unit tests ------------------------*/\n\n\n\n\n/*****************************************************************\n * 6. Test driver.\n *****************************************************************/\n#ifdef eslSTATS_TESTDRIVE\n/* gcc -g -Wall -o stats_utest -L. -I. -DeslSTATS_TESTDRIVE esl_stats.c -leasel -lm\n * gcc -DHAVE_LIBGSL -O2 -o stats_utest -L. -I. -DeslSTATS_TESTDRIVE esl_stats.c -leasel -lgsl -lm\n */\n#include \n#include \"easel.h\"\n#include \"esl_getopts.h\"\n#include \"esl_random.h\"\n#include \"esl_stats.h\"\n\nstatic ESL_OPTIONS options[] = {\n /* name type default env range togs reqs incomp help docgrp */\n {\"-h\", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, \"show help and usage\", 0},\n {\"-s\", eslARG_INT, \"42\", NULL, NULL, NULL, NULL, NULL, \"set random number seed to \", 0},\n {\"-v\", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, \"verbose: show verbose output\", 0},\n {\"-N\", eslARG_INT,\"10000000\", NULL, NULL, NULL, NULL, NULL, \"number of trials in LogGamma test\", 0},\n { 0,0,0,0,0,0,0,0,0,0},\n};\nstatic char usage[] = \"[-options]\";\nstatic char banner[] = \"test driver for stats special functions\";\n\nint\nmain(int argc, char **argv)\n{\n ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);\n ESL_RANDOMNESS *r = esl_randomness_Create(esl_opt_GetInteger(go, \"-s\"));\n int be_verbose = esl_opt_GetBoolean(go, \"-v\");\n int N = esl_opt_GetInteger(go, \"-N\");\n\n if (be_verbose) printf(\"seed = %\" PRIu32 \"\\n\", esl_randomness_GetSeed(r));\n\n utest_LogGamma(r, N, be_verbose);\n utest_LinearRegression(r, TRUE, be_verbose);\n utest_LinearRegression(r, FALSE, be_verbose);\n \n esl_getopts_Destroy(go);\n esl_randomness_Destroy(r);\n exit(0);\n}\n#endif /*eslSTATS_TESTDRIVE*/\n/*------------------- end of test driver ------------------------*/\n\n\n\n\n/*****************************************************************\n * 7. Examples.\n *****************************************************************/\n\n/* Compile: gcc -g -Wall -o example -I. -DeslSTATS_EXAMPLE esl_stats.c esl_random.c easel.c -lm \n * or gcc -g -Wall -o example -I. -L. -DeslSTATS_EXAMPLE esl_stats.c -leasel -lm \n */\n#ifdef eslSTATS_EXAMPLE\n/*::cexcerpt::stats_example::begin::*/\n/* gcc -g -Wall -o example -I. -DeslSTATS_EXAMPLE esl_stats.c esl_random.c easel.c -lm */\n#include \n#include \"easel.h\"\n#include \"esl_random.h\"\n#include \"esl_stats.h\"\n\nint main(void)\n{\n ESL_RANDOMNESS *r = esl_randomness_Create(0);\n double a = -3.;\n double b = 1.;\n double xori = -20.;\n double xstep = 1.0;\n double setsigma = 1.0;\t\t/* sigma on all points */\n int n = 100;\n double *x = malloc(sizeof(double) * n);\n double *y = malloc(sizeof(double) * n);\n double *sigma = malloc(sizeof(double) * n);\n int i;\n double ae, be, siga, sigb, cov_ab, cc, Q;\n \n /* Simulate some linear data, with Gaussian noise added to y_i */\n for (i = 0; i < n; i++) {\n sigma[i] = setsigma;\n x[i] = xori + i*xstep;\n y[i] = esl_rnd_Gaussian(r, a + b*x[i], sigma[i]);\n }\n \n if (esl_stats_LinearRegression(x, y, sigma, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK)\n esl_fatal(\"linear regression failed\");\n\n printf(\"estimated intercept a = %8.4f [true = %8.4f]\\n\", ae, a);\n printf(\"estimated slope b = %8.4f [true = %8.4f]\\n\", be, b);\n printf(\"estimated sigma on a = %8.4f\\n\", siga);\n printf(\"estimated sigma on b = %8.4f\\n\", sigb);\n printf(\"estimated cov(a,b) = %8.4f\\n\", cov_ab);\n printf(\"correlation coeff = %8.4f\\n\", cc);\n printf(\"P-value = %8.4f\\n\", Q);\n\n free(x); free(y); free(sigma); \n esl_randomness_Destroy(r);\n exit(0);\n}\n/*::cexcerpt::stats_example::end::*/\n#endif /* eslSTATS_EXAMPLE */\n\n\n#ifdef eslSTATS_EXAMPLE2\n\n#include \n\n#include \"easel.h\"\n#include \"esl_getopts.h\"\n#include \"esl_stats.h\"\n\nstatic ESL_OPTIONS options[] = {\n /* name type default env range toggles reqs incomp help docgroup*/\n { \"-h\", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, \"show brief help on version and usage\", 0 },\n { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },\n};\nstatic char usage[] = \"[-options] \";\nstatic char banner[] = \"example from the stats module: using a G-test\";\n\nint\nmain(int argc, char **argv)\n{\n ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 4, argc, argv, banner, usage);\n int ca = strtol(esl_opt_GetArg(go, 1), NULL, 10);\n int na = strtol(esl_opt_GetArg(go, 2), NULL, 10);\n int cb = strtol(esl_opt_GetArg(go, 3), NULL, 10);\n int nb = strtol(esl_opt_GetArg(go, 4), NULL, 10);\n double G, P;\n int status;\n \n if (ca > na || cb > nb) esl_fatal(\"argument order wrong? expect ca, na, cb, nb for ca/na, cb/nb\");\n \n if ( (status = esl_stats_GTest(ca, na, cb, nb, &G, &P)) != eslOK) esl_fatal(\"G-test failed?\");\n printf(\"%-10.3g %12.2f\\n\", P, G);\n exit(0);\n}\n#endif /* eslSTATS_EXAMPLE2 */\n/*--------------------- end of examples -------------------------*/\n\n\n\n\n/*****************************************************************\n * Easel - a library of C functions for biological sequence analysis\n * Version h3.1b2; February 2015\n * Copyright (C) 2015 Howard Hughes Medical Institute.\n * Other copyrights also apply. See the COPYRIGHT file for a full list.\n * \n * Easel is distributed under the Janelia Farm Software License, a BSD\n * license. See the LICENSE file for more details.\n *\n * SVN $Id: esl_stats.c 854 2013-02-25 22:00:19Z wheelert $\n * SVN $URL: https://svn.janelia.org/eddylab/eddys/easel/branches/hmmer/3.1/esl_stats.c $\n *****************************************************************/\n", "meta": {"hexsha": "ed133f0dbf25b0a8c054ea4ec747d2d564cc63ef", "size": 30899, "ext": "c", "lang": "C", "max_stars_repo_path": "Linux/easel/esl_stats.c", "max_stars_repo_name": "YJY-98/PROSAVA", "max_stars_repo_head_hexsha": "6c1beb53922471218386b7ed24e72fb093fe457c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linux/easel/esl_stats.c", "max_issues_repo_name": "YJY-98/PROSAVA", "max_issues_repo_head_hexsha": "6c1beb53922471218386b7ed24e72fb093fe457c", "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": "Linux/easel/esl_stats.c", "max_forks_repo_name": "YJY-98/PROSAVA", "max_forks_repo_head_hexsha": "6c1beb53922471218386b7ed24e72fb093fe457c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5130151844, "max_line_length": 124, "alphanum_fraction": 0.5240299039, "num_tokens": 9807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7133443025406525}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ellipsoid/ellipsoid.h\"\n#include \"ellipsoid/ellSolv.h\"\n#include \"sphere/sphere.h\"\n#include \"sphere/sphSolv.h\"\n#include \"constants.h\"\n#include \"testProblem.h\"\n\n\n//compares ellipsoidal and spherical\n//has ellipsoidal distribution of charges just inside ellipsoidal boundary\n//computes the solution at two point, one inside smallest enclosing sphere where spherical diverges\n//other solution point is outside of sphere and ellipse to compare convergence\n#undef __FUNCT__\n#define __FUNCT__ \"EllVsSphConvergence\"\nPetscErrorCode EllVsSphConvergence()\n{\n PetscErrorCode ierr;\n //semi-axes of ellipsoid\n PetscReal a = 3.0;\n PetscReal b = 2.5;\n PetscReal c = 1.2;\n //sphere radius\n PetscReal sphRad = 3;\n //dielecric permitivities both set to 1\n const PetscReal eps1 = 1.0;\n const PetscReal eps2 = 1.0;\n //charges placed on ellipsoid with sem-axes smaller by epsilon\n PetscReal epsilon = .5;\n //interior charge XYZ and magnitude\n const PetscInt SQRT_NUM_CHARGES = 3;\n Vec chargeXYZ;\n Vec chargeMag;\n //maximum expansion order for test\n const PetscInt MAX_N = 20;\n //solutions vector\n const PetscInt NUM_SOL_PTS = 2;\n Vec ellSolutions[MAX_N], sphSolutions[MAX_N];\n Vec ellError[MAX_N], sphError[MAX_N];\n Vec exactSolution;\n Vec solXYZ;\n //solution point inside of sphere\n PetscReal sol1X = .1;\n PetscReal sol1Y = .1;\n PetscReal sol1Z = 1.5;\n //solution point outside of sphere\n PetscReal sol2X = 2.1;\n PetscReal sol2Y = 2.6;\n PetscReal sol2Z = 1;\n //pointer for accessing petsc vectors\n PetscScalar *vecPt;\n PetscFunctionBegin;\n\n //create, set charge magnitudes to 1\n ierr = VecCreateSeq(PETSC_COMM_SELF, SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, &chargeMag);CHKERRQ(ierr);\n ierr = VecSet(chargeMag, 1.0);CHKERRQ(ierr);\n\n //create, set charge XYZ values to be on a-eps,b-eps,c-eps ellipsoid\n ierr = VecCreateSeq(PETSC_COMM_SELF, 3*SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, &chargeXYZ);CHKERRQ(ierr);\n ierr = VecGetArray(chargeXYZ, &vecPt);CHKERRQ(ierr);\n PetscReal pu, pv;\n for(PetscInt i=0; istageInfo[chargeStages[count]].perfInfo.flops);CHKERRQ(ierr);\n count++;\n }\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"WriteToFile\"\nPetscErrorCode WriteToFile(const char *fname, PetscInt rowsize, Vec values)\n{\n PetscErrorCode ierr;\n PetscInt k;\n PetscInt nPts;\n const PetscScalar *valuesArray;\n PetscFunctionBegin;\n\n ierr = VecGetSize(values, &nPts);CHKERRQ(ierr);\n\n ierr = VecGetArrayRead(values, &valuesArray);CHKERRQ(ierr);\n FILE *fp = fopen(fname, \"w\");\n for(k=0; k < nPts; ++k) {\n fprintf(fp, \"%4.4f \", valuesArray[k]);\n if((k+1)%rowsize == 0)\n fprintf(fp, \"\\n\");\n }\n fclose(fp);\n ierr = VecRestoreArrayRead(values, &valuesArray);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"SolutionAnimation\"\nPetscErrorCode SolutionAnimation()\n{\n PetscErrorCode ierr;\n Vec x1, y1, s0, s1, s2, s3;\n PetscFunctionBegin;\n PetscInt nSrc = 10;\n PetscInt nx = 15;\n PetscReal xl = -4.6;\n PetscReal xr = 4.6;\n PetscInt ny = 15;\n PetscReal yl = -4.6;\n PetscReal yr = 4.6;\n PetscReal zConst = .1;\n\n ierr = GridSolution(0, nSrc, nx, xl, xr, ny, yl, yr, zConst, &x1, &y1, &s0);CHKERRQ(ierr);\n ierr = WriteToFile((const char*) \"out/sol0.txt\", ny, s0);CHKERRQ(ierr);\n ierr = GridSolution(1, nSrc, nx, xl, xr, ny, yl, yr, zConst, &x1, &y1, &s1);CHKERRQ(ierr);\n ierr = WriteToFile((const char*) \"out/sol1.txt\", ny, s1);CHKERRQ(ierr);\n ierr = GridSolution(2, nSrc, nx, xl, xr, ny, yl, yr, zConst, &x1, &y1, &s2);CHKERRQ(ierr);\n ierr = WriteToFile((const char*) \"out/sol2.txt\", ny, s2);CHKERRQ(ierr);\n ierr = GridSolution(3, nSrc, nx, xl, xr, ny, yl, yr, zConst, &x1, &y1, &s3);CHKERRQ(ierr);\n ierr = WriteToFile((const char*) \"out/sol3.txt\", ny, s3);CHKERRQ(ierr);\n\n ierr = WriteToFile((const char*) \"out/xVals.txt\", 1, x1);CHKERRQ(ierr);\n ierr = WriteToFile((const char*) \"out/yVals.txt\", 1, y1);CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"testLame\"\nPetscErrorCode testLame()\n{\n PetscErrorCode ierr;\n PetscInt n, p;\n PetscInt Nmax;\n PetscReal Fnp;\n PetscReal Enp;\n PetscReal a, b, c;\n PetscReal cval;\n PetscInt signm, signn;\n EllipsoidalSystem e;\n PetscFunctionBegin;\n\n cval = .3;\n signm = -1;\n signn = 1;\n \n a = 3.0; b = 2.0; c = 1.0;\n initEllipsoidalSystem(&e, a, b, c, 64);\n FILE *fp = fopen(\"newellout.txt\", \"w\");\n Nmax = 6;\n for(n=0; n < Nmax; ++n) {\n for(p=0; p < 2*n+1; ++p) {\n ierr = calcLame(&e, n, p, cval, signm, signn, &Enp);CHKERRQ(ierr);\n fprintf(fp, \"%d %d %15.15f\\n\", n, p, Enp);\n }\n }\n fclose(fp);\n\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"main\"\nPetscErrorCode main( int argc, char **argv )\n{\n\n PetscErrorCode ierr;\n \n PetscFunctionBeginUser;\n //initialize Petsc\n ierr = PetscInitialize(&argc, &argv, NULL, NULL); CHKERRQ(ierr);\n ierr = PetscLogDefaultBegin(); CHKERRQ(ierr); \n\n\n //ierr = EllVsSphConvergence();CHKERRQ(ierr);\n \n //testSphericalCoordinates();\n //runTest1();\n //testLegendre();\n //runTest4();\n //test4sphere();\n //RunArg();\n //ierr = RunArgTester(); CHKERRQ(ierr);\n //PetscErrorCode GridSolution(PetscInt Nmax, PetscInt nSrc, PetscInt nx, PetscReal xl, PetscReal xr, PetscInt ny, PetscReal yl, PetscReal yr, PetscReal zConst)\n /*\n PetscInt Nmax = 4;\n PetscInt nSrc = 25;\n PetscInt nx = 15;\n PetscReal xl = -5.23;\n PetscReal xr = 5.23;\n PetscInt ny = 15;\n PetscReal yl = -4.45;\n PetscReal yr = 4.45;\n PetscReal zConst = .1;\n PetscReal eps1 = 4.0;\n PetscReal eps2 = 80.0;\n */\n //ierr = GridSolution(Nmax, nSrc, nx, xl, xr, ny, yl, yr, zConst, NULL, NULL);CHKERRQ(ierr);\n //ierr = SolutionAnimation(); //<---- total crap\n //runTest1();\n //testLame();\n\n\n// ierr = runTest1();CHKERRQ(ierr);\n //ierr = RunArg();\n //ierr = GridAnimation();CHKERRQ(ierr);\n //ierr = ChargeFlopsExample(10);CHKERRQ(ierr);\n ierr = WorkPrecExample();CHKERRQ(ierr);\n //ierr = SphereLimitExample();CHKERRQ(ierr);\n\n\n\n\n //ierr = numChargesPlot(100, 500, 100);\n ierr = PetscFinalize();CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "8d6409be8e14edfd955f29390e07f6ab11513adc", "size": 52653, "ext": "c", "lang": "C", "max_stars_repo_path": "src/testProblem.c", "max_stars_repo_name": "tom-klotz/ellipsoid-solvation", "max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z", "max_issues_repo_path": "src/testProblem.c", "max_issues_repo_name": "tom-klotz/ellipsoid-solvation", "max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/testProblem.c", "max_forks_repo_name": "tom-klotz/ellipsoid-solvation", "max_forks_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6631513648, "max_line_length": 191, "alphanum_fraction": 0.6603802252, "num_tokens": 17522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.7132928564443485}} {"text": "#include \n#include \n#include /* GSL Integration Library */\n#include \"funs.c\" /* Integration functions */\n#include \"timing_funs.h\" /* Timing functions */\n\n#define NMAX 100\n\n\n\nint main(void)\n{\n\t/* Declaration and initialization */\n\tint i;\n\tdouble vals1[NMAX+1], vals2[NMAX+1];\n\n\t/*Uses functions declared in \"funs.c\" to compute I(n) using the recurrence and the \t\tgeneric integrator methods, and stores the results in their respective arrays.*/\n\tintegral_recur(0, 100, vals1);\n\tintegral_gen(0, 100, vals2);\n\t\n\t/*Prints \"n\" and the result I(n) for each method above. The absolute error \t\tmultiplied by a factor of 1.e9 is reported in the last column.*/\n\t\n\tprintf(\"n Recurrence Generic Scaled Abs Err\\n\");\n\n\tfor(i = 0; i <=NMAX; i++)\n\t{\n\t\tprintf(\"%d %.8f %.8f %f\\n\", i, vals1[i], vals2[i], \n\t\t(fabs(vals1[i]-vals2[i]))*1.e9);\n\t}\n\n\n\t/* Define the intial number of counts, tmin, tmax*/\n\tdouble time, trr, tgsl;\n\tint tmin = 1;\n\tint tmax = 2;\n\tint count = 1000;\n\n\t/* Computes the time per function call of the recurrence integration method. Calls \t\tthe function integral_recur() \"count\" times and adjusts count until the total time \t\tis between 1 and 2 seconds.*/\n\tprintf(\"\\n Timing for Recurrence Relation:\\n\");\n\tdo\n\t{\n\t\ttimer_start ();\n\t\tfor(i = 0; i < count; i++)\n\t\t{\n\t\t\tintegral_recur(0, 100, vals1);\n\t\t}\n\t\ttime = timer_stop ();\n\t\ttrr = time /count;\n\t\tprintf (\" %10.2f usec %10.6f sec %10d\\n\",trr * 1.e6, time, count);\n\t\tcount = adjust_rep_count (count, time, tmin, tmax);\n\t}\n\twhile ((time >tmax) || (time tmax) || (time \n#include \n#include \n\n\ndouble square(double x, void* params){\n return x*x;\n}\n\ndouble square_int(double x){\n return (x*x*x)/3;\n}\n\n\ndouble root(double x, void * params){\n return sqrt(x);\n}\n\ndouble root_int(double x){\n return (2.0/3) * sqrt(x*x*x);\n}\n\ndouble osc(double x, void* params){\n double a = *(double *) params;\n return a * cos(a* x);\n}\n\ndouble osc_int(double x, double a){\n return sin(a* x);\n}\n\ndouble rev(double x, void* params){\n return 1.0/ (x*x);\n}\n\ndouble rev_int(double x){\n return (1.0) /x;\n}\n\nint\nmain (void)\n{\n gsl_integration_workspace * w\n = gsl_integration_workspace_alloc (1000);\n\n double result;\n double error;\n gsl_function F;\n printf(\"method,funct,result,expected,est_error,intervals\\n\" );\n\n F.function = □\n // F.params = α\n size_t neval = 5;\n double desired_error;\n\n //////////////////////////////\n // QNG\n desired_error = 1.0;\n for(int i=0; i<6; i++){\n F.function = □\n\n gsl_integration_qng(&F, 0, 1, 0, desired_error, &result, &error, &neval);\n printf(\"qng,square,%.18f,%.18f,%.18f,%zd\\n\",result,square_int(1),error,neval );\n F.function = root;\n gsl_integration_qng(&F, 0.001, 1, 0, desired_error, &result, &error, &neval);\n printf(\"qng,root,%.18f,%.18f,%.18f,%zd\\n\",result,root_int(1),error,neval );\n desired_error = desired_error / 10;\n }\n\n /////////////////////\n\n ////////////////////////\n //QAG\n\n desired_error = 1.0;\n\n neval = 15;\n for(int i=0; i<6; i++){\n F.function = □\n gsl_integration_qag(&F, 0, 1, 0, desired_error, 1000, i, w, &result, &error);\n printf(\"qag,square,%.18f,%.18f,%.18f,%zd\\n\",result,square_int(1),error,w->size);\n F.function = root;\n gsl_integration_qag(&F, 0.001, 1, 0, desired_error, 1000, i, w, &result, &error);\n printf(\"qag,root,%.18f,%.18f,%.18f,%zd\\n\",result,root_int(1),error,w->size );\n desired_error = desired_error / 10;\n if(i==0) neval+=6;\n else neval +=10;\n }\n\n /////////////////////\n\n ////////////////////////\n //QAGS\n\n desired_error = 1.0;\n\n neval = 15;\n for(int i=0; i<6; i++){\n F.function = □\n gsl_integration_qags(&F, 0, 1, 0, desired_error, 1000, w, &result, &error);\n printf(\"qags,square,%.18f,%.18f,%.18f,%zd\\n\",result,square_int(1),error,w->size);\n F.function = root;\n gsl_integration_qags(&F, 0.001, 1, 0, desired_error, 1000, w, &result, &error);\n printf(\"qags,root,%.18f,%.18f,%.18f,%zd\\n\",result,root_int(1),error,w->size);\n desired_error = desired_error / 10;\n if(i==0) neval+=6;\n else neval +=10;\n }\n /////\n\n ////////////////////////\n //QAGP\n\n double pts[2];\n pts[0] = 0;\n pts[1] = 1;\n desired_error = 1.0;\n\n neval = 15;\n for(int i=0; i<6; i++){\n F.function = □\n gsl_integration_qagp(&F, pts, 2, 0, desired_error, 1000, w, &result, &error);\n printf(\"qags,square,%.18f,%.18f,%.18f,%zd\\n\",result,square_int(1),error,w->size);\n F.function = root;\n gsl_integration_qagp(&F,pts, 2, 0, desired_error, 1000, w, &result, &error);\n printf(\"qags,root,%.18f,%.18f,%.18f,%zd\\n\",result,root_int(1),error,w->size);\n desired_error = desired_error / 10;\n if(i==0) neval+=6;\n else neval +=10;\n }\n /////\n\n /////////////////\n // Oscillation\n //////////\n // QNG\n double stop;\n double alpha;\n alpha = 4.0;\n F.params = α\n F.function = &osc;\n desired_error = 1.0;\n double start=1.0;\n stop = (9.0 / (2.0 * M_PI));\n for(int i=0; i<6; i++){\n gsl_integration_qng(&F, start, stop, 0, desired_error, &result, &error, &neval);\n printf(\"qng,osc,%.18f,%.18f,%.18f,%zd\\n\",result,(osc_int(stop, alpha) - osc_int(start, alpha)),error,neval);\n desired_error = desired_error / 10;\n }\n\n // QAG\n alpha = 4.0;\n F.params = α\n F.function = &osc;\n desired_error = 1.0;\n stop = (9.0 / (2.0 * M_PI));\n neval=15;\n for(int i=0; i<6; i++){\n gsl_integration_qag(&F, start, stop, 0, desired_error, 1000, i, w, &result, &error);\n printf(\"qag,osc,%.18f,%.18f,%.18f,%zd\\n\",result,(osc_int(stop, alpha) - osc_int(start, alpha)),error,neval);\n desired_error = desired_error / 10;\n if(i==0) neval+=6;\n else neval +=10;\n }\n\n //QAWO\n gsl_integration_qawo_table * wf = gsl_integration_qawo_table_alloc(alpha, (stop - start), GSL_INTEG_SINE, 2);\n desired_error = 1.0;\n\n for(int i=0; i<6; i++){\n gsl_integration_qawo(&F, start, 0, desired_error, 1000, w, wf, &result, &error);\n printf(\"qawo,osc,%.18f,%.18f,%.18f,%zd\\n\",result,(osc_int(stop, alpha) - osc_int(start, alpha)),error, w->size);\n desired_error = desired_error / 10;\n if(i==0) neval+=6;\n else neval +=10;\n }\n gsl_integration_qawo_table_free(wf);\n\n\n\n ///QAGIU\n F.function = &rev;\n desired_error = 1.0;\n start = 2.5;\n for(int i=0; i<6; i++){\n gsl_integration_qagiu(&F, start, 0, desired_error, 1000, w, &result, &error);\n printf(\"qagiu,osc,%.18f,%.18f,%.18f,%zd\\n\",result,(rev_int(start)),error, w->size);\n desired_error = desired_error / 10;\n if(i==0) neval+=6;\n else neval +=10;\n }\n\n\n\n gsl_integration_workspace_free (w);\n return 0;\n}\n", "meta": {"hexsha": "8d1b4c5d7ca10ed9d9b599e3303e0cca6e01e3f4", "size": 5058, "ext": "c", "lang": "C", "max_stars_repo_path": "lab8/integr.c", "max_stars_repo_name": "mprzewie/MOwNiT_2", "max_stars_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab8/integr.c", "max_issues_repo_name": "mprzewie/MOwNiT_2", "max_issues_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271", "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": "lab8/integr.c", "max_forks_repo_name": "mprzewie/MOwNiT_2", "max_forks_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-10T09:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T10:19:18.000Z", "avg_line_length": 25.5454545455, "max_line_length": 116, "alphanum_fraction": 0.5915381574, "num_tokens": 1816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7128514680581354}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \"optimization.h\"\n\n\n\n\n\n\n\n/*****************************************************************************/\n/* vector routines */\n\ndouble vec_dot_prod(const double *v1, const double *v2, const int N)\n{\n int i;\n double nn = 0;\n for (i=0;i= WOLFE_C2 * dir_deriv_old)\n {\n return 1;\n }\n return 0;\n}\n\nint check_strong_curvature(double dir_deriv_old, double dir_deriv_new)\n{\n /* returns 1 if strong curvature satisfied, 0 otherwise */\n if (dir_deriv_new >= WOLFE_C2 * dir_deriv_old && \n dir_deriv_new <= -WOLFE_C2 * dir_deriv_old)\n {\n return 1;\n }\n return 0;\n}\n\n\n/*****************************************************************************/\n\ndouble initial_step_length(search_dir sd, double alpha_old, double dir_deriv_old, double dir_deriv_new)\n{\n /* calculate initial step length for a line search step */\n /* inputs: */\n /* sd: search direction, CG, STEEPEST, or LBFGS */\n /* alpha_old: previous (accepted) step length */\n /* dir_deriv_old: directional derivative at previous step */\n /* (dot product of previous gradient and search direction) */\n /* dir_deriv_new: directional derivative at current step */\n /* (dot product of current gradient and search direction) */\n \n\n\n if (sd == CG || sd == STEEPEST)\n {\n /* see Nocedal & Wright 2006, p. 59 */\n return alpha_old * (dir_deriv_old / dir_deriv_new);\n }\n\n /* quasi-Newton methods are well scaled use steplength of 1.0 for L-BFGS */\n return 1.0;\n\n}\n\n\n\n/*****************************************************************************/\n/* steepest descent direction */\n\nvoid steepest_descent_direction(const double *grad, double *p, const int N)\n{\n int i;\n for (i=0;i beta_FR)\n {\n beta = beta_FR;\n }\n\n /* calculate new search direction */\n for (i=0;i=0;ii--)\n {\n aa[ii] = rho[ind[ii] / N] * vec_dot_prod(s+ind[ii], q, N);\n\n\n for (jj=0;jj\nvoid newton_direction(const double *gradient, const double *hessian, const int N, double *p_new)\n{\n /********************************************************/\n /* not implemented yet - use steepest descent for now */\n //fprintf(stderr,\"Newton direction not implemented yet\\n\");\n //fprintf(stderr,\"Reverting to steepest descent\\n\");\n //steepest_descent_direction(gradient, p_new, N);\n /********************************************************/\n\n /* make a temp copy of the gradient*/\n double *temp_g = opt_allocate(sizeof(*temp_g) * N);\n double *temp_h = opt_allocate(sizeof(*temp_h) * N * N);\n\n memcpy(temp_g, gradient, sizeof(*temp_h) * N );\n\n\n /* need to check if Hessian is PD and modify if not */\n /* Note that this repeated performs a Cholesky factorization on */\n /* the Hessian and will be expensive if N is large */\n /* In those cases, a modified Cholesky factorization (see Nocedal */\n /* and Wright 2006, pp. 52-54) may be a better approach */\n double beta = sqrt(DBL_EPSILON);\n int pd = hessian_modification(hessian, temp_h, N, beta);\n\n /* if we found a pd Hessian approximation, solve system for p */\n /* otherwise, return steepest descent direction */\n if (pd != 1)\n {\n fprintf(stderr,\"Could not find a positive definite \"\n \"Hessian approximation\\n\");\n fprintf(stderr,\"Returning steepest descent direction\\n\");\n }\n else\n {\n /* solve system for p: Hp = -g */\n int nrhs = 1;\n int lda = N;\n int ldb = N;\n LAPACKE_dpotrs(LAPACK_COL_MAJOR, 'L', N, nrhs, temp_h, lda, temp_g, ldb);\n }\n\n /* negate gradient or solution to system */\n int i;\n for (i = 0;i 0)\n {\n /* if it is already pd, min_diag will be positive */\n tau = 0.0;\n }\n else \n {\n tau = - min_diag + beta;\n }\n\n /* add multiples of the identity until hessian is positive definite */\n int k;\n int pd;\n int lda = N;\n for (k=0;k beta ? 2.0 * tau : beta;\n\n }\n /* return 0 if not positive definite */\n return 0;\n \n}\n\n\n/*****************************************************************************/\n/* function for performing line search */\n\n\nvoid line_search(double *x_in, \n double *x_out,\n const int N,\n optimization_parameters *opt_par,\n void *aux\n )\n{\n\n double (*misfit)(const double *, const int, void *) = opt_par->objective;\n void (*grad)(const double *, double *, int, void *) = opt_par->grad;\n void (*hess)(const double *, double *, int, void *) = opt_par->hess;\n\n int success = 0;\n int i,j;\n\n /* note: opt_allocate is the same as malloc, but checks to make sure */ \n /* memory allocate was successful */\n\n double *gradient = opt_allocate(sizeof(*gradient) * N);\n double *grad_old = opt_allocate(sizeof(*grad_old) * N);\n\n double *p = opt_allocate(sizeof(*p) * N);\n double *p_old = opt_allocate(sizeof(*p_old) * N);\n\n double *x_old = opt_allocate(sizeof(*x_old) * N);\n double *x_trial = opt_allocate(sizeof(*x_trial) * N);\n\n double *hessian = NULL;\n if (opt_par->sd == NEWTON)\n hessian = opt_allocate(sizeof(*hessian) * N * N);\n\n /* initial alpha_old and dir_deriv_old to keep the compiler from complaining, */\n /* but these initialization values will never be used */\n double alpha_old = 1;\n double alpha_new;\n\n double dir_deriv_old = 1;\n double dir_deriv_new;\n\n /* copy x_in to x_old */\n for (i=0;istopping_tolerance)\n {\n success = 1;\n free(p);\n free(gradient);\n return;\n }\n\n int m = opt_par->LBFGS_mem;\n\n /* start main loop */\n search_dir sd;\n int max_it = opt_par->max_iterations;\n for (j=0;jsd != NEWTON)\n {\n /* first iteration - use steepest descent */\n /* get steepest descent direction */\n steepest_descent_direction(gradient, p, N);\n sd = STEEPEST;\n dir_deriv_new = vec_dot_prod(gradient, p, N);\n alpha_new = opt_par->initial_step_length;\n }\n else\n {\n if (opt_par->sd == LBFGS)\n {\n LBFGS_direction(gradient, grad_old, x_out, x_old, p, N, m, j);\n \n\n sd = LBFGS;\n dir_deriv_new = vec_dot_prod(gradient, p, N);\n }\n else if (opt_par->sd == CG)\n {\n conjugate_grad_direction(grad_old, gradient, p_old, p, N);\n sd = CG;\n dir_deriv_new = vec_dot_prod(gradient, p, N);\n }\n else if (opt_par->sd == NEWTON)\n {\n /* compute hessian */\n hess(x_out, hessian, N, aux);\n newton_direction(gradient, hessian, N, p);\n sd = NEWTON;\n dir_deriv_new = vec_dot_prod(gradient, p, N);\n }\n\n if (opt_par->sd == STEEPEST || (opt_par->angle_restart_allowed && check_angle_restart(gradient, p, N)))\n {\n steepest_descent_direction(gradient, p, N);\n sd = STEEPEST;\n dir_deriv_new = vec_dot_prod(gradient, p, N);\n }\n\n alpha_new = initial_step_length(sd, alpha_old, dir_deriv_old, dir_deriv_new);\n }\n\n if (opt_par->bracket_only || j==0)\n {\n alpha_new = ls_bracket(x_out, p, N, opt_par, alpha_new, aux);\n }\n else \n {\n alpha_new = back_track(x_out, p, N, opt_par, alpha_new, aux);\n }\n \n\n for (i=0;ibacktrack_only && !opt_par->bracket_only && j!=0)\n {\n /* update model */\n for (i=0;istopping_tolerance)\n {\n success = 1;\n break;\n }\n\n }\n\n \n printf(\"No. iterations: %d\\n\",j);\n\n free(p);\n free(p_old);\n free(gradient);\n free(grad_old);\n free(x_trial);\n free(x_old);\n\n if (hessian)\n free(hessian);\n\n if (!success)\n {\n fprintf(stderr,\"Error: line search failed to find a solution\\n\");\n fprintf(stderr,\"Point returned is not stationary\\n\");\n }\n\n}\n\n\n\n\n\n\n\n/*****************************************************************************/\n\ndouble ls_zoom(const double *x, \n const double *p,\n const int N,\n optimization_parameters *opt_par,\n double a_lo,\n double a_hi,\n void *aux\n )\n{\n double (*misfit)(const double *, const int, void *) = opt_par->objective;\n void (*grad)(const double *, double *, int, void *) = opt_par->grad;\n\n\n int success = 0;\n\n double bb_star = 0.0;\n\n double mf;\n double *gradient = opt_allocate(sizeof(*gradient) * N);\n double *x_update = opt_allocate(sizeof(*x_update) * N);\n\n /* calculate initial misfit and gradient */\n mf = misfit(x, N, aux);\n grad(x, gradient, N, aux);\n\n\n double phi0 = mf;\n double phi_prime0 = vec_dot_prod(gradient, p, N);\n\n\n double phi_aj;\n double phi_prime_aj;\n\n double phi_a_lo;\n \n double mean_step;\n\n double tol = 0;\n\n /* start iterations */\n double a_j;\n int i, j;\n for (i=0;ibracket_zoom_iterations;i++) \n {\n printf(\"Bracket successful, starting zoom, iteration %d\\n\",i);\n printf(\"a_lo, a_hi: %f, %f\\n\", a_lo, a_hi);\n fflush(stdout);\n\n /* check if a_lo and a_hi are too close together */\n mean_step = 0.5 * (a_lo + a_hi);\n if (fabs(a_lo - a_hi) / mean_step < 0.01)\n {\n bb_star = mean_step;\n success = 1;\n break;\n }\n if (mean_step < 1e-6) /* <-- this should really depend on the scaling of the problem */\n {\n success = 0;\n break;\n }\n\n a_j = ls_cubic_interpolation(x, p, N, opt_par, a_lo, a_hi, aux);\n //a_j = (a_lo + a_hi) / 2.0;\n\n tol = mean_step * 0.01; /* one percent of the mean step */\n //fprintf(stderr, \"Trial step: %f\\n\",a_j);\n if (fabs(a_j - a_lo) < tol || fabs(a_j - a_hi) < tol)\n {\n /* too close to boundary of interval */\n //fprintf(stderr,\"ls_zoom: too close to boundary\\n\");\n //success = 0;\n //break;\n a_j = mean_step;\n }\n \n if (isnan(a_j) || isinf(a_j))\n {\n fprintf(stderr,\"nan/inf value\\n\");\n success = 0;\n break;\n }\n\n /* evaluate function at a_lo (don't need dir. derivative) */\n for (j=0;j phi0 + WOLFE_C1 * a_j * phi_prime0\n || phi_aj >= phi_a_lo)\n {\n /* trial step length violates Armijo or */\n /* trial step evaluate to a function value greater than a_lo */\n /* need to reduce step length */\n a_hi = a_j;\n }\n else \n {\n /* trial step length satisfies Armijo and function value is */\n /* less than a_lo */\n /* check curvature */\n grad(x_update, gradient, N, aux);\n phi_prime_aj = vec_dot_prod(gradient, p, N);\n printf(\"Trial step length %E dir deriv: %E\\n\", a_j, phi_prime_aj);\n if (fabs(phi_prime_aj) <= -WOLFE_C2 * phi_prime0)\n {\n /* trial step length satisfies strong curvature condition */\n /* accept trial step length */\n bb_star = a_j;\n success = 1;\n break;\n }\n\n if (phi_prime_aj * (a_hi - a_lo) >= 0)\n {\n a_hi = a_lo;\n }\n\n /* satisfies Armijo, but not curvature */\n /* increase step length */\n a_lo = a_j;\n\n\n }\n }\n\n free(x_update);\n free(gradient);\n\n if (!success)\n {\n fprintf(stderr,\"Line search zoom failed to return an \"\n \"appropriate step length\\n\");\n //exit(-90);\n return -1;\n }\n\n return bb_star;\n}\n\n\n/*****************************************************************************/\n\ndouble ls_cubic_interpolation(const double *x, \n const double *p,\n const int N,\n optimization_parameters *opt_par,\n const double bound1,\n const double bound2,\n void *aux\n )\n{\n /* calculates a new trial step length from cubic interpolation */\n /* interpolation is based on two function values and the */\n /* corresponding directional derivatives */\n /* */\n /* This interpolation requires two function evaluations and */\n /* two gradient evaluations. If the function or gradient is */\n /* expensive to evaluate, there are probably better ways to */\n /* calculate an appropriate step length */\n /* */\n /* see Nocedal and Wright 2006, equation 3.59 */\n /* */\n /* inputs: */ \n /* x: current point in parameter space */\n /* p: search direction */\n /* N: number of dimensions */\n /* misfit: function that takes point and returns objective */\n /* function value. x and N as defined above */\n /* grad: function that takes point and returns gradient */\n /* value (returned as parameter) */\n /* bound1, bound2: bounds of step length search */\n /* */\n /* new trial step length is returned */\n \n \n double (*misfit)(const double *, const int, void *) = opt_par->objective;\n void (*grad)(const double *, double *, int, void *) = opt_par->grad;\n\n\n double *gradient = opt_allocate(sizeof(*gradient) * N);\n double *x_update = opt_allocate(sizeof(*x_update) * N);\n\n double f1, f2, g1, g2;\n\n int i;\n\n /* evaluate objective function and directional derivative at bound1 */\n for (i=0;i bound1 ? 1.0 : -1.0;\n if ((bound2 - bound1) > 0)\n d2_sign = 1.0;\n else if ((bound2 - bound1) < 0)\n d2_sign = -1.0;\n else\n d2_sign = 0.0;\n\n\n double d2 = d2_sign * sqrt(d1 * d1 - g1 * g2);\n\n double a_new = bound2 - (bound2 - bound1) * ((g2 + d2 - d1)/(g2 - g1 + 2 * d2));\n\n /* the minimum is always either at a_new as calculated above orj */\n /* at one of the end points. Check those here. */\n //a_new = (a_new < bound1) ? a_new : bound1;\n //a_new = (a_new < bound2) ? a_new : bound2;\n\n free(x_update);\n free(gradient);\n return a_new;\n}\n\n\n/*****************************************************************************/\n\n\ndouble ls_bracket(const double *x, \n const double *p,\n const int N,\n optimization_parameters *opt_par,\n double alpha0,\n void *aux\n )\n{\n\n double (*misfit)(const double *, const int, void *) = opt_par->objective;\n void (*grad)(const double *, double *, int, void *) = opt_par->grad;\n\n\n int success = 0;\n double b_star;\n\n int steplength_max = 50;\n double beta_max = 5e30;\n double beta0 = 0;\n double beta1 = alpha0; /* initial step length */\n\n double *gradient = opt_allocate(sizeof(*gradient) * N);\n double *x_update = opt_allocate(sizeof(*x_update) * N);\n\n\n double p0; /* phi(0) */\n double pp0; /* phi'(0) */\n /* evaluate objective and dir. derivative at initial point */\n p0 = misfit(x, N, aux);\n grad(x, gradient, N, aux);\n pp0 = vec_dot_prod(gradient, p, N);\n\n\n double pi; /* phi(i) */\n double ppi; /* phi'(i) */\n double pi_1 = p0; /* phi(i-1) */\n //double ppi_1 = pp0; /* phi'(i-1) */\n double b_i = beta1; /* beta_i */\n double b_i_1 = beta0; /* beta_{i-1} */\n \n\n int i, j;\n for (i=0;i p0 + WOLFE_C1 * b_i * pp0) || (pi >= pi_1 && i>0))\n {\n b_star = ls_zoom(x, p, N, opt_par, b_i_1, b_i, aux);\n if (b_star < 0)\n {\n /* ls_zoom failed - try bigger steps */\n b_i = 2 * alpha0;\n b_i_1 = alpha0;\n continue;\n }\n success = 1;\n break;\n }\n\n grad(x_update, gradient, N, aux);\n ppi = vec_dot_prod(gradient, p, N);\n if (fabs(ppi) <= -WOLFE_C2 * pp0)\n {\n b_star = b_i;\n success = 1;\n break;\n }\n\n if (ppi >= 0.0)\n {\n b_star = ls_zoom(x, p, N, opt_par, b_i, b_i_1, aux);\n if (b_star < 0)\n {\n /* ls_zoom failed - try bigger steps */\n b_i = 2 * alpha0;\n b_i_1 = alpha0;\n continue;\n }\n success = 1;\n break;\n }\n\n /* update b_i and b_i_1 */\n b_i_1 = b_i;\n b_i = 2 * b_i;\n\n if (b_i > beta_max)\n {\n fprintf(stderr,\"Error: ls_bracket: max step length reached\\n\");\n success = 0;\n break;\n }\n }\n\n\n free(x_update);\n free(gradient);\n\n\n if (!success)\n {\n fprintf(stderr,\"Line search bracket failed to return an \"\n \"appropriate step length\\n\");\n exit(-90);\n }\n\n printf(\"Step length successfully selected. Step length: %E\\n\",b_star);\n fflush(stdout);\n return b_star;\n}\n\n\n\n\n/*****************************************************************************/\n\nint check_angle_restart(double *grad, double *p, int N)\n{\n int restart = 0;\n double angle_tol_deg = 95.0;\n double angle_tol_rad = angle_tol_deg * (M_PI / 180.0); \n\n double grad_norm = vec_norm(grad, N);\n double p_norm = vec_norm(p, N);\n double pg = vec_dot_prod(p, grad, N);\n double ang = pg / (p_norm * grad_norm);\n if(ang > cos(angle_tol_rad))\n {\n restart = 1;\n }\n\n return restart;\n}\n\n\n/*****************************************************************************/\n\n\ndouble back_track_quad(double phi0, double phip0, double phi_a0, double a0)\n{\n /* see Nodedal and Wright, p. 58 (equation 3.57 and 3.58) */\n\n double a1;\n\n double num = phip0 * a0 * a0;\n double den = phi_a0 - phi0 - phip0 * a0;\n\n a1 = -0.5 * (num / den);\n return a1;\n}\n\n\ndouble back_track_cubic(double phi0, \n double phip0,\n double phi_a0,\n double phi_a1,\n double a0,\n double a1)\n{\n /* see Nocedal and Wright 2006, p. 58 */\n\n\n double a, b, a2;\n\n double a02 = a0 * a0; /* a0 squared */\n double a12 = a1 * a1; /* a1 squared */\n double a03 = a02 * a0; /* a0 cubed */\n double a13 = a12 * a1; /* a1 cubed */ \n\n\n double v1 = phi_a1 - phi0 - phip0 * a1;\n double v2 = phi_a0 - phi0 - phip0 * a0;\n\n double norm = 1.0 / (a02 * a12 * (a1 - a0));\n\n\n a = norm * (a02 * v1 - a12 * v2);\n b = norm * (-a03 * v1 + a13 * v2);\n\n\n a2 = (-b + sqrt(b * b - 3 * a * phip0)) / (3 * a);\n\n return a2;\n}\n\n\n\n\n/*****************************************************************************/\n\n\ndouble back_track(double *x,\n double *p,\n int N,\n optimization_parameters *opt_par,\n double alpha,\n void *aux\n )\n{\n static double a[2]; /* holds a set of step lengths that can be used for bracketing */\n a[0] = 0;\n a[1] = 0;\n\n\n double (*misfit)(const double *, const int, void *) = opt_par->objective;\n void (*grad)(const double *, double *, int, void *) = opt_par->grad;\n\n int i;\n\n double phi0, phip0;\n double a0, a1, a2;\n double phi_a0, phi_a1, phi_a2;\n\n double *gradient = opt_allocate(sizeof(*gradient) * N);\n double *x_update = opt_allocate(sizeof(*x_update) * N);\n\n /* evaluate initial misfit and directional derivative */\n phi0 = misfit(x, N, aux);\n grad(x, gradient, N, aux);\n phip0 = vec_dot_prod(gradient, p, N);\n\n\n /* try a0*/\n a0 = alpha;\n a[1] = a0;\n for (i=0;i= cubic_max)\n {\n fprintf(stderr,\"Backtrack failed to return an \"\n \"appropriate step length\\n\");\n //exit(1);\n }\n\n\n\n free(x_update);\n free(gradient);\n return a2;\n}\n\n\n\n\n\n\n\n\n\n\n/*****************************************************************************/\n\ndouble max3(double x1, double x2, double x3)\n{\n double mm = (x1 > x2) ? x1 : x2;\n mm = (mm > x3) ? mm : x3;\n return mm;\n\n}\n\n\n\nvoid modified_chol(double *A, int N)\n{\n\n /* make temp copy of A */\n double *temp = opt_allocate(sizeof(*temp) * N * N);\n double *c = opt_allocate(sizeof(*c) * N * N);\n double *d = opt_allocate(sizeof(*d) * N);\n memcpy(temp, A, sizeof(*temp) * N *N);\n\n\n int i, j, s;\n\n double sum = 0;\n\n double beta = 1.0;\n double delta = 1.0e-3;\n double theta = 0.0;\n\n for (j = 0; j < N; j++)\n {\n for (s=0;s c[i+j*N] ? theta : c[i+j*N];\n A[i+j*N] = c[i+j*N] / d[j];\n }\n }\n\n for (j=0;j\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* function to be fitted */\ndouble\nfunc(const double t)\n{\n double x = sin(10.0 * t);\n return exp(x*x*x);\n}\n\n/* construct a row of the least squares matrix */\nint\nbuild_row(const double t, gsl_vector *row)\n{\n const size_t p = row->size;\n double Xj = 1.0;\n size_t j;\n\n for (j = 0; j < p; ++j)\n {\n gsl_vector_set(row, j, Xj);\n Xj *= t;\n }\n\n return 0;\n}\n\nint\nsolve_system(const int print_data, const gsl_multilarge_linear_type * T,\n const double lambda, const size_t n, const size_t p,\n gsl_vector * c)\n{\n const size_t nblock = 5; /* number of blocks to accumulate */\n const size_t nrows = n / nblock; /* number of rows per block */\n gsl_multilarge_linear_workspace * w =\n gsl_multilarge_linear_alloc(T, p);\n gsl_matrix *X = gsl_matrix_alloc(nrows, p);\n gsl_vector *y = gsl_vector_alloc(nrows);\n gsl_rng *r = gsl_rng_alloc(gsl_rng_default);\n const size_t nlcurve = 200;\n gsl_vector *reg_param = gsl_vector_alloc(nlcurve);\n gsl_vector *rho = gsl_vector_alloc(nlcurve);\n gsl_vector *eta = gsl_vector_alloc(nlcurve);\n size_t rowidx = 0;\n double rnorm, snorm, rcond;\n double t = 0.0;\n double dt = 1.0 / (n - 1.0);\n\n while (rowidx < n)\n {\n size_t nleft = n - rowidx; /* number of rows left to accumulate */\n size_t nr = GSL_MIN(nrows, nleft); /* number of rows in this block */\n gsl_matrix_view Xv = gsl_matrix_submatrix(X, 0, 0, nr, p);\n gsl_vector_view yv = gsl_vector_subvector(y, 0, nr);\n size_t i;\n\n /* build (X,y) block with 'nr' rows */\n for (i = 0; i < nr; ++i)\n {\n gsl_vector_view row = gsl_matrix_row(&Xv.matrix, i);\n double fi = func(t);\n double ei = gsl_ran_gaussian (r, 0.1 * fi); /* noise */\n double yi = fi + ei;\n\n /* construct this row of LS matrix */\n build_row(t, &row.vector);\n\n /* set right hand side value with added noise */\n gsl_vector_set(&yv.vector, i, yi);\n\n if (print_data && (i % 100 == 0))\n printf(\"%f %f\\n\", t, yi);\n\n t += dt;\n }\n\n /* accumulate (X,y) block into LS system */\n gsl_multilarge_linear_accumulate(&Xv.matrix, &yv.vector, w);\n\n rowidx += nr;\n }\n\n if (print_data)\n printf(\"\\n\\n\");\n\n /* compute L-curve */\n gsl_multilarge_linear_lcurve(reg_param, rho, eta, w);\n\n /* solve large LS system and store solution in c */\n gsl_multilarge_linear_solve(lambda, c, &rnorm, &snorm, w);\n\n /* compute reciprocal condition number */\n gsl_multilarge_linear_rcond(&rcond, w);\n\n fprintf(stderr, \"=== Method %s ===\\n\", gsl_multilarge_linear_name(w));\n fprintf(stderr, \"condition number = %e\\n\", 1.0 / rcond);\n fprintf(stderr, \"residual norm = %e\\n\", rnorm);\n fprintf(stderr, \"solution norm = %e\\n\", snorm);\n\n /* output L-curve */\n {\n size_t i;\n for (i = 0; i < nlcurve; ++i)\n {\n printf(\"%.12e %.12e %.12e\\n\",\n gsl_vector_get(reg_param, i),\n gsl_vector_get(rho, i),\n gsl_vector_get(eta, i));\n }\n printf(\"\\n\\n\");\n }\n\n gsl_matrix_free(X);\n gsl_vector_free(y);\n gsl_multilarge_linear_free(w);\n gsl_rng_free(r);\n gsl_vector_free(reg_param);\n gsl_vector_free(rho);\n gsl_vector_free(eta);\n\n return 0;\n}\n\nint\nmain(int argc, char *argv[])\n{\n const size_t n = 50000; /* number of observations */\n const size_t p = 16; /* polynomial order + 1 */\n double lambda = 0.0; /* regularization parameter */\n gsl_vector *c_tsqr = gsl_vector_alloc(p);\n gsl_vector *c_normal = gsl_vector_alloc(p);\n\n if (argc > 1)\n lambda = atof(argv[1]);\n\n /* solve system with TSQR method */\n solve_system(1, gsl_multilarge_linear_tsqr, lambda, n, p, c_tsqr);\n\n /* solve system with Normal equations method */\n solve_system(0, gsl_multilarge_linear_normal, lambda, n, p, c_normal);\n\n /* output solutions */\n {\n gsl_vector *v = gsl_vector_alloc(p);\n double t;\n\n for (t = 0.0; t <= 1.0; t += 0.01)\n {\n double f_exact = func(t);\n double f_tsqr, f_normal;\n\n build_row(t, v);\n gsl_blas_ddot(v, c_tsqr, &f_tsqr);\n gsl_blas_ddot(v, c_normal, &f_normal);\n\n printf(\"%f %e %e %e\\n\", t, f_exact, f_tsqr, f_normal);\n }\n\n gsl_vector_free(v);\n }\n\n gsl_vector_free(c_tsqr);\n gsl_vector_free(c_normal);\n\n return 0;\n}\n", "meta": {"hexsha": "82820559f5975f6638ba3236a9bb1a22d593cef9", "size": 4548, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc_texinfo/examples/largefit.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/largefit.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/largefit.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.1379310345, "max_line_length": 80, "alphanum_fraction": 0.6097185576, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7124417852733996}} {"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2017 by Synge Todo \n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include \n#include \n#include \n\nint imax(int x, int y) { return (x > y) ? x : y; }\n\nint main(int argc, char** argv) {\n int n = 5;\n int i, j, info;\n double norm;\n double *w;\n double **a, **u, **t;\n\n if (argc > 1) n = atoi(argv[1]);\n \n /* generate matrix */\n a = alloc_dmatrix(n, n);\n for (j = 0; j < n; ++j) {\n for (i = 0; i < n; ++i) {\n mat_elem(a, i, j) = n - imax(i, j);\n }\n }\n printf(\"Matrix A: \");\n fprint_dmatrix(stdout, n, n, a);\n\n /* diagonalization */\n u = alloc_dmatrix(n, n);\n cblas_dcopy(n * n, mat_ptr(a), 1, mat_ptr(u), 1);\n w = alloc_dvector(n);\n info = LAPACKE_dsyev(LAPACK_COL_MAJOR, 'V', 'U', n, mat_ptr(u), n, vec_ptr(w));\n if (info != 0) {\n fprintf(stderr, \"Error: dsyev fails with error code %d\\n\", info);\n exit(255);\n }\n printf(\"Eigenvalues: \");\n fprint_dvector(stdout, n, w);\n printf(\"Eigenvectors: \");\n fprint_dmatrix(stdout, n, n, u);\n\n /* orthogonality check */\n t = alloc_dmatrix(n, n);\n cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n, n, n, 1, mat_ptr(u), n,\n mat_ptr(u), n, 0, mat_ptr(t), n);\n for (i = 0; i < n; ++i) mat_elem(t, i, i) -= 1;\n norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', n, n, mat_ptr(t), n);\n printf(\"|| U^t U - I || = %e\\n\", norm);\n if (norm > 1e-10) {\n fprintf(stderr, \"Error: orthogonality check\\n\");\n exit(255);\n }\n\n /* eigenvalue check */\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1, mat_ptr(a), n,\n mat_ptr(u), n, 0, mat_ptr(t), n);\n cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n, n, n, 1, mat_ptr(u), n,\n mat_ptr(t), n, 0, mat_ptr(a), n);\n for (i = 0; i < n; ++i) mat_elem(a, i, i) -= w[i];\n norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', n, n, mat_ptr(a), n);\n printf(\"|| U^t A U - diag(w) || = %e\\n\", norm);\n if (norm > 1e-10) {\n fprintf(stderr, \"Error: eigenvalue check\\n\");\n exit(255);\n }\n\n free_dmatrix(a);\n free_dmatrix(u);\n free_dvector(w);\n free_dmatrix(t);\n return 0;\n}\n", "meta": {"hexsha": "7f301933b0cc60b5c7cf23946fa54d0ffd17f770", "size": 2483, "ext": "c", "lang": "C", "max_stars_repo_path": "example/lapack/dsyev.c", "max_stars_repo_name": "t-sakashita/rokko", "max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z", "max_issues_repo_path": "example/lapack/dsyev.c", "max_issues_repo_name": "t-sakashita/rokko", "max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z", "max_forks_repo_path": "example/lapack/dsyev.c", "max_forks_repo_name": "t-sakashita/rokko", "max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z", "avg_line_length": 30.2804878049, "max_line_length": 83, "alphanum_fraction": 0.5529601289, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7120673233986519}} {"text": "/*\n * Copyright (C) 2015 University of Oregon\n *\n * You may distribute under the terms of either the GNU General Public\n * License or the Apache License, as specified in the LICENSE file.\n *\n * For more information, see the LICENSE file.\n */\n\n#include \n#include \n#include \n\n\nvoid vnmr_svd(double **a, int irow, int jcol, double w[], double **v)\n{\n gsl_matrix *gA;\n gsl_matrix *gV;\n gsl_vector *gS;\n int i,j;\n int res;\n gA = gsl_matrix_alloc(irow,jcol);\n for (i=0; i\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"roots.h\"\n\ntypedef struct\n {\n double f_lower, f_upper;\n }\nbisection_state_t;\n\nstatic int bisection_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper);\nstatic int bisection_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper);\n\nstatic int\nbisection_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper)\n{\n bisection_state_t * state = (bisection_state_t *) vstate;\n\n double f_lower, f_upper ;\n\n *root = 0.5 * (x_lower + x_upper) ;\n\n SAFE_FUNC_CALL (f, x_lower, &f_lower);\n SAFE_FUNC_CALL (f, x_upper, &f_upper);\n \n state->f_lower = f_lower;\n state->f_upper = f_upper;\n\n if ((f_lower < 0.0 && f_upper < 0.0) || (f_lower > 0.0 && f_upper > 0.0))\n {\n GSL_ERROR (\"endpoints do not straddle y=0\", GSL_EINVAL);\n }\n\n return GSL_SUCCESS;\n\n}\n\nstatic int\nbisection_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper)\n{\n bisection_state_t * state = (bisection_state_t *) vstate;\n\n double x_bisect, f_bisect;\n\n const double x_left = *x_lower ;\n const double x_right = *x_upper ;\n\n const double f_lower = state->f_lower; \n const double f_upper = state->f_upper;\n\n if (f_lower == 0.0)\n {\n *root = x_left ;\n *x_upper = x_left;\n return GSL_SUCCESS;\n }\n \n if (f_upper == 0.0)\n {\n *root = x_right ;\n *x_lower = x_right;\n return GSL_SUCCESS;\n }\n \n x_bisect = (x_left + x_right) / 2.0;\n \n SAFE_FUNC_CALL (f, x_bisect, &f_bisect);\n \n if (f_bisect == 0.0)\n {\n *root = x_bisect;\n *x_lower = x_bisect;\n *x_upper = x_bisect;\n return GSL_SUCCESS;\n }\n \n /* Discard the half of the interval which doesn't contain the root. */\n \n if ((f_lower > 0.0 && f_bisect < 0.0) || (f_lower < 0.0 && f_bisect > 0.0))\n {\n *root = 0.5 * (x_left + x_bisect) ;\n *x_upper = x_bisect;\n state->f_upper = f_bisect;\n }\n else\n {\n *root = 0.5 * (x_bisect + x_right) ;\n *x_lower = x_bisect;\n state->f_lower = f_bisect;\n }\n\n return GSL_SUCCESS;\n}\n\n\nstatic const gsl_root_fsolver_type bisection_type =\n{\"bisection\", /* name */\n sizeof (bisection_state_t),\n &bisection_init,\n &bisection_iterate};\n\nconst gsl_root_fsolver_type * gsl_root_fsolver_bisection = &bisection_type;\n", "meta": {"hexsha": "9665b736997c06520f5f7b9996622351a6a500dd", "size": 3457, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/roots/bisection.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/roots/bisection.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/roots/bisection.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 25.6074074074, "max_line_length": 114, "alphanum_fraction": 0.6592421174, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7113347290135689}} {"text": "/*\n * Simple example of NLopt usage from:\n * http://nlopt.readthedocs.io/en/latest/NLopt_Tutorial/\n */\n#include \n#include \n#include \n\nint count = 0;\n\n//\n// Objective function.\n//\ndouble myfunc(unsigned n, const double *x, double *grad, void *my_func_data)\n{\n count++;\n if (grad) {\n grad[0] = 0.0;\n grad[1] = 0.5 / sqrt(x[1]);\n }\n return sqrt(x[1]);\n}\n\ntypedef struct {\n double a, b;\n} my_constraint_data;\n\n//\n// Constraint function.\n//\ndouble myconstraint(unsigned n, const double *x, double *grad, void *data)\n{\n my_constraint_data *d = (my_constraint_data*) data;\n double a = d->a,\n b = d->b;\n if (grad) {\n grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);\n grad[1] = -1.0;\n }\n return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);\n}\n\nint main()\n{\n // Select algorithm.\n\n //\n // Global optimization\n //\n// nlopt_algorithm algorithm = NLOPT_GN_DIRECT; // DIviding RECTangles algorithm for global optimization\n// nlopt_algorithm algorithm = NLOPT_GN_DIRECT_L; // locally biased variant of DIRECT\n// nlopt_algorithm algorithm = NLOPT_GN_DIRECT_L_RAND; // slightly randomized variant of DIRECT-L\n// nlopt_algorithm algorithm = NLOPT_GN_CRS2_LM; // Controlled Random Search with local mutation\n// nlopt_algorithm algorithm = NLOPT_G_MLSL; // Multi-Level Single-Linkage\n// nlopt_algorithm algorithm = NLOPT_G_MLSL_LDS; // modification of MLSL with low-discrepancy sequence\n// nlopt_algorithm algorithm = NLOPT_GD_STOGO; // StoGO\n// nlopt_algorithm algorithm = NLOPT_GD_STOGO_RAND; // randomized variant of StoGO\n// nlopt_algorithm algorithm = NLOPT_GN_ISRES; // Improved Stochastic Ranking Evolution Strategy\n// nlopt_algorithm algorithm = NLOPT_GN_ESCH; // evolutionary algorithm\n\n //\n // Local derivative-free optimization\n //\n// nlopt_algorithm algorithm = NLOPT_LN_COBYLA; // Constrained Optimization BY Linear Approximations\n// nlopt_algorithm algorithm = NLOPT_LN_BOBYQA; // BOBYQA, iterative quadratic approximation\n// nlopt_algorithm algorithm = NLOPT_LN_NEWUOA; // NEWUOA, quadratic approximation\n// nlopt_algorithm algorithm = NLOPT_LN_NEWUOA_BOUND; // variant of NEWUOA with bound constraints\n// nlopt_algorithm algorithm = NLOPT_LN_PRAXIS; // PRincipal AXIS\n// nlopt_algorithm algorithm = NLOPT_LN_NELDERMEAD; // Nelder-Mead Simplex\n// nlopt_algorithm algorithm = NLOPT_LN_SBPLX; // re-implementation of Subplex algorithm\n\n //\n // Local gradient-based optimization\n //\n nlopt_algorithm algorithm = NLOPT_LD_MMA; // Method of Moving Asymptotes\n// nlopt_algorithm algorithm = NLOPT_LD_CCSAQ; // conservative convex separable approximation, quadratic\n// nlopt_algorithm algorithm = NLOPT_LD_SLSQP; // Sequential Least-Squares Quadratic Programming\n// nlopt_algorithm algorithm = NLOPT_LD_LBFGS; // Low-storage BFGS\n// nlopt_algorithm algorithm = NLOPT_LD_TNEWTON; // Truncated Newton\n// nlopt_algorithm algorithm = NLOPT_LD_VAR1; // shifted limited-memory variable-metric algorithm, rank-1\n// nlopt_algorithm algorithm = NLOPT_LD_VAR2; // shifted limited-memory variable-metric algorithm, rank-2\n\n // Create optimizer object.\n // Select dimensionality.\n nlopt_opt opt = nlopt_create(algorithm, 2);\n\n // Set objective function.\n nlopt_set_min_objective(opt, myfunc, NULL);\n\n // Specify bounds.\n double lb[2] = { -HUGE_VAL, 0 }; // lower bounds\n nlopt_set_lower_bounds(opt, lb);\n //TODO: nlopt_set_upper_bounds();\n\n // Add constraints.\n my_constraint_data data[2] = { {2, 0}, {-1, 1} };\n nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);\n nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);\n\n // Stopping criteria, or. a relative tolerance on the optimization parameters.\n nlopt_set_xtol_rel(opt, 1e-4);\n\n // Perform the optimization, starting with some initial guess.\n double x[2] = { 1.234, 5.678 }; // initial guess\n double minf; // the minimum objective value upon return\n\n if (nlopt_optimize(opt, x, &minf) < 0) {\n printf(\"nlopt failed!\\n\");\n } else {\n printf(\"found minimum after %d evaluations\\n\", count);\n printf(\"found minimum at f(%g, %g) = %0.10g\\n\", x[0], x[1], minf);\n }\n\n nlopt_destroy(opt);\n return 0;\n}\n", "meta": {"hexsha": "79cca56a6a49b54735e9ee4515612fed72c3095f", "size": 4478, "ext": "c", "lang": "C", "max_stars_repo_path": "languages/c-language/nlopt-example.c", "max_stars_repo_name": "sergev/vak-opensource", "max_stars_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2016-10-29T19:50:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T21:27:43.000Z", "max_issues_repo_path": "languages/c-language/nlopt-example.c", "max_issues_repo_name": "sergev/vak-opensource", "max_issues_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "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": "languages/c-language/nlopt-example.c", "max_forks_repo_name": "sergev/vak-opensource", "max_forks_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2017-06-19T23:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-13T15:00:41.000Z", "avg_line_length": 38.2735042735, "max_line_length": 115, "alphanum_fraction": 0.6670388566, "num_tokens": 1272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7108222978019846}} {"text": "#pragma once\n\n#include \n#include \n\n#include \n\n\n#include \n#include \n\n\n#include \n#include \n\n#include \n\n#define VECTOR_AT(v, i) (*((v->data + (i * v->tda ))))\n\n/*====================================================================================================================================================================*\n | This class will be used to represent matrices of arbitrary sizes (m rows by n columns) that have elements of type double. The underlying data strucutre used by |\n | this class is gsl's (Gnu Scientific Library) matrix class. This class also makes use of the ATLAS implementation of BLAS for some operations such as matrix-matrix |\n | multiplication. This class is meant to improve performance, not necessarily ease of use. |\n *====================================================================================================================================================================*/\n\nclass MATHLIB_DECLSPEC Vector : public Matrix{\npublic:\n\t/**\n\t\tconstructor - creates an n row vector that is not initialized to any particular values\n\t*/\n\tVector(int n);\n\n\t/**\n\t\tdefault constructor\n\t*/\n\tVector();\n\n\t/**\n\t\tcopy constructor - performs a deep copy of the matrix passed in as a parameter.\n\t*/\n\tVector(const Vector& other);\n\n\t/**\n\t\tdestructor.\n\t*/\n\t~Vector();\n\n\t/**\n\t\tcopy operator - performs a deep copy of the Vector passed in as a parameter.\n\t*/\n\tVector& operator=(const Vector &other);\n\n\t/**\n\t\tcopy operator - performs a deep copy of the Vector passed in as a parameter.\n\t*/\n\tVector& operator=(const Matrix &other);\t\n\n\t/**\n\t\tthis method performs a shallow copy of the Vector that is passed in as a parameter.\n\t*/\n\tvoid shallowCopy(const Matrix& other);\n\n\t/**\n\t\tthis method performs a deep copy of the vector that is passed in as a paramerer.\n\t*/\n\tvoid deepCopy(const Matrix& other);\n\n\t/**\n\t\tThis method sets the current vector to be equal to one of the products: A * b or A'*b.\n\t\tThe value of transA indicates if A is transposed or not\n\t*/\n\tvoid setToProductOf(const Matrix& A, const Matrix& B, bool transA = false, bool transB = false);\n\n\n\t/**\n\t\tThis method sets the current vector to be equal to one of the rows of A - shallow column only!\n\t*/\n\tvoid setToRow(const Matrix& A, int row, int start = 0, int howMany = -1);\n\n\t/**\n\t\tThis method sets the current vector to be equal to one of the cols of A - shallow column only!\n\t*/\n\tvoid setToCol(const Matrix& A, int col, int start = 0, int howMany = -1);\n\n\t/**\n\t\tThis method prints the contents of the matrix - testing purpose only.\n\t*/\n\tvoid printVector() const;\n\n\t/**\n\t\tThis method returns a copy of the value of the matrix at (i,j)\n\t*/\n\tdouble get(int i) const;\n\n\t/**\n\t\tThis method sets the value of the matrix at (i,j) to newVal.\n\t*/\n\tvoid set(int i, double newVal);\n\n\t/**\n\t\tComputes the 2-norm squared for the current vector.\n\t*/\n\tinline double normSquared(){\n\t\tint r = getRowCount();\n\t\tdouble result = 0;\n\t\tfor (int i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n\nclass matrixBoost{\n private:\n\n boost::numeric::ublas::matrix value;\n\t\tboost::numeric::ublas::range r1;\n\t\tboost::numeric::ublas::range r2;\n\t\tboost::numeric::ublas::matrixvalBack;\n\t\tbool subMatrixCopy = false;\n\n\t\t//http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?LU_Matrix_Inversion\n\t\tbool InvertMatrix(const boost::numeric::ublas::matrix& input, boost::numeric::ublas::matrix& inverse) {\n\t\t\tusing namespace boost::numeric::ublas;\n\t\t\ttypedef permutation_matrix pmatrix;\n\t\t\t// create a working copy of the input\n\t\t\tmatrix A(input);\n\t\t\t// create a permutation matrix for the LU-factorization\n\t\t\tpmatrix pm(A.size1());\n\t\t\t// perform LU-factorization\n\t\t\tint res = lu_factorize(A,pm);\n\t\t\tif( res != 0 ) return false;\n\t\t\t// create identity matrix of \"inverse\"\n\t\t\tinverse.assign(boost::numeric::ublas::identity_matrix(A.size1()));\n\t\t\t// backsubstitute to get the inverse\n\t\t\tlu_substitute(A, pm, inverse);\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid setSystemValue(boost::numeric::ublas::matrix v){\n\t\t\tvalue = v;\n\t\t}\n\n public:\n matrixBoost(){}\n\n\t\tmatrixBoost(int rowCount, int colCount){\n\t\t\tvalue = boost::numeric::ublas::zero_matrix(rowCount,colCount);\n\t\t}\n\n matrixBoost(boost::numeric::ublas::matrix value):value(value){}\n\n static matrixBoost Identity(int dimension,int dimension2){\n return matrixBoost(boost::numeric::ublas::identity_matrix(dimension,dimension2));\n }\n\n matrixBoost transpose(){\n matrixBoost t(boost::numeric::ublas::trans(value));\n return t;\n }\n\n matrixBoost inverse(){\n\t\t\tboost::numeric::ublas::matrix inverse(value.size1(),value.size2());\n\t\t\tInvertMatrix(value,inverse);\n matrixBoost t(inverse);\n return t;\n }\n\n boost::numeric::ublas::matrix getSystemValue() const{\n return value;\n }\n\t\t\n\t\tmatrixBoost & block(int i1, int i2, int l1, int l2){\n\t\t\tif(subMatrixCopy){\n\t\t\t\tstd::swap(valBack,value);\n\t\t\t}\n\t\t\tsubMatrixCopy = true;\n\t\t\tr1 = boost::numeric::ublas::range(i1,i1+l1);\n\t\t\tr2 = boost::numeric::ublas::range(i2,i2+l2);\n\t\t\tvalBack = boost::numeric::ublas::project(value,r1,r2);\n\t\t\tstd::swap(valBack,value);\n\t\t\treturn *this;\n\t\t}\n\n\t\tmatrixBoost &operator=( const matrixBoost other){\n\t\t\tif(subMatrixCopy){\n\t\t\t\tsubMatrixCopy = false;\n\t\t\t\tboost::numeric::ublas::project(valBack,r1,r2) = other.getSystemValue();\n\t\t\t\tstd::swap(valBack,value);\n\t\t\t}else{\n\t\t\t\tvalue = other.getSystemValue();\n\t\t\t}\n\t\t\treturn *this;//better be no chaining of equal signs\n\t\t}\n\n\t\tstatic void lowerTriangulate(matrixBoost & val){\n\t\t\tboost::numeric::ublas::matrix in= val.getSystemValue();\n\t\t\tint rows = in.size1();\n\t\t\tint cols = in.size2();\n\t\t\tfor(int i = 0; i < rows; i++){\n\t\t\t\tint length = cols - i;\n\t\t\t\tboost::numeric::ublas::vector v = (row(in,i));\n\t\t\t\tv = boost::numeric::ublas::subrange(v,i,cols);\n\t\t\t\tdouble mew = boost::numeric::ublas::norm_2(v);\n\t\t\t\tif(mew!=0){\n\t\t\t\t\tdouble beta = v(0) + (-2*(v(0) < 0)+1)*mew;\n\t\t\t\t\tv = v/beta;\n\t\t\t\t}\n\t\t\t\tv(0) = 1;\n\t\t\t\tboost::numeric::ublas::range t1(i,rows);\n\t\t\t\tboost::numeric::ublas::range t2(i,cols);\n\t\t\t\tboost::numeric::ublas::vector w = -2.0/\n\t\t\t\t\t(boost::numeric::ublas::norm_2(v)*boost::numeric::ublas::norm_2(v))*\n\t\t\t\t\t(prod(project(in,t1,t2),v));\n\t\t\t\t\n\t\t\t\tboost::numeric::ublas::matrix vM(v.size(),1);\n\t\t\t\tfor(int i = 0; i < v.size(); i++){\n\t\t\t\t\tvM(i,0) = v(i); \n\t\t\t\t}\n\t\t\t\tboost::numeric::ublas::matrix wM(w.size(),1);\n\t\t\t\tfor(int i = 0; i < w.size(); i++){\n\t\t\t\t\twM(i,0) = w(i);\n\t\t\t\t}\n\t\t\t\tproject(in,t1,t2) = project(in,t1,t2) + prod(wM,boost::numeric::ublas::trans(vM));\t\n\t\t\t}\n\t\t\tval.setSystemValue(in);\n\t\t}\n};\n\nclass vectorBoost{\n private:\n\t\tboost::numeric::ublas::vector value;\n public:\n vectorBoost(){\n }\n\n vectorBoost(boost::numeric::ublas::vector value):value(value){}\n\n boost::numeric::ublas::vector getSystemValue() const{\n return value;\n }\n\t\n\t\tstatic vectorBoost randomVector(int dimension,uint32_t seed){\n\t\t\tstd::mt19937 generator(seed);\n\t\t\tstd::normal_distribution distribution(0.0,1.0);\n\t\t\tboost::numeric::ublas::vector tmp(dimension);\n\t\t\tfor(int i = 0; i < dimension; i++){\n\t\t\t\ttmp(i) = distribution(generator);\n\t\t\t}\n\t\t\treturn vectorBoost(tmp);\n\t\t}\n\n\t\tstatic vectorBoost solve(matrixBoost A, vectorBoost b){\n\t\t\tboost::numeric::ublas::matrix Alocal = A.getSystemValue();\n\t\t\tboost::numeric::ublas::vector blocal = b.getSystemValue();\n\t\t\tboost::numeric::ublas::permutation_matrix pm(Alocal.size1());\n\n\t\t\tboost::numeric::ublas::lu_factorize(Alocal,pm);\n\t\t\tboost::numeric::ublas::lu_substitute(Alocal, pm, blocal);\n\t\t\treturn vectorBoost(blocal);\n\t\t}\t\n};\n\n\nvectorBoost operator-(const vectorBoost &lhs,const vectorBoost &rhs){\n vectorBoost res(lhs.getSystemValue() - rhs.getSystemValue());\n return res;\n};\n\nvectorBoost operator+(const vectorBoost &lhs,const vectorBoost &rhs){\n vectorBoost res(lhs.getSystemValue() + rhs.getSystemValue());\n return res;\n};\n\nstd::ostream& operator<<(std::ostream& stream, const vectorBoost & vec) {\n\tboost::numeric::ublas::vector v = vec.getSystemValue(); \n\tfor(int i = 0; i < v.size()-1; i++){\n\t\tstream< m = mat.getSystemValue(); \n\tfor(int i = 0; i < m.size1(); i++){\n\t\tfor(int j = 0; j < m.size2(); j++){\n\t\t\tstream<\r\n#include \r\n\r\nint main(void)\r\n{\r\n double data[5] = {17.2, 18.1, 16.5, 18.3, 12.6};\r\n double mean, variance, largest, smallest;\r\n\r\n mean = gsl_stats_mean(data, 1, 5);\r\n variance = gsl_stats_variance(data, 1, 5);\r\n largest = gsl_stats_max(data, 1, 5);\r\n smallest = gsl_stats_min(data, 1, 5);\r\n\r\n printf (\"The dataset is %g, %g, %g, %g, %g\\n\",\r\n data[0], data[1], data[2], data[3], data[4]);\r\n\r\n printf (\"The sample mean is %g\\n\", mean);\r\n printf (\"The estimated variance is %g\\n\", variance);\r\n printf (\"The largest value is %g\\n\", largest);\r\n printf (\"The smallest value is %g\\n\", smallest);\r\n return 0;\r\n}\r\n", "meta": {"hexsha": "f5a7558a7b6e52fec2399901a2d954d31bf28da1", "size": 674, "ext": "c", "lang": "C", "max_stars_repo_path": "notebook/demo/src/gsl-example.c", "max_stars_repo_name": "marketmodelbrokendown/1", "max_stars_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebook/demo/src/gsl-example.c", "max_issues_repo_name": "marketmodelbrokendown/1", "max_issues_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-18T21:55:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-18T21:55:20.000Z", "max_forks_repo_path": "notebook/demo/src/gsl-example.c", "max_forks_repo_name": "marketmodelbrokendown/1", "max_forks_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0833333333, "max_line_length": 55, "alphanum_fraction": 0.5994065282, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474246069458, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.709463436332913}} {"text": "/* vectorviews.c */\n\n// 8.4.13 Example programs for matrices of gsl-ref.pdf\n// GNU GSL GNU Scientific Library reference book\n// pp. 99,100\n\n/*\n Compiling advice:\n gcc vectorviews.c -lgsl -lgslcblas -lm\n\n */\n\n#include \n#include \n#include \n#include \n\nint main (void)\n{\n size_t i,j;\n\n gsl_matrix *m = gsl_matrix_alloc(10,10);\n\n for (i = 0; i < 10; i++)\n for (j = 0; j < 10; j++)\n gsl_matrix_set (m, i, j, sin(i) + cos(j));\n\n for (j = 0; j < 10; j++)\n {\n gsl_vector_view column = gsl_matrix_column(m, j);\n double d;\n\n d = gsl_blas_dnrm2 (&column.vector);\n\n printf(\"matrix column %zu, norm = %g\\n\", j, d);\n }\n\n gsl_matrix_free(m);\n\n return 0;\n}\n\n", "meta": {"hexsha": "dd1799286a2cda22913587d917d3c966cc886f19", "size": 734, "ext": "c", "lang": "C", "max_stars_repo_path": "gslExamples/vectorviews.c", "max_stars_repo_name": "ernestyalumni/CompPhys", "max_stars_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2017-07-24T04:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T16:00:41.000Z", "max_issues_repo_path": "gslExamples/vectorviews.c", "max_issues_repo_name": "ernestyalumni/CompPhys", "max_issues_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-01-16T22:34:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-29T22:37:10.000Z", "max_forks_repo_path": "gslExamples/vectorviews.c", "max_forks_repo_name": "ernestyalumni/CompPhys", "max_forks_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2017-01-24T19:18:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-01T07:13:35.000Z", "avg_line_length": 17.0697674419, "max_line_length": 55, "alphanum_fraction": 0.5940054496, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7093955132988363}} {"text": "#include \n#include \n\nint main(int argc, char *argv[])\n{\n /* 0 + 2x - 3x^2 + 1x^3 */\n double p[] = {0, 2, -3, 1};\n double z[6];\n gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc(4);\n gsl_poly_complex_solve(p, 4, w, z);\n gsl_poly_complex_workspace_free(w);\n\n for(int i = 0; i < 3; ++i)\n printf(\"%.12f\\n\", z[2 * i]);\n\n return 0;\n}\n", "meta": {"hexsha": "3bc63c8f43cb4f93d5542105ad7abf4e7b8f5c5d", "size": 400, "ext": "c", "lang": "C", "max_stars_repo_path": "lang/C/roots-of-a-function-2.c", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-06-10T14:21:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-26T18:52:29.000Z", "max_issues_repo_path": "lang/C/roots-of-a-function-2.c", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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": "lang/C/roots-of-a-function-2.c", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 22.2222222222, "max_line_length": 72, "alphanum_fraction": 0.5775, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7076970863348958}} {"text": "/* specfunc/gsl_sf_coupling.h\n * \n * Copyright (C) 1996,1997,1998,1999,2000,2001,2002 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#ifndef __GSL_SF_COUPLING_H__\n#define __GSL_SF_COUPLING_H__\n\n#include \n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n\n/* 3j Symbols: / ja jb jc \\\n * \\ ma mb mc /\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_coupling_3j_e(int two_ja, int two_jb, int two_jc,\n int two_ma, int two_mb, int two_mc,\n gsl_sf_result * result\n );\ndouble gsl_sf_coupling_3j(int two_ja, int two_jb, int two_jc,\n int two_ma, int two_mb, int two_mc\n );\n\n\n/* 6j Symbols: / ja jb jc \\\n * \\ jd je jf /\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_coupling_6j_e(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf,\n gsl_sf_result * result\n );\ndouble gsl_sf_coupling_6j(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf\n );\n\n/* Racah W coefficients:\n *\n * W(a b c d; e f) = (-1)^{a+b+c+d} / a b e \\\n * \\ d c f /\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_coupling_RacahW_e(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf,\n gsl_sf_result * result\n );\ndouble gsl_sf_coupling_RacahW(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf\n );\n\n\n/* 9j Symbols: / ja jb jc \\\n * | jd je jf |\n * \\ jg jh ji /\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_coupling_9j_e(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf,\n int two_jg, int two_jh, int two_ji,\n gsl_sf_result * result\n );\ndouble gsl_sf_coupling_9j(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf,\n int two_jg, int two_jh, int two_ji\n );\n\n\n/* INCORRECT version of 6j Symbols:\n * This function actually calculates\n * / ja jb je \\\n * \\ jd jc jf /\n * It represents the original implementation,\n * which had the above permutation of the\n * arguments. This was wrong and confusing,\n * and I had to fix it. Sorry for the trouble.\n * [GJ] Tue Nov 26 12:53:39 MST 2002\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\n#ifndef GSL_DISABLE_DEPRECATED\nint gsl_sf_coupling_6j_INCORRECT_e(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf,\n gsl_sf_result * result\n );\ndouble gsl_sf_coupling_6j_INCORRECT(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf\n );\n#endif /* !GSL_DISABLE_DEPRECATED */\n\n\n__END_DECLS\n\n#endif /* __GSL_SF_COUPLING_H__ */\n", "meta": {"hexsha": "bd6b58372302cbfee5da490258797dd62234cda9", "size": 4165, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_coupling.h", "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_coupling.h", "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_coupling.h", "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "avg_line_length": 33.0555555556, "max_line_length": 81, "alphanum_fraction": 0.5740696279, "num_tokens": 1096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7061603616615507}} {"text": "#include \n#include \n#include \n#include \n#define ABS(a) (((a) < 0) ? -(a) : (a))\n\nint main()\n{\n /*\n *\thbar^2/2m = 1\n */\n \n static double pi = M_PI;\n int n, npw;\n double v0, a, b, ecut, k;\n double *g, *e, *h, *wrk;\n int i, j, ij, m, lwork, info, p;\n char *V = \"V\";\n char *U = \"U\";\n FILE *out;\n \n /* Input data\n Potential: V(x)=-V_0 for |x|b/2\n Periodicity: V(x+a)=V(x)\n */\n fprintf(stdout, \"Parameters for potential well: V_0, a, b > \");\n scanf(\"%lf %lf %lf\",&v0, &a, &b);\n if ( v0 <= 0 || a <= 0 || b <= 0 || a <= b ) { \n fprintf(stderr, \"wrong input parameters\\n\");\n exit(1);\n }\n fprintf (stdout,\" V_0=%f, a0=%f, b=%f\\n\",v0,a,b);\n /*\n Plane waves basis set: G_n=n*2pi/a, \\hbar^2/2m*G^2 < Ecut\n */\n fprintf(stdout, \"Cutoff for plane waves: ecut > \");\n scanf(\"%lf\",&ecut);\n if ( ecut <= 0) {\n fprintf(stderr, \"wrong input parameter\\n\");\n exit(2);\n }\n /*\n Number of plane waves\n */\n npw = (int) ( sqrt ( ecut/pow( 2.0*pi/a, 2) ) + 0.5 );\n npw = 2*npw+1;\n fprintf (stdout,\" ecut = %f, # of PWs=%d\\n\",ecut, npw);\n /*\n Assign values of G_n: n=0,+1,-1,+2,-2, etc\n */\n n=100;\n g = (double *) malloc ( npw * sizeof (double) );\n e = (double *) malloc ( npw * sizeof (double) );\n h = (double *) malloc ( n*n * sizeof (double) );\n wrk= (double *) malloc (3*npw* sizeof (double) );\n\n g[0] = 0.0;\n for ( i = 1; i < npw; i+=2 ) {\n g[i ] = (i+1)*pi/a;\n g[i+1] =-(i+1)*pi/a;\n }\n for ( ij = 0; ij < n*n; ++ij ) {\n h[ij] = 0.0;\n }\n /*\n Loop on k-vectors: k runs from -pi/a to pi/a\n */\n out = fopen(\"bands.out\", \"w\");\n for ( m =-n; m <= n; m++ ) {\n k = m*pi/n/a;\n /*\n Assign values of the matrix elements of the hamiltonian \n on the plane wave basis\n */\n ij = 0;\n for ( i = 0; i < npw; ++i ) {\n for ( j = 0; j < npw; ++j ) {\n /* NOTA BENE: the matrix h is a vector in the calling program,\n while dsyev expects a (pointer to a) fortran matrix.\n A fortran matrix is \"simulated\" in the following way:\n if h[ij] is the C array and h(i,j) is a N*M Fortran matrix,\n h[ij] == h(i,j), where ij = (j-1)*N + (i-1) (i=1,N, j=1,M)\n */\n\n\tif ( i == j ) {\n\t h[ij++] = (k+g[i])*(k+g[i]) - v0/a*b; \n\t} else {\n\t h[ij++] = -v0/a * sin( (g[j]-g[i])*b/2.0 ) / (g[j]-g[i])*2.0;\n\t}\n }\n }\n /*\n Solution [expansion coefficients are stored into h(i,j)\n j=basis function index, i= eigenvalue index]\n (beware fortran-C reversed index convention!)\n */\n lwork = 3*npw;\n dsyev_ ( V, U, &npw, h, &npw, e, wrk, &lwork, &info ); \n\n if ( info != 0) {\n fprintf(stderr, \"H-matrix diagonalization failed\\n\");\n exit(3);\n }\n \n /*printf(\"%f \",k);\n for(p=0; p\n#include \n#include \n#include \"ccl_params.h\"\n#include \"ccl_error.h\"\n#include \n\n/* ------- ROUTINE: ccl_linear spacing ------\nINPUTS: [xmin,xmax] of the interval to be divided in N bins\nOUTPUT: bin edges in range [xmin,xmax]\n*/\n\ndouble * ccl_linear_spacing(double xmin, double xmax, int N)\n{\n double dx = (xmax-xmin)/(N -1.);\n \n double * x = malloc(sizeof(double)*N);\n if (x==NULL) {\n fprintf(stderr, \"ERROR: Could not allocate memory for linear-spaced array (N=%d)\\n\", N);\n return x;\n }\n \n for (int i=0; i0 && xmax>0)) {\n fprintf(stderr, \"ERROR: Cannot make log-spaced array xmax or xmax non-positive (had %le, %le)\\n\", xmin, xmax);\n return NULL;\n }\n \n double log_xmax = log(xmax);\n double log_xmin = log(xmin);\n double dlog_x = (log_xmax - log_xmin) / (N-1.);\n \n double * x = malloc(sizeof(double)*N);\n if (x==NULL) {\n fprintf(stderr, \"ERROR: Could not allocate memory for log-spaced array (N=%d)\\n\", N);\n return x;\n }\n \n for (int i=0; i number of points\n//x -> x-axis\n//y -> f(x)-axis\n//y0,yf -> values of f(x) to use beyond the interpolation range\nSplPar *ccl_spline_init(int n,double *x,double *y,double y0,double yf)\n{\n SplPar *spl=malloc(sizeof(SplPar));\n if(spl==NULL)\n return NULL;\n \n spl->intacc=gsl_interp_accel_alloc();\n spl->spline=gsl_spline_alloc(gsl_interp_cspline,n);\n int parstatus=gsl_spline_init(spl->spline,x,y,n);\n if(parstatus) {\n gsl_interp_accel_free(spl->intacc);\n gsl_spline_free(spl->spline);\n return NULL;\n }\n\n spl->x0=x[0];\n spl->xf=x[n-1];\n spl->y0=y0;\n spl->yf=yf;\n\n return spl;\n}\n\n//Evaluates spline at x checking for bound errors\ndouble ccl_spline_eval(double x,SplPar *spl)\n{\n if(x<=spl->x0)\n return spl->y0;\n else if(x>=spl->xf) \n return spl->yf;\n else {\n double y;\n int stat=gsl_spline_eval_e(spl->spline,x,spl->intacc,&y);\n if (stat!=GSL_SUCCESS) {\n ccl_raise_exception(stat,\"ccl_utils.c: ccl_splin_eval(): gsl error\\n\");\n return NAN;\n }\n return y;\n }\n}\n\n//Spline destructor\nvoid ccl_spline_free(SplPar *spl)\n{\n gsl_spline_free(spl->spline);\n gsl_interp_accel_free(spl->intacc);\n free(spl);\n}\n", "meta": {"hexsha": "e8ee0736f566a9a9fea49a84604d1832e8d13cb0", "size": 3026, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_utils.c", "max_stars_repo_name": "zdu863/3dcorrelation", "max_stars_repo_head_hexsha": "1683ee0af665e68924e67a11bffda26ab3269fe5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_utils.c", "max_issues_repo_name": "zdu863/3dcorrelation", "max_issues_repo_head_hexsha": "1683ee0af665e68924e67a11bffda26ab3269fe5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccl_utils.c", "max_forks_repo_name": "zdu863/3dcorrelation", "max_forks_repo_head_hexsha": "1683ee0af665e68924e67a11bffda26ab3269fe5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4032258065, "max_line_length": 114, "alphanum_fraction": 0.6427627231, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7050604621231394}} {"text": "/* Compile with:\nexport LDLIBS=\"`pkg-config --libs gsl`\"\nexport CFLAGS=\"`pkg-config --cflags gsl` -g -Wall -std=gnu11 -O3\"\nmake gsl_erf\n*/\n#include \n#include \n\nint main(){\n double bottom_tail = gsl_cdf_gaussian_P(-1.96, 1);\n printf(\"Area between [-1.96, 1.96]: %g\\n\", 1-2*bottom_tail);\n}\n", "meta": {"hexsha": "88b09605f539c6917aa30783b7ad5a08ce390e95", "size": 318, "ext": "c", "lang": "C", "max_stars_repo_path": "progr/c/21st-century-c/21st-Century-Examples/gsl_erf.c", "max_stars_repo_name": "catalingheorghe/learning-activities", "max_stars_repo_head_hexsha": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-10T11:24:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:24:07.000Z", "max_issues_repo_path": "progr/c/21st-century-c/21st-Century-Examples/gsl_erf.c", "max_issues_repo_name": "catalingheorghe/learning-activities", "max_issues_repo_head_hexsha": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "progr/c/21st-century-c/21st-Century-Examples/gsl_erf.c", "max_forks_repo_name": "catalingheorghe/learning-activities", "max_forks_repo_head_hexsha": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4615384615, "max_line_length": 65, "alphanum_fraction": 0.6603773585, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7048108839043382}} {"text": "#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nint\nmain()\n{\n const size_t N = 100; /* number of grid points */\n const size_t n = N - 2; /* subtract 2 to exclude boundaries */\n const double h = 1.0 / (N - 1.0); /* grid spacing */\n gsl_spmatrix *A = gsl_spmatrix_alloc(n ,n); /* triplet format */\n gsl_spmatrix *C; /* compressed format */\n gsl_vector *f = gsl_vector_alloc(n); /* right hand side vector */\n gsl_vector *u = gsl_vector_alloc(n); /* solution vector */\n size_t i;\n\n /* construct the sparse matrix for the finite difference equation */\n\n /* construct first row */\n gsl_spmatrix_set(A, 0, 0, -2.0);\n gsl_spmatrix_set(A, 0, 1, 1.0);\n\n /* construct rows [1:n-2] */\n for (i = 1; i < n - 1; ++i)\n {\n gsl_spmatrix_set(A, i, i + 1, 1.0);\n gsl_spmatrix_set(A, i, i, -2.0);\n gsl_spmatrix_set(A, i, i - 1, 1.0);\n }\n\n /* construct last row */\n gsl_spmatrix_set(A, n - 1, n - 1, -2.0);\n gsl_spmatrix_set(A, n - 1, n - 2, 1.0);\n\n /* scale by h^2 */\n gsl_spmatrix_scale(A, 1.0 / (h * h));\n\n /* construct right hand side vector */\n for (i = 0; i < n; ++i)\n {\n double xi = (i + 1) * h;\n double fi = -M_PI * M_PI * sin(M_PI * xi);\n gsl_vector_set(f, i, fi);\n }\n\n /* convert to compressed column format */\n C = gsl_spmatrix_ccs(A);\n\n /* now solve the system with the GMRES iterative solver */\n {\n const double tol = 1.0e-6; /* solution relative tolerance */\n const size_t max_iter = 10; /* maximum iterations */\n const gsl_splinalg_itersolve_type *T = gsl_splinalg_itersolve_gmres;\n gsl_splinalg_itersolve *work =\n gsl_splinalg_itersolve_alloc(T, n, 0);\n size_t iter = 0;\n double residual;\n int status;\n\n /* initial guess u = 0 */\n gsl_vector_set_zero(u);\n\n /* solve the system A u = f */\n do\n {\n status = gsl_splinalg_itersolve_iterate(C, f, tol, u, work);\n\n /* print out residual norm ||A*u - f|| */\n residual = gsl_splinalg_itersolve_normr(work);\n fprintf(stderr, \"iter %zu residual = %.12e\\n\", iter, residual);\n\n if (status == GSL_SUCCESS)\n fprintf(stderr, \"Converged\\n\");\n }\n while (status == GSL_CONTINUE && ++iter < max_iter);\n\n /* output solution */\n for (i = 0; i < n; ++i)\n {\n double xi = (i + 1) * h;\n double u_exact = sin(M_PI * xi);\n double u_gsl = gsl_vector_get(u, i);\n\n printf(\"%f %.12e %.12e\\n\", xi, u_gsl, u_exact);\n }\n\n gsl_splinalg_itersolve_free(work);\n }\n\n gsl_spmatrix_free(A);\n gsl_spmatrix_free(C);\n gsl_vector_free(f);\n gsl_vector_free(u);\n\n return 0;\n} /* main() */\n", "meta": {"hexsha": "5d9ba81827f0f25a57bb2b453645c0514d97eaa2", "size": 2820, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/poisson.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/poisson.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/poisson.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.6470588235, "max_line_length": 84, "alphanum_fraction": 0.574822695, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.7047988461122177}} {"text": "#include \"linearwaves.h\"\n#include \n#include \n\n\n#define FREAD_CHECK(i,j) ((i) >= (j)) ? (void) 0 : printf(\"fread returned read fewer items than expected (%zu < %zu) at line %d in %s of %s\\n\",i,j,__LINE__,__func__,__FILE__)\n\nvoid interpolation(double *xd, double *yd, int nd, double *x, double *y, double *dy, double *d2y, int n) {\n gsl_interp_accel *acc = gsl_interp_accel_alloc ();\n gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, nd);\n\n gsl_spline_init (spline, xd, yd, nd);\n\n int i;\n for(i=0;i= xd[0]) {\n jstart = i;\n break;\n }\n }\n for(i=jstart;i= xd[ndata-1]) {\n if (lr[i] == xd[ndata-1]) {\n jend = i;\n }\n else {\n jend = i-1;\n }\n break;\n }\n }\n int n_interp = jend-jstart +1;\n\n interpolation(xd,yd,ndata,&lr[jstart],&ynew[jstart],&dlydlr[jstart],&d2lydlr[jstart],n_interp);\n\n\n \n for(i=0;i\n\n#include \n#include \n\nnamespace kabsch\n{\n\n\ntemplate \ndouble rmsd(\n const M P,\n const M Q)\n{\n double rmsd {0.0};\n const unsigned int D {3};\n const unsigned int size = P.size();\n const unsigned int N = size / D;\n\n for(unsigned int i = 0; i < size; ++i) {\n rmsd += (P[i] - Q[i])*(P[i] - Q[i]);\n }\n\n return sqrt(rmsd/N);\n}\n\n\ntemplate \nM centroid(M coordinates)\n{\n\n double x {0};\n double y {0};\n double z {0};\n unsigned int size = coordinates.size();\n unsigned int n_atoms = size / 3;\n\n unsigned int i = 0;\n while(i\nMatrix multiply(Matrix A, Matrix B,\n const int M,\n const int N,\n const int K)\n{\n double one = 1.0;\n\n Matrix C(M*N);\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n M, N, K, one,\n begin(A), K,\n begin(B), N, 1.0,\n begin(C), N);\n\n return C;\n}\n\n\ntemplate \nMatrix transpose_multiply(Matrix A, Matrix B,\n const int M,\n const int N,\n const int K)\n{\n double one = 1.0;\n\n Matrix C(M*N);\n\n cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans,\n M, N, K, one,\n begin(A), M,\n begin(B), N, one,\n begin(C), N);\n\n return C;\n}\n\n\ntemplate \nstd::tuple matrix_svd(Matrix A, int rows, int cols)\n{\n // lapack_int LAPACKE_dgesvd( int matrix_layout, char jobu, char jobvt,\n // lapack_int m, lapack_int n,\n // double* a, lapack_int lda,\n // double* s, double* u, lapack_int ldu,\n // double* vt, lapack_int ldvt,\n // double* superb );\n\n Matrix U(cols*rows);\n Matrix S(rows);\n Matrix VT(cols*rows);\n Matrix superb(cols*rows);\n int info;\n\n info = LAPACKE_dgesvd(LAPACK_ROW_MAJOR, 'A', 'A',\n rows, cols,\n begin(A), rows,\n begin(S),\n begin(U), rows,\n begin(VT), rows,\n begin(superb));\n\n // TODO check if SVD is unconverged\n if(info > 0)\n {\n // Failed\n }\n\n return make_tuple(U, S, VT);\n}\n\n\ntemplate \ndouble determinant3x3(M A)\n{\n // determinant of a square 3x3 matrix\n double det = A[0]*A[4]*A[8]\n +A[1]*A[5]*A[6]\n +A[2]*A[3]*A[7]\n -A[2]*A[4]*A[6]\n -A[1]*A[3]*A[8]\n -A[0]*A[5]*A[7];\n\n return det;\n}\n\n\ntemplate \nM kabsch(M P, M Q, const T n_atoms)\n{\n // const unsigned int L = P.size();\n // const unsigned int D = 3;\n\n M U;\n M V;\n M S;\n\n M C = transpose_multiply(P, Q, 3, 3, n_atoms);\n\n tie(U, S, V) = matrix_svd(C, 3, 3);\n\n // Getting the sign of the det(U)*(V) to decide whether we need to correct\n // our rotation matrix to ensure a right-handed coordinate system.\n if(determinant3x3(U)*determinant3x3(V) < 0.0)\n {\n // TODO More numpy'ish way to do this?\n U[std::slice( 2, 3, 3 )] = {-U[3*0+2], -U[3*1+2], -U[3*2+2]};\n }\n\n M rotation = multiply(U, V, 3, 3, 3);\n\n return rotation;\n}\n\n\ntemplate \nM kabsch_rotate(\n const M P,\n const M Q,\n const T n_atoms)\n{\n M U = kabsch(P, Q, n_atoms);\n M product = multiply(P, U, n_atoms, 3, 3);\n return product;\n}\n\n\ntemplate \ndouble kabsch_rmsd(\n const M P,\n const M Q,\n const T n_atoms)\n{\n M P_rotated = kabsch_rotate(P, Q, n_atoms);\n return rmsd(P_rotated, Q);\n}\n\n\n} // namespace rmsd\n\n#endif\n", "meta": {"hexsha": "00577eba7bb57904ac300e9aec8da16a71ee2d50", "size": 3692, "ext": "h", "lang": "C", "max_stars_repo_path": "rmsd++/kabsch.h", "max_stars_repo_name": "kjappelbaum/rmsd", "max_stars_repo_head_hexsha": "8cd6adf6ca736ead1be745130efd6e3341e940df", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rmsd++/kabsch.h", "max_issues_repo_name": "kjappelbaum/rmsd", "max_issues_repo_head_hexsha": "8cd6adf6ca736ead1be745130efd6e3341e940df", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmsd++/kabsch.h", "max_forks_repo_name": "kjappelbaum/rmsd", "max_forks_repo_head_hexsha": "8cd6adf6ca736ead1be745130efd6e3341e940df", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-30T06:56:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-30T06:56:51.000Z", "avg_line_length": 18.46, "max_line_length": 78, "alphanum_fraction": 0.5484832069, "num_tokens": 1183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.7045935300685606}} {"text": "#ifndef CURVATURE_H_LSXONAFA\n#define CURVATURE_H_LSXONAFA\n\n#include \n#include \n#include \n\nnamespace sens_loc::math {\n\n/// This function calculates the gaussian curvature for a function given its\n/// derivatives.\n/// \\tparam Real precision of the calculation\n/// \\param f_u,f_v,f_uu,f_vv,f_uv partial derivatives of the depth values\n/// \\returns gaussian curvature for these derivatives\n/// \\sa conversion::depth_to_gaussian_curvature\n/// \\note check https://en.wikipedia.org/wiki/Gaussian_curvature for more info\ntemplate \ninline Real gaussian_curvature(\n Real f_u, Real f_v, Real f_uu, Real f_vv, Real f_uv) noexcept {\n static_assert(std::is_floating_point_v);\n\n return (f_uu * f_vv - f_uv * f_uv) / (Real(1.) + f_u * f_u + f_v * f_v);\n}\n\n/// This function calculates the mean curvature for a function given its\n/// derivatives.\n/// \\tparam Real precicions of the calculation\n/// \\param f_u,f_v,f_uu,f_vv,f_uv partial derivatives of the depth values\n/// \\returns the mean curvature for these derivatives\n/// \\sa conversion::depth_to_mean_curvature\n/// \\note check https://en.wikipedia.org/wiki/Mean_curvature for more info\ntemplate \ninline Real\nmean_curvature(Real f_u, Real f_v, Real f_uu, Real f_vv, Real f_uv) noexcept {\n static_assert(std::is_floating_point_v);\n\n using std::pow;\n using std::sqrt;\n // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)\n return ((Real(1.) + f_v * f_v) * f_uu - Real(2.) * f_u * f_v * f_uv +\n (Real(1.) + f_u * f_u) * f_vv) /\n // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)\n pow(Real(2.) * sqrt(Real(1.) + f_u * f_u + f_v * f_v), Real(3.));\n}\n} // namespace sens_loc::math\n\n#endif /* end of include guard: CURVATURE_H_LSXONAFA */\n", "meta": {"hexsha": "b78f840fd7fbb7ab9c8210cbc7233ba9e5a82853", "size": 1807, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/sens_loc/math/curvature.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/include/sens_loc/math/curvature.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/sens_loc/math/curvature.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6458333333, "max_line_length": 78, "alphanum_fraction": 0.7127836193, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7038723455787552}} {"text": "#include \"ll.h\"\n#include \"gslsupp.h\"\n\n#include \n#include \n\ndouble log_fact(size_t n)\n{\n gsl_sf_result res;\n if (n <= UINT_MAX) \n {\n if (gsl_sf_lnfact_e((unsigned) n, &res) == GSL_SUCCESS) return res.val;\n }\n else\n {\n if (gsl_sf_lngamma_e((double) n + 1., &res) == GSL_SUCCESS) return res.val;\n }\n return nan(__func__);\n}\n\ndouble log_choose(size_t n, size_t m)\n{\n if (m > n) return nan(__func__);\n if (m == n || !m) return 0.;\n return m > (n >> 1) ? log_fact(n) - log_fact(n - m) - log_fact(m) : log_fact(n) - log_fact(m) - log_fact(n - m); // Addition here may be not associative\n}\n\ndouble pdf_hypergeom(size_t k, size_t n1, size_t n2, size_t t)\n{\n size_t car, n12 = size_add(&car, n1, n2);\n if (car) return nan(__func__);\n if (t > n12) t = n12;\n if (k > n1 || k > t || (t > n2 && k < t - n2)) return 0.;\n return exp(log_choose(n1, k) + log_choose(n2, t - k) - log_choose(n12, t));\n}\n\ndouble gamma_inc_P(double a, double x)\n{\n gsl_sf_result res;\n if (gsl_sf_gamma_inc_P_e(a, x, &res) == GSL_SUCCESS) return res.val;\n return nan(__func__);\n}\n\ndouble gamma_inc_Q(double a, double x)\n{\n gsl_sf_result res;\n if (gsl_sf_gamma_inc_Q_e(a, x, &res) == GSL_SUCCESS) return res.val;\n return nan(__func__);\n}\n\ndouble cdf_gamma_Q(double x, double a, double b)\n{\n if (x <= 0.) return 1.;\n double y = x / b;\n return y < a ? 1. - gamma_inc_P(a, y) : gamma_inc_Q(a, y);\n}\n\ndouble cdf_chisq_Q(double x, double df)\n{\n return cdf_gamma_Q(x, df / 2., 2.);\n}", "meta": {"hexsha": "8b01f181c7ab73e4605cbb099c4f5a0c2024b7c4", "size": 1551, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gslsupp.c", "max_stars_repo_name": "DobzhanskyCenterSPBU/RegionsMT.Update", "max_stars_repo_head_hexsha": "b416ed24df0178244061a9f2aa75c513b3d8df9c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gslsupp.c", "max_issues_repo_name": "DobzhanskyCenterSPBU/RegionsMT.Update", "max_issues_repo_head_hexsha": "b416ed24df0178244061a9f2aa75c513b3d8df9c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gslsupp.c", "max_forks_repo_name": "DobzhanskyCenterSPBU/RegionsMT.Update", "max_forks_repo_head_hexsha": "b416ed24df0178244061a9f2aa75c513b3d8df9c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4262295082, "max_line_length": 156, "alphanum_fraction": 0.6060606061, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7038003312692327}} {"text": "#include \n#include \n#include \n\ndouble f (double x, void * params)\n{\n return pow (x, 1.5);\n}\n\nint\nmain (void)\n{\n gsl_function F;\n double result, abserr;\n\n F.function = &f;\n F.params = 0;\n\n printf (\"f(x) = x^(3/2)\\n\");\n\n gsl_deriv_central (&F, 2.0, 1e-8, &result, &abserr);\n printf (\"x = 2.0\\n\");\n printf (\"f'(x) = %.10f +/- %.10f\\n\", result, abserr);\n printf (\"exact = %.10f\\n\\n\", 1.5 * sqrt(2.0));\n\n gsl_deriv_forward (&F, 0.0, 1e-8, &result, &abserr);\n printf (\"x = 0.0\\n\");\n printf (\"f'(x) = %.10f +/- %.10f\\n\", result, abserr);\n printf (\"exact = %.10f\\n\", 0.0);\n\n return 0;\n}\n", "meta": {"hexsha": "b32e1934f547a84e0ed90e49766ee747884ab1be", "size": 636, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/diff.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/doc/examples/diff.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/doc/examples/diff.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 19.2727272727, "max_line_length": 55, "alphanum_fraction": 0.5534591195, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382006, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7035011236856609}} {"text": "/* specfunc/gsl_sf_bessel.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * 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, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n/* Author: G. Jungman */\r\n\r\n#ifndef __GSL_SF_BESSEL_H__\r\n#define __GSL_SF_BESSEL_H__\r\n\r\n#if !defined( GSL_FUN )\r\n# if !defined( GSL_DLL )\r\n# define GSL_FUN extern\r\n# elif defined( BUILD_GSL_DLL )\r\n# define GSL_FUN extern __declspec(dllexport)\r\n# else\r\n# define GSL_FUN extern __declspec(dllimport)\r\n# endif\r\n#endif\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\n\r\n/* Regular Bessel Function J_0(x)\r\n *\r\n * exceptions: none\r\n */\r\nGSL_FUN int gsl_sf_bessel_J0_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_J0(const double x);\r\n\r\n\r\n/* Regular Bessel Function J_1(x)\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_J1_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_J1(const double x);\r\n\r\n\r\n/* Regular Bessel Function J_n(x)\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Jn_e(int n, double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Jn(const int n, const double x);\r\n\r\n\r\n/* Regular Bessel Function J_n(x), nmin <= n <= nmax\r\n *\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Jn_array(int nmin, int nmax, double x, double * result_array);\r\n\r\n\r\n/* Irregular Bessel function Y_0(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Y0_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Y0(const double x);\r\n\r\n\r\n/* Irregular Bessel function Y_1(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Y1_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Y1(const double x);\r\n\r\n\r\n/* Irregular Bessel function Y_n(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Yn_e(int n,const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Yn(const int n,const double x);\r\n\r\n\r\n/* Irregular Bessel function Y_n(x), nmin <= n <= nmax\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Yn_array(const int nmin, const int nmax, const double x, double * result_array);\r\n\r\n\r\n/* Regular modified Bessel function I_0(x)\r\n *\r\n * exceptions: GSL_EOVRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_I0_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_I0(const double x);\r\n\r\n\r\n/* Regular modified Bessel function I_1(x)\r\n *\r\n * exceptions: GSL_EOVRFLW, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_I1_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_I1(const double x);\r\n\r\n\r\n/* Regular modified Bessel function I_n(x)\r\n *\r\n * exceptions: GSL_EOVRFLW, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_In_e(const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_In(const int n, const double x);\r\n\r\n\r\n/* Regular modified Bessel function I_n(x) for n=nmin,...,nmax\r\n *\r\n * nmin >=0, nmax >= nmin\r\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_In_array(const int nmin, const int nmax, const double x, double * result_array);\r\n\r\n\r\n/* Scaled regular modified Bessel function\r\n * exp(-|x|) I_0(x)\r\n *\r\n * exceptions: none\r\n */\r\nGSL_FUN int gsl_sf_bessel_I0_scaled_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_I0_scaled(const double x);\r\n\r\n\r\n/* Scaled regular modified Bessel function\r\n * exp(-|x|) I_1(x)\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_I1_scaled_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_I1_scaled(const double x);\r\n\r\n\r\n/* Scaled regular modified Bessel function\r\n * exp(-|x|) I_n(x)\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_In_scaled_e(int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_In_scaled(const int n, const double x);\r\n\r\n\r\n/* Scaled regular modified Bessel function\r\n * exp(-|x|) I_n(x) for n=nmin,...,nmax\r\n *\r\n * nmin >=0, nmax >= nmin\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_In_scaled_array(const int nmin, const int nmax, const double x, double * result_array);\r\n\r\n\r\n/* Irregular modified Bessel function K_0(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_K0_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_K0(const double x);\r\n\r\n\r\n/* Irregular modified Bessel function K_1(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_K1_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_K1(const double x);\r\n\r\n\r\n/* Irregular modified Bessel function K_n(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Kn_e(const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Kn(const int n, const double x);\r\n\r\n\r\n/* Irregular modified Bessel function K_n(x) for n=nmin,...,nmax\r\n *\r\n * x > 0.0, nmin >=0, nmax >= nmin\r\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Kn_array(const int nmin, const int nmax, const double x, double * result_array);\r\n\r\n\r\n/* Scaled irregular modified Bessel function\r\n * exp(x) K_0(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM\r\n */\r\nGSL_FUN int gsl_sf_bessel_K0_scaled_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_K0_scaled(const double x);\r\n\r\n\r\n/* Scaled irregular modified Bessel function\r\n * exp(x) K_1(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_K1_scaled_e(const double x, gsl_sf_result * result); \r\nGSL_FUN double gsl_sf_bessel_K1_scaled(const double x);\r\n\r\n\r\n/* Scaled irregular modified Bessel function\r\n * exp(x) K_n(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Kn_scaled_e(int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Kn_scaled(const int n, const double x);\r\n\r\n\r\n/* Scaled irregular modified Bessel function exp(x) K_n(x) for n=nmin,...,nmax\r\n *\r\n * x > 0.0, nmin >=0, nmax >= nmin\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Kn_scaled_array(const int nmin, const int nmax, const double x, double * result_array);\r\n\r\n\r\n/* Regular spherical Bessel function j_0(x) = sin(x)/x\r\n *\r\n * exceptions: none\r\n */\r\nGSL_FUN int gsl_sf_bessel_j0_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_j0(const double x);\r\n\r\n\r\n/* Regular spherical Bessel function j_1(x) = (sin(x)/x - cos(x))/x\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_j1_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_j1(const double x);\r\n\r\n\r\n/* Regular spherical Bessel function j_2(x) = ((3/x^2 - 1)sin(x) - 3cos(x)/x)/x\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_j2_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_j2(const double x);\r\n\r\n\r\n/* Regular spherical Bessel function j_l(x)\r\n *\r\n * l >= 0, x >= 0.0\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_jl_e(const int l, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_jl(const int l, const double x);\r\n\r\n\r\n/* Regular spherical Bessel function j_l(x) for l=0,1,...,lmax\r\n *\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_jl_array(const int lmax, const double x, double * result_array);\r\n\r\n\r\n/* Regular spherical Bessel function j_l(x) for l=0,1,...,lmax\r\n * Uses Steed's method.\r\n *\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_jl_steed_array(const int lmax, const double x, double * jl_x_array);\r\n\r\n\r\n/* Irregular spherical Bessel function y_0(x)\r\n *\r\n * exceptions: none\r\n */\r\nGSL_FUN int gsl_sf_bessel_y0_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_y0(const double x);\r\n\r\n\r\n/* Irregular spherical Bessel function y_1(x)\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_y1_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_y1(const double x);\r\n\r\n\r\n/* Irregular spherical Bessel function y_2(x)\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_y2_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_y2(const double x);\r\n\r\n\r\n/* Irregular spherical Bessel function y_l(x)\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_yl_e(int l, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_yl(const int l, const double x);\r\n\r\n\r\n/* Irregular spherical Bessel function y_l(x) for l=0,1,...,lmax\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_yl_array(const int lmax, const double x, double * result_array);\r\n\r\n\r\n/* Regular scaled modified spherical Bessel function\r\n *\r\n * Exp[-|x|] i_0(x)\r\n *\r\n * exceptions: none\r\n */\r\nGSL_FUN int gsl_sf_bessel_i0_scaled_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_i0_scaled(const double x);\r\n\r\n\r\n/* Regular scaled modified spherical Bessel function\r\n *\r\n * Exp[-|x|] i_1(x)\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_i1_scaled_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_i1_scaled(const double x);\r\n\r\n\r\n/* Regular scaled modified spherical Bessel function\r\n *\r\n * Exp[-|x|] i_2(x)\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_i2_scaled_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_i2_scaled(const double x);\r\n\r\n\r\n/* Regular scaled modified spherical Bessel functions\r\n *\r\n * Exp[-|x|] i_l(x)\r\n *\r\n * i_l(x) = Sqrt[Pi/(2x)] BesselI[l+1/2,x]\r\n *\r\n * l >= 0\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_il_scaled_e(const int l, double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_il_scaled(const int l, const double x);\r\n\r\n\r\n/* Regular scaled modified spherical Bessel functions\r\n *\r\n * Exp[-|x|] i_l(x)\r\n * for l=0,1,...,lmax\r\n *\r\n * exceptions: GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_il_scaled_array(const int lmax, const double x, double * result_array);\r\n\r\n\r\n/* Irregular scaled modified spherical Bessel function\r\n * Exp[x] k_0(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_k0_scaled_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_k0_scaled(const double x);\r\n\r\n\r\n/* Irregular modified spherical Bessel function\r\n * Exp[x] k_1(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW, GSL_EOVRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_k1_scaled_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_k1_scaled(const double x);\r\n\r\n\r\n/* Irregular modified spherical Bessel function\r\n * Exp[x] k_2(x)\r\n *\r\n * x > 0.0\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW, GSL_EOVRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_k2_scaled_e(const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_k2_scaled(const double x);\r\n\r\n\r\n/* Irregular modified spherical Bessel function\r\n * Exp[x] k_l[x]\r\n *\r\n * k_l(x) = Sqrt[Pi/(2x)] BesselK[l+1/2,x]\r\n *\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_kl_scaled_e(int l, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_kl_scaled(const int l, const double x);\r\n\r\n\r\n/* Irregular scaled modified spherical Bessel function\r\n * Exp[x] k_l(x)\r\n *\r\n * for l=0,1,...,lmax\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_kl_scaled_array(const int lmax, const double x, double * result_array);\r\n\r\n\r\n/* Regular cylindrical Bessel function J_nu(x)\r\n *\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Jnu_e(const double nu, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Jnu(const double nu, const double x);\r\n\r\n\r\n/* Irregular cylindrical Bessel function Y_nu(x)\r\n *\r\n * exceptions: \r\n */\r\nGSL_FUN int gsl_sf_bessel_Ynu_e(double nu, double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Ynu(const double nu, const double x);\r\n\r\n\r\n/* Regular cylindrical Bessel function J_nu(x)\r\n * evaluated at a series of x values. The array\r\n * contains the x values. They are assumed to be\r\n * strictly ordered and positive. The array is\r\n * over-written with the values of J_nu(x_i).\r\n *\r\n * exceptions: GSL_EDOM, GSL_EINVAL\r\n */\r\nGSL_FUN int gsl_sf_bessel_sequence_Jnu_e(double nu, gsl_mode_t mode, size_t size, double * v);\r\n\r\n\r\n/* Scaled modified cylindrical Bessel functions\r\n *\r\n * Exp[-|x|] BesselI[nu, x]\r\n * x >= 0, nu >= 0\r\n *\r\n * exceptions: GSL_EDOM\r\n */\r\nGSL_FUN int gsl_sf_bessel_Inu_scaled_e(double nu, double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Inu_scaled(double nu, double x);\r\n\r\n\r\n/* Modified cylindrical Bessel functions\r\n *\r\n * BesselI[nu, x]\r\n * x >= 0, nu >= 0\r\n *\r\n * exceptions: GSL_EDOM, GSL_EOVRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Inu_e(double nu, double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Inu(double nu, double x);\r\n\r\n\r\n/* Scaled modified cylindrical Bessel functions\r\n *\r\n * Exp[+|x|] BesselK[nu, x]\r\n * x > 0, nu >= 0\r\n *\r\n * exceptions: GSL_EDOM\r\n */\r\nGSL_FUN int gsl_sf_bessel_Knu_scaled_e(const double nu, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Knu_scaled(const double nu, const double x);\r\n\r\nGSL_FUN int gsl_sf_bessel_Knu_scaled_e10_e(const double nu, const double x, gsl_sf_result_e10 * result);\r\n\r\n/* Modified cylindrical Bessel functions\r\n *\r\n * BesselK[nu, x]\r\n * x > 0, nu >= 0\r\n *\r\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\r\n */\r\nGSL_FUN int gsl_sf_bessel_Knu_e(const double nu, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_Knu(const double nu, const double x);\r\n\r\n\r\n/* Logarithm of modified cylindrical Bessel functions.\r\n *\r\n * Log[BesselK[nu, x]]\r\n * x > 0, nu >= 0\r\n *\r\n * exceptions: GSL_EDOM\r\n */\r\nGSL_FUN int gsl_sf_bessel_lnKnu_e(const double nu, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_lnKnu(const double nu, const double x);\r\n\r\n\r\n/* s'th positive zero of the Bessel function J_0(x).\r\n *\r\n * exceptions: \r\n */\r\nGSL_FUN int gsl_sf_bessel_zero_J0_e(unsigned int s, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_zero_J0(unsigned int s);\r\n\r\n\r\n/* s'th positive zero of the Bessel function J_1(x).\r\n *\r\n * exceptions: \r\n */\r\nGSL_FUN int gsl_sf_bessel_zero_J1_e(unsigned int s, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_zero_J1(unsigned int s);\r\n\r\n\r\n/* s'th positive zero of the Bessel function J_nu(x).\r\n *\r\n * exceptions: \r\n */\r\nGSL_FUN int gsl_sf_bessel_zero_Jnu_e(double nu, unsigned int s, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_bessel_zero_Jnu(double nu, unsigned int s);\r\n\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_SF_BESSEL_H__ */\r\n", "meta": {"hexsha": "316b56113e1e9d646905135c56f73801fed9d255", "size": 15765, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_sf_bessel.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_sf_bessel.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_sf_bessel.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 28.1517857143, "max_line_length": 114, "alphanum_fraction": 0.7158896289, "num_tokens": 4590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8031737940012417, "lm_q1q2_score": 0.7034091634227204}} {"text": "/* cdf/hypergeometric.c\n *\n * Copyright (C) 2004 Jason H. Stover.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\n\n/*\n * Computes the cumulative distribution function for a hypergeometric\n * random variable. A hypergeometric random variable X is the number\n * of elements of type 1 in a sample of size t, drawn from a population\n * of size n1 + n2, in which n1 are of type 1 and n2 are of type 2.\n *\n * This algorithm computes Pr( X <= k ) by summing the terms from\n * the mass function, Pr( X = k ).\n *\n * References:\n *\n * T. Wu. An accurate computation of the hypergeometric distribution \n * function. ACM Transactions on Mathematical Software. Volume 19, number 1,\n * March 1993.\n * This algorithm is not used, since it requires factoring the\n * numerator and denominator, then cancelling. It is more accurate\n * than the algorithm used here, but the cancellation requires more\n * time than the algorithm used here.\n *\n * W. Feller. An Introduction to Probability Theory and Its Applications,\n * third edition. 1968. Chapter 2, section 6. \n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\nstatic double\nlower_tail (const unsigned int k, const unsigned int n1,\n const unsigned int n2, const unsigned int t)\n{\n double relerr;\n int i = k;\n double s, P;\n\n s = gsl_ran_hypergeometric_pdf (i, n1, n2, t);\n P = s;\n \n while (i > 0)\n {\n double factor =\n (i / (n1 - i + 1.0)) * ((n2 + i - t) / (t - i + 1.0));\n s *= factor;\n P += s;\n relerr = s / P;\n if (relerr < GSL_DBL_EPSILON)\n break;\n i--;\n }\n\n return P;\n}\n \nstatic double \nupper_tail (const unsigned int k, const unsigned int n1,\n const unsigned int n2, const unsigned int t)\n{\n double relerr;\n unsigned int i = k + 1;\n double s, Q;\n \n s = gsl_ran_hypergeometric_pdf (i, n1, n2, t);\n Q = s;\n \n while (i < t)\n {\n double factor =\n ((n1 - i) / (i + 1.0)) * ((t - i) / (n2 + i + 1.0 - t));\n s *= factor;\n Q += s;\n relerr = s / Q;\n if (relerr < GSL_DBL_EPSILON)\n break;\n i++;\n }\n\n return Q;\n}\n\n\n\n\n/*\n * Pr (X <= k)\n */\ndouble\ngsl_cdf_hypergeometric_P (const unsigned int k,\n const unsigned int n1,\n const unsigned int n2, const unsigned int t)\n{\n double P;\n\n if (t > (n1 + n2))\n {\n CDF_ERROR (\"t larger than population size\", GSL_EDOM);\n }\n else if (k >= n1 || k >= t)\n {\n P = 1.0;\n }\n else if (k < 0.0)\n {\n P = 0.0;\n }\n else\n {\n double midpoint = (int) (t * n1 / (n1 + n2));\n\n if (k >= midpoint)\n {\n P = 1 - upper_tail (k, n1, n2, t);\n }\n else\n {\n P = lower_tail (k, n1, n2, t);\n }\n }\n\n return P;\n}\n\n/*\n * Pr (X > k)\n */\ndouble\ngsl_cdf_hypergeometric_Q (const unsigned int k,\n const unsigned int n1,\n const unsigned int n2, const unsigned int t)\n{\n double Q;\n\n if (t > (n1 + n2))\n {\n CDF_ERROR (\"t larger than population size\", GSL_EDOM);\n }\n else if (k >= n1 || k >= t)\n {\n Q = 0.0;\n }\n else if (k < 0.0)\n {\n Q = 1.0;\n }\n else\n {\n double midpoint = (int) (t * n1 / (n1 + n2));\n\n if (k < midpoint)\n {\n Q = 1 - lower_tail (k, n1, n2, t);\n }\n else\n {\n Q = upper_tail (k, n1, n2, t);\n }\n }\n\n return Q;\n}\n", "meta": {"hexsha": "c0dee39f5598dbfd8911908cf6da986b8aded413", "size": 4198, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/cdf/hypergeometric.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/cdf/hypergeometric.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/cdf/hypergeometric.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 22.8152173913, "max_line_length": 77, "alphanum_fraction": 0.5743211053, "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7033930244405213}} {"text": "#include \n#include \n#include \n#include \"compearth.h\"\n#ifdef COMPEARTH_USE_MKL\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#pragma clang diagnostic ignored \"-Wstrict-prototypes\"\n#endif\n#include \n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include \n#endif\n\nstatic double compearth_norm64f(const int n, const double *__restrict__ x,\n const enum ceNormType_enum norm,\n const double p, int *ierr);\n/*!\n * @brief Computes the matrix (Frobenius) norm for a matrix\n *\n * @param[in] n number of matrices\n * @param[in] M 3 x 3 input matrix as a length 9 array [9*n]\n * @param[in] Lnorm matrix norm\n * TWO_NORM (2)\n * ONE_NORM (1)\n * P_NORM (in this case must set p)\n * INFINITY_NORM\n * NEGATIVE_INFINITY_NORM\n * @param[in] p if using a p-norm this is the value for p (> 0)\n *\n * @param[out] mnorm matrix norms for each matrix\n *\n * @result 0 indicates success \n *\n */\nint compearth_normMat(const int n,\n const double *__restrict__ M,\n const enum ceNormType_enum Lnorm,\n const double p,\n double *__restrict__ mnorm)\n{\n int i, ierr;\n ierr = 0;\n for (i=0; i\n#include \n#include \n#include \"gauss.h\"\n\n#define SQRT_2_PI 2.506628274631 /* sqrt(2*PI) */\n#define LOG_SQRT_2_PI 0.918938533204673 /* log(sqrt(2*PI)) */\n\ngauss_t gauss_init_prec(double prec_mean, double prec){\n\tgauss_t r;\n\tr.prec_mean = prec_mean;\n\tr.prec = prec;\n\tr.var = 1.0 / prec;\n\tr.mean = prec_mean / prec;\n\tr.stddev = sqrt(r.var);\n\treturn r;\n}\n\ngauss_t gauss_init_var(double mean, double var){\n\tgauss_t r;\n\tr.var = var;\n\tr.mean = mean;\n\tr.stddev = sqrt(var);\n\tr.prec = 1.0 / var;\n\tr.prec_mean = r.prec * r.mean;\n\treturn r;\n}\n\ngauss_t gauss_init_std(double mean, double stddev){\n\tgauss_t r;\n\tr.var = stddev * stddev;\n\tr.mean = mean;\n\tr.stddev = stddev;\n\tr.prec = 1.0 / r.var;\n\tr.prec_mean = r.prec * r.mean;\n\treturn r;\n}\n\ndouble gauss_log_product_normal(gauss_t a, gauss_t b){\n\tif(a.prec == 0 || b.prec == 0) return 0.0;\n\t\n\tdouble var_sum = a.var + b.var;\n\tdouble mean_diff = a.mean - b.mean;\n\t\n\treturn -LOG_SQRT_2_PI - (log(var_sum)/2.0) - ((mean_diff * mean_diff) / (2.0 * var_sum));\n}\n\ndouble gauss_log_ratio_normal(gauss_t a, gauss_t b){\n\tif(a.prec == 0 || b.prec == 0) return 0.0;\n\t\n\tdouble var_diff = a.var - b.var;\n\tdouble mean_diff = a.mean - b.mean;\n\n\treturn log(b.var) + LOG_SQRT_2_PI - (log(var_diff)/2.0) + ((mean_diff * mean_diff) / (2.0 * var_diff));\n}\n\n\ndouble gauss_cdf_P(gauss_t a, double x){\n\treturn gsl_cdf_gaussian_P(x - a.mean, a.stddev);\n}\n\ndouble gauss_cdf_Q(gauss_t a, double x){\n\treturn gsl_cdf_gaussian_Q(x - a.mean, a.stddev);\n}\n\ngauss_t gauss_add(gauss_t a, gauss_t b){\n\tgauss_t r;\n\tr.mean = a.mean + b.mean;\n\tr.var = a.var + b.var;\n\tr.prec = 1.0 / r.var;\n\tr.prec_mean = r.prec * r.mean;\n\tr.stddev = sqrt(r.var);\n\treturn r;\n}\n\n\n\n\n\ngauss_t gauss_sub(gauss_t a, gauss_t b){\n\tgauss_t temp = b;\n\ttemp.mean = -temp.mean;\n\treturn gauss_add(a, temp);\n}\n\ndouble gauss_abs_diff(gauss_t a, gauss_t b){\n\tdouble prec_mean_diff = fabs(a.prec_mean - b.prec_mean);\n\tdouble prec_diff = sqrt(fabs(a.prec - b.prec));\n\treturn (prec_mean_diff > prec_diff) ? prec_mean_diff : prec_diff;\n}\n\ngauss_t gauss_div(gauss_t a, gauss_t b){\n\tdouble prec = a.prec - b.prec;\n\tdouble prec_mean = a.prec_mean - b.prec_mean;\n\treturn gauss_init_prec(prec_mean, prec);\n}\n\ngauss_t gauss_mul(gauss_t a, gauss_t b){\n\tdouble prec = a.prec + b.prec;\n\tdouble prec_mean = a.prec_mean + b.prec_mean;\n\treturn gauss_init_prec(prec_mean, prec);\n}\n", "meta": {"hexsha": "8c314da6c7814b40f3fdf9ecd5036480073d2980", "size": 2494, "ext": "c", "lang": "C", "max_stars_repo_path": "gauss.c", "max_stars_repo_name": "cosmicturtle/gamesetmatch", "max_stars_repo_head_hexsha": "caffee7a58ef60b962aee41d91da1f8f1808462f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gauss.c", "max_issues_repo_name": "cosmicturtle/gamesetmatch", "max_issues_repo_head_hexsha": "caffee7a58ef60b962aee41d91da1f8f1808462f", "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": "gauss.c", "max_forks_repo_name": "cosmicturtle/gamesetmatch", "max_forks_repo_head_hexsha": "caffee7a58ef60b962aee41d91da1f8f1808462f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.213592233, "max_line_length": 104, "alphanum_fraction": 0.6483560545, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.702736712552831}} {"text": "#ifndef __SPATIAL_STATISTICS_H__\n#define __SPATIAL_STATISTICS_H__\n\n#include \n#include \n\nextern \"C\" double gsl_sf_gamma(const double);\nextern \"C\" double gsl_sf_hyperg_1F1(double, double, double);\n\ntemplate struct Spatial_Statistics\n{\n private:\n T phi, nu;\n T con;\n int d;\n\n public:\n Spatial_Statistics(T phi, T nu, int dim)\n {\n this->phi = phi;\n this->nu = nu;\n // this->alpha = alpha;\n this->d = dim;\n\n con = pow(2, (nu - 1)) * tgamma(nu);\n con = 1.0 / con;\n\n // c1 = pow(h / sigma, d) / pow(sigma, alpha);\n // c2 = -pow(2.0, alpha) * gsl_sf_gamma((alpha + (T)d) / 2) / pow(M_PI, (T)d / 2) / gsl_sf_gamma((T)d / 2);\n }\n\n // T G(T x) const\n //{\n // return c2 * gsl_sf_hyperg_1F1((alpha + (T)d) / 2, (T)d / 2, -x * x);\n //}\n\n T operator()(T *pt_x, T *pt_y) const\n {\n T diff = 0.0;\n for (int i = 0; i < d; i++)\n diff += (pt_x[i] - pt_y[i]) * (pt_x[i] - pt_y[i]);\n T dist = sqrt(diff);\n\n dist = 4.0 * sqrt(2.0 * nu) * (dist / phi);\n if (dist == 0.0)\n {\n return 1.0;\n }\n else\n {\n return con * pow(dist, nu) * gsl_sf_bessel_Knu(nu, dist);\n }\n }\n};\n\ntemplate struct MaternKernel\n{\n private:\n T h, sigma, alpha;\n T c1, c2;\n int d;\n\n public:\n MaternKernel(T h, T sigma, T alpha, int dim)\n {\n this->h = h;\n this->sigma = sigma;\n this->alpha = alpha;\n this->d = dim;\n\n c1 = pow(h / sigma, d) / pow(sigma, alpha);\n c2 = -pow(2.0, alpha) * gsl_sf_gamma((alpha + (T)d) / 2.0) / pow(M_PI, (T)d / 2.0) / gsl_sf_gamma((T)d / 2.0);\n }\n\n T G(T x) const\n {\n return c2 * gsl_sf_hyperg_1F1((alpha + (T)d) / 2.0, (T)d / 2.0, -x * x);\n }\n\n T operator()(T *pt_x, T *pt_y) const\n {\n T diff = 0.0;\n for (int i = 0; i < d; i++)\n diff += (pt_x[i] - pt_y[i]) * (pt_x[i] - pt_y[i]);\n T dist = sqrt(diff);\n\n return c1 * G(dist / sigma);\n }\n};\n\n#endif\n", "meta": {"hexsha": "7a4740ba493ab46fb1d67b8a770d04220fe73566", "size": 2102, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/spatialstatistics/spatial_statistics.h", "max_stars_repo_name": "ecrc/h2opus", "max_stars_repo_head_hexsha": "c75d74cc96d728c11b7bf0f291ba71dc369a89f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-09-09T14:26:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T18:47:48.000Z", "max_issues_repo_path": "examples/spatialstatistics/spatial_statistics.h", "max_issues_repo_name": "ecrc/h2opus", "max_issues_repo_head_hexsha": "c75d74cc96d728c11b7bf0f291ba71dc369a89f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/spatialstatistics/spatial_statistics.h", "max_forks_repo_name": "ecrc/h2opus", "max_forks_repo_head_hexsha": "c75d74cc96d728c11b7bf0f291ba71dc369a89f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-25T03:44:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T10:28:30.000Z", "avg_line_length": 22.847826087, "max_line_length": 118, "alphanum_fraction": 0.4823977165, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.7027367086651904}} {"text": "static char help[] =\n\"Solves the p-Helmholtz equation in 2D using Q_1 FEM. Option prefix -ph_.\\n\"\n\"Problem is posed as minimizing this objective functional over W^{1,p}\\n\"\n\"for p>1:\\n\"\n\" I[u] = int_Omega (1/p) |grad u|^p + (1/2) u^2 - f u.\\n\"\n\"The strong form equation, namely setting the gradient to zero, is a PDE\\n\"\n\" - div( |grad u|^{p-2} grad u ) + u = f\\n\"\n\"subject to homogeneous Neumann boundary conditions. Implements objective\\n\"\n\"and gradient (residual) but no Hessian (Jacobian). Defaults to linear\\n\"\n\"problem (p=2) and quadrature degree 2. Can be run with only an objective\\n\" \"function; use -ph_no_gradient -snes_fd_function.\\n\\n\";\n\n#include \n#include \"../interlude/quadrature.h\"\n\ntypedef struct {\n PetscReal p, eps;\n PetscInt quadpts;\n PetscReal (*f)(PetscReal x, PetscReal y, PetscReal p, PetscReal eps);\n} PHelmCtx;\n\nstatic PetscReal f_constant(PetscReal x, PetscReal y, PetscReal p, PetscReal eps) {\n return 1.0;\n}\n\nstatic PetscReal u_exact_cosines(PetscReal x, PetscReal y, PetscReal p, PetscReal eps) {\n return PetscCosReal(PETSC_PI * x) * PetscCosReal(PETSC_PI * y);\n}\n\nstatic PetscReal f_cosines(PetscReal x, PetscReal y, PetscReal p, PetscReal eps) {\n const PetscReal uu = u_exact_cosines(x,y,p,eps),\n pi2 = PETSC_PI * PETSC_PI,\n lapu = - 2 * pi2 * uu;\n if (p == 2.0) {\n return - lapu + uu;\n } else {\n const PetscReal\n ux = - PETSC_PI * PetscSinReal(PETSC_PI * x)\n * PetscCosReal(PETSC_PI * y),\n uy = - PETSC_PI * PetscCosReal(PETSC_PI * x)\n * PetscSinReal(PETSC_PI * y),\n // note regularization changes f(x,y) but not u(x,y):\n w = ux * ux + uy * uy + eps * eps,\n pi3 = pi2 * PETSC_PI,\n wx = pi3 * PetscSinReal(2 * PETSC_PI * x)\n * PetscCosReal(2 * PETSC_PI * y),\n wy = pi3 * PetscCosReal(2 * PETSC_PI * x)\n * PetscSinReal(2 * PETSC_PI * y);\n const PetscReal s = (p - 2) / 2; // -1/2 <= s <= 0\n return - s * PetscPowScalar(w,s-1) * (wx * ux + wy * uy)\n - PetscPowScalar(w,s) * lapu + uu;\n }\n}\n\ntypedef enum {CONSTANT, COSINES} ProblemType;\nstatic const char* ProblemTypes[] = {\"constant\",\"cosines\",\n \"ProblemType\", \"\", NULL};\n\nextern PetscErrorCode GetVecFromFunction(DMDALocalInfo*, Vec,\n PetscReal (*)(PetscReal, PetscReal, PetscReal, PetscReal), PHelmCtx*);\nextern PetscErrorCode FormObjectiveLocal(DMDALocalInfo*, PetscReal**, PetscReal*, PHelmCtx*);\nextern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, PetscReal**, PetscReal**, PHelmCtx*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n DM da;\n SNES snes;\n Vec u_initial, u, u_exact;\n PHelmCtx user;\n DMDALocalInfo info;\n ProblemType problem = COSINES;\n PetscBool no_objective = PETSC_FALSE,\n no_gradient = PETSC_FALSE,\n exact_init = PETSC_FALSE,\n view_f = PETSC_FALSE;\n PetscReal err;\n\n ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr;\n\n user.p = 2.0;\n user.eps = 0.0;\n user.quadpts = 2;\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD,\"ph_\",\n \"p-Helmholtz solver options\",\"\"); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-eps\",\n \"regularization parameter eps\",\n \"phelm.c\",user.eps,&(user.eps),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-exact_init\",\n \"use exact solution to initialize\",\n \"phelm.c\",exact_init,&(exact_init),NULL);CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-no_objective\",\n \"do not set the objective evaluation function\",\n \"phelm.c\",no_objective,&(no_objective),NULL);CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-no_gradient\",\n \"do not set the residual evaluation function\",\n \"phelm.c\",no_gradient,&(no_gradient),NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-p\",\n \"exponent p > 1\",\n \"phelm.c\",user.p,&(user.p),NULL); CHKERRQ(ierr);\n if (user.p < 1.0) {\n SETERRQ(PETSC_COMM_SELF,1,\"p >= 1 required\");\n }\n if (user.p == 1.0) {\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"WARNING: well-posedness only known for p > 1\\n\"); CHKERRQ(ierr);\n }\n ierr = PetscOptionsEnum(\"-problem\",\n \"problem type determines right side f(x,y)\",\n \"phelm.c\",ProblemTypes,(PetscEnum)problem,(PetscEnum*)&problem,\n NULL); CHKERRQ(ierr);\n ierr = PetscOptionsInt(\"-quadpts\",\n \"number n of quadrature points in each direction (= 1,2,3 only)\",\n \"phelm.c\",user.quadpts,&(user.quadpts),NULL); CHKERRQ(ierr);\n if ((user.quadpts < 1) || (user.quadpts > 3)) {\n SETERRQ(PETSC_COMM_SELF,3,\"quadrature points n=1,2,3 only\");\n }\n ierr = PetscOptionsBool(\"-view_f\",\n \"view right-hand side to STDOUT\",\n \"phelm.c\",view_f,&(view_f),NULL);CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n ierr = DMDACreate2d(PETSC_COMM_WORLD,\n DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_BOX,\n 2,2,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da); CHKERRQ(ierr);\n ierr = DMSetFromOptions(da); CHKERRQ(ierr);\n ierr = DMSetUp(da); CHKERRQ(ierr);\n ierr = DMSetApplicationContext(da,&user);CHKERRQ(ierr);\n ierr = DMDASetUniformCoordinates(da,0.0,1.0,0.0,1.0,-1.0,-1.0); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n\n ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);\n ierr = SNESSetDM(snes,da); CHKERRQ(ierr);\n if (!no_objective) {\n ierr = DMDASNESSetObjectiveLocal(da,\n (DMDASNESObjective)FormObjectiveLocal,&user); CHKERRQ(ierr);\n }\n if (no_gradient) {\n // why isn't this the default? why no programmatic way to set?\n ierr = PetscOptionsSetValue(NULL,\"-snes_fd_function_eps\",\"0.0\"); CHKERRQ(ierr);\n } else {\n ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,\n (DMDASNESFunction)FormFunctionLocal,&user); CHKERRQ(ierr);\n }\n ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);\n\n // set initial iterate and right-hand side\n ierr = DMCreateGlobalVector(da,&u_initial);CHKERRQ(ierr);\n ierr = VecSet(u_initial,0.5); CHKERRQ(ierr);\n switch (problem) {\n case CONSTANT:\n if (exact_init) {\n ierr = VecSet(u_initial,1.0); CHKERRQ(ierr);\n }\n user.f = &f_constant;\n break;\n case COSINES:\n if (exact_init) {\n ierr = GetVecFromFunction(&info,u_initial,&u_exact_cosines,&user); CHKERRQ(ierr);\n }\n user.f = &f_cosines;\n break;\n default:\n SETERRQ(PETSC_COMM_SELF,4,\"unknown problem type\\n\");\n }\n\n // optionally view right-hand-side on initial grid\n if (view_f) {\n Vec vf;\n ierr = VecDuplicate(u_initial,&vf); CHKERRQ(ierr);\n switch (problem) {\n case CONSTANT:\n ierr = VecSet(vf,1.0); CHKERRQ(ierr);\n break;\n case COSINES:\n ierr = GetVecFromFunction(&info,vf,&f_cosines,&user); CHKERRQ(ierr);\n break;\n }\n ierr = VecView(vf,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);\n VecDestroy(&vf);\n }\n\n // solve and clean up\n ierr = SNESSolve(snes,NULL,u_initial); CHKERRQ(ierr);\n ierr = VecDestroy(&u_initial); CHKERRQ(ierr);\n ierr = DMDestroy(&da); CHKERRQ(ierr);\n ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr);\n ierr = SNESGetDM(snes,&da); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n\n // evaluate numerical error\n ierr = VecDuplicate(u,&u_exact); CHKERRQ(ierr);\n switch (problem) {\n case CONSTANT:\n ierr = VecSet(u_exact,1.0); CHKERRQ(ierr);\n break;\n case COSINES:\n ierr = GetVecFromFunction(&info,u_exact,&u_exact_cosines,&user); CHKERRQ(ierr);\n break;\n }\n ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); // u <- u + (-1.0) uexact\n ierr = VecNorm(u,NORM_INFINITY,&err); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"done on %d x %d grid with p=%.3f ...\\n\"\n \" numerical error: |u-u_exact|_inf = %.3e\\n\",\n info.mx,info.my,user.p,err); CHKERRQ(ierr);\n\n VecDestroy(&u_exact); SNESDestroy(&snes);\n return PetscFinalize();\n}\n\nPetscErrorCode GetVecFromFunction(DMDALocalInfo *info, Vec w,\n PetscReal (*fcn)(PetscReal, PetscReal, PetscReal, PetscReal),\n PHelmCtx *user) {\n PetscErrorCode ierr;\n const PetscReal hx = 1.0 / (info->mx - 1), hy = 1.0 / (info->my - 1);\n PetscReal x, y, **aw;\n PetscInt i, j;\n ierr = DMDAVecGetArray(info->da,w,&aw); CHKERRQ(ierr);\n for (j = info->ys; j < info->ys + info->ym; j++) {\n y = j * hy;\n for (i = info->xs; i < info->xs + info->xm; i++) {\n x = i * hx;\n aw[j][i] = (*fcn)(x,y,user->p,user->eps);\n }\n }\n ierr = DMDAVecRestoreArray(info->da,w,&aw); CHKERRQ(ierr);\n return 0;\n}\n\n//STARTFEM\nstatic PetscReal xiL[4] = { 1.0, -1.0, -1.0, 1.0},\n etaL[4] = { 1.0, 1.0, -1.0, -1.0};\n\nstatic PetscReal chi(PetscInt L, PetscReal xi, PetscReal eta) {\n return 0.25 * (1.0 + xiL[L] * xi) * (1.0 + etaL[L] * eta);\n}\n\n// evaluate v(xi,eta) on reference element using local node numbering\nstatic PetscReal eval(const PetscReal v[4], PetscReal xi, PetscReal eta) {\n return v[0] * chi(0,xi,eta) + v[1] * chi(1,xi,eta)\n + v[2] * chi(2,xi,eta) + v[3] * chi(3,xi,eta);\n}\n\ntypedef struct {\n PetscReal xi, eta;\n} gradRef;\n\nstatic gradRef dchi(PetscInt L, PetscReal xi, PetscReal eta) {\n const gradRef result = {0.25 * xiL[L] * (1.0 + etaL[L] * eta),\n 0.25 * etaL[L] * (1.0 + xiL[L] * xi)};\n return result;\n}\n\n// evaluate partial derivs of v(xi,eta) on reference element\nstatic gradRef deval(const PetscReal v[4], PetscReal xi, PetscReal eta) {\n gradRef sum = {0.0,0.0}, tmp;\n PetscInt L;\n for (L=0; L<4; L++) {\n tmp = dchi(L,xi,eta);\n sum.xi += v[L] * tmp.xi; sum.eta += v[L] * tmp.eta;\n }\n return sum;\n}\n\nstatic PetscReal GradInnerProd(PetscReal hx, PetscReal hy,\n gradRef du, gradRef dv) {\n const PetscReal cx = 4.0 / (hx * hx), cy = 4.0 / (hy * hy);\n return cx * du.xi * dv.xi + cy * du.eta * dv.eta;\n}\n\nstatic PetscReal GradPow(PetscReal hx, PetscReal hy,\n gradRef du, PetscReal P, PetscReal eps) {\n return PetscPowScalar(GradInnerProd(hx,hy,du,du) + eps*eps, P/2.0);\n}\n//ENDFEM\n\n/* FLOPS: (counting PetscPowScalar as 1)\n chi = 6\n eval = 4*6+7 = 31\n dchi = 8\n deval = 4*8+4 = 36\n GradInnerProd = 9\n GradPow = 9+4 = 13\n ObjIntegrandRef = deval + 2*eval + GradPow + 10 = 121\n FunIntegrandRef = chi + dchi + 2*eval + deval + GradPo + GradInnerProd + 9\n = 143\n*/\n\n//STARTOBJECTIVE\nstatic PetscReal ObjIntegrandRef(DMDALocalInfo *info,\n const PetscReal ff[4], const PetscReal uu[4],\n PetscReal xi, PetscReal eta, PHelmCtx *user) {\n const gradRef du = deval(uu,xi,eta);\n const PetscReal hx = 1.0 / (info->mx-1), hy = 1.0 / (info->my-1),\n u = eval(uu,xi,eta);\n return GradPow(hx,hy,du,user->p,0.0) / user->p + 0.5 * u * u\n - eval(ff,xi,eta) * u;\n}\n\nPetscErrorCode FormObjectiveLocal(DMDALocalInfo *info, PetscReal **au,\n PetscReal *obj, PHelmCtx *user) {\n PetscErrorCode ierr;\n const PetscReal hx = 1.0 / (info->mx-1), hy = 1.0 / (info->my-1);\n const Quad1D q = gausslegendre[user->quadpts-1];\n PetscReal x, y, lobj = 0.0;\n PetscInt i,j,r,s;\n MPI_Comm com;\n\n // loop over all elements\n for (j = info->ys; j < info->ys + info->ym; j++) {\n if (j == 0)\n continue;\n y = j * hy;\n for (i = info->xs; i < info->xs + info->xm; i++) {\n if (i == 0)\n continue;\n x = i * hx;\n const PetscReal ff[4] = {user->f(x,y,user->p,user->eps),\n user->f(x-hx,y,user->p,user->eps),\n user->f(x-hx,y-hy,user->p,user->eps),\n user->f(x,y-hy,user->p,user->eps)};\n const PetscReal uu[4] = {au[j][i],au[j][i-1],\n au[j-1][i-1],au[j-1][i]};\n // loop over quadrature points on this element\n for (r = 0; r < q.n; r++) {\n for (s = 0; s < q.n; s++) {\n lobj += q.w[r] * q.w[s]\n * ObjIntegrandRef(info,ff,uu,\n q.xi[r],q.xi[s],user);\n }\n }\n }\n }\n lobj *= hx * hy / 4.0; // from change of variables formula\n ierr = PetscObjectGetComm((PetscObject)(info->da),&com); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&lobj,obj,1,MPIU_REAL,MPIU_SUM,com); CHKERRQ(ierr);\n ierr = PetscLogFlops(129*info->xm*info->ym); CHKERRQ(ierr);\n return 0;\n}\n//ENDOBJECTIVE\n\n//STARTFUNCTION\nstatic PetscReal IntegrandRef(DMDALocalInfo *info, PetscInt L,\n const PetscReal ff[4], const PetscReal uu[4],\n PetscReal xi, PetscReal eta, PHelmCtx *user) {\n const gradRef du = deval(uu,xi,eta),\n dchiL = dchi(L,xi,eta);\n const PetscReal hx = 1.0 / (info->mx-1), hy = 1.0 / (info->my-1);\n return GradPow(hx,hy,du,user->p - 2.0,user->eps)\n * GradInnerProd(hx,hy,du,dchiL)\n + (eval(uu,xi,eta) - eval(ff,xi,eta)) * chi(L,xi,eta);\n}\n\nPetscErrorCode FormFunctionLocal(DMDALocalInfo *info, PetscReal **au,\n PetscReal **FF, PHelmCtx *user) {\n PetscErrorCode ierr;\n const PetscReal hx = 1.0 / (info->mx-1), hy = 1.0 / (info->my-1);\n const Quad1D q = gausslegendre[user->quadpts-1];\n const PetscInt li[4] = {0,-1,-1,0}, lj[4] = {0,0,-1,-1};\n PetscReal x, y;\n PetscInt i,j,l,r,s,PP,QQ;\n\n // clear residuals\n for (j = info->ys; j < info->ys + info->ym; j++)\n for (i = info->xs; i < info->xs + info->xm; i++)\n FF[j][i] = 0.0;\n\n // loop over all elements\n for (j = info->ys; j <= info->ys + info->ym; j++) {\n if ((j == 0) || (j > info->my-1))\n continue;\n y = j * hy;\n for (i = info->xs; i <= info->xs + info->xm; i++) {\n if ((i == 0) || (i > info->mx-1))\n continue;\n x = i * hx;\n const PetscReal ff[4] = {user->f(x,y,user->p,user->eps),\n user->f(x-hx,y,user->p,user->eps),\n user->f(x-hx,y-hy,user->p,user->eps),\n user->f(x,y-hy,user->p,user->eps)};\n const PetscReal uu[4] = {au[j][i],au[j][i-1],\n au[j-1][i-1],au[j-1][i]};\n // loop over corners of element i,j\n for (l = 0; l < 4; l++) {\n PP = i + li[l];\n QQ = j + lj[l];\n // only update residual if we own node\n if (PP >= info->xs && PP < info->xs + info->xm\n && QQ >= info->ys && QQ < info->ys + info->ym) {\n // loop over quadrature points\n for (r = 0; r < q.n; r++) {\n for (s = 0; s < q.n; s++) {\n FF[QQ][PP]\n += 0.25 * hx * hy * q.w[r] * q.w[s]\n * IntegrandRef(info,l,ff,uu,\n q.xi[r],q.xi[s],user);\n }\n }\n }\n }\n }\n }\n ierr = PetscLogFlops((5+q.n*q.n*149)*(info->xm+1)*(info->ym+1)); CHKERRQ(ierr);\n return 0;\n}\n//ENDFUNCTION\n\n", "meta": {"hexsha": "02251bd1617d52ff3b21433a630b59f449f4d055", "size": 16041, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch9/phelm.c", "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_issues_repo_path": "c/ch9/phelm.c", "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_forks_repo_path": "c/ch9/phelm.c", "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "avg_line_length": 39.4127764128, "max_line_length": 133, "alphanum_fraction": 0.5394302101, "num_tokens": 4803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7020359248561915}} {"text": "static char help[] =\n\"Structured-grid minimal surface equation (MSE) in 2D. Option prefix mse_.\\n\"\n\"Equation is\\n\"\n\" - div ( (1 + |grad u|^2)^q grad u ) = 0\\n\"\n\"on the unit square [0,1]x[0,1] subject to Dirichlet boundary\\n\"\n\"conditions u = g(x,y). Power q defaults to -1/2 (i.e. MSE) but is adjustable.\\n\"\n\"Catenoid and tent boundary conditions are implemented; catenoid is an exact\\n\"\n\"solution. We re-use the Jacobian from the Poisson equation, but it is suitable\\n\"\n\"only for low-amplitude g, or as preconditioning material in -snes_mf_operator.\\n\"\n\"Options -snes_fd_color and -snes_grid_sequence K are recommended.\\n\"\n\"This code is multigrid (GMG) capable.\\n\\n\";\n\n#include \n#include \"../ch6/poissonfunctions.h\"\n#include \"../quadrature.h\"\n\ntypedef struct {\n double q, // the exponent in the diffusivity;\n // =-1/2 for minimal surface eqn; =0 for Laplace eqn\n tent_H, // height of tent door along y=0 boundary\n catenoid_c; // parameter in catenoid formula\n int quaddegree; // quadrature degree used in -mse_monitor\n} MinimalCtx;\n\n// Dirichlet boundary conditions\nstatic double g_bdry_tent(double x, double y, double z, void *ctx) {\n PoissonCtx *user = (PoissonCtx*)ctx;\n MinimalCtx *mctx = (MinimalCtx*)(user->addctx);\n if (x < 1.0e-8) {\n return 2.0 * mctx->tent_H * (y < 0.5 ? y : 1.0 - y);\n } else\n return 0;\n}\n\nstatic double g_bdry_catenoid(double x, double y, double z, void *ctx) {\n PoissonCtx *user = (PoissonCtx*)ctx;\n MinimalCtx *mctx = (MinimalCtx*)(user->addctx);\n const double c = mctx->catenoid_c;\n return c * cosh(x/c) * sin(acos( (y/c) / cosh(x/c) ));\n}\n\n// the coefficient (diffusivity) of minimal surface equation, as a function\n// of w = |grad u|^2\nstatic double DD(double w, double q) {\n return pow(1.0 + w,q);\n}\n\ntypedef enum {TENT, CATENOID} ProblemType;\nstatic const char* ProblemTypes[] = {\"tent\",\"catenoid\",\n \"ProblemType\", \"\", NULL};\n\nextern PetscErrorCode FormExactFromG(DMDALocalInfo*, Vec, PoissonCtx*);\nextern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, double**,\n double **FF, PoissonCtx*);\nextern PetscErrorCode MSEMonitor(SNES, int, double, void*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n DM da;\n SNES snes;\n Vec u_initial, u;\n PoissonCtx user;\n MinimalCtx mctx;\n PetscBool monitor = PETSC_FALSE,\n exact_init = PETSC_FALSE;\n DMDALocalInfo info;\n ProblemType problem = CATENOID;\n\n // defaults:\n mctx.q = -0.5;\n mctx.tent_H = 1.0;\n mctx.catenoid_c = 1.1; // case shown in Figure in book\n mctx.quaddegree = 3;\n user.cx = 1.0;\n user.cy = 1.0;\n user.cz = 1.0;\n\n PetscInitialize(&argc,&argv,NULL,help);\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD,\"mse_\",\n \"minimal surface equation solver options\",\"\"); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-catenoid_c\",\n \"parameter for problem catenoid; c >= 1 required\",\n \"minimal.c\",mctx.catenoid_c,&(mctx.catenoid_c),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-exact_init\",\n \"initial Newton iterate = continuum exact solution; only for catenoid\",\n \"minimal.c\",exact_init,&(exact_init),NULL);CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-monitor\",\n \"print surface area and diffusivity bounds at each SNES iteration\",\n \"minimal.c\",monitor,&(monitor),NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-q\",\n \"power of (1+|grad u|^2) in diffusivity\",\n \"minimal.c\",mctx.q,&(mctx.q),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsInt(\"-quaddegree\",\n \"quadrature degree (=1,2,3) used in -mse_monitor\",\n \"minimal.c\",mctx.quaddegree,&(mctx.quaddegree),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnum(\"-problem\",\n \"problem type determines boundary conditions\",\n \"minimal.c\",ProblemTypes,(PetscEnum)problem,(PetscEnum*)&problem,\n NULL); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-tent_H\",\n \"'door' height for problem tent\",\n \"minimal.c\",mctx.tent_H,&(mctx.tent_H),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n user.addctx = &mctx; // attach MSE-specific parameters\n switch (problem) {\n case TENT:\n if (exact_init) {\n SETERRQ(PETSC_COMM_WORLD,2,\n \"initialization with exact solution only possible for -mse_problem catenoid\\n\");\n }\n user.g_bdry = &g_bdry_tent;\n break;\n case CATENOID:\n if (mctx.catenoid_c < 1.0) {\n SETERRQ(PETSC_COMM_WORLD,3,\n \"catenoid exact solution only valid if c >= 1\\n\");\n }\n if ((exact_init) && (mctx.q != -0.5)) {\n SETERRQ(PETSC_COMM_WORLD,4,\n \"initialization with catenoid exact solution only possible if q=-0.5\\n\");\n }\n user.g_bdry = &g_bdry_catenoid;\n break;\n default:\n SETERRQ(PETSC_COMM_WORLD,5,\"unknown problem type\\n\");\n }\n\n ierr = DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE,\n DMDA_STENCIL_BOX, // contrast with fish2\n 3,3,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da); CHKERRQ(ierr);\n ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr);\n ierr = DMSetFromOptions(da); CHKERRQ(ierr);\n ierr = DMSetUp(da); CHKERRQ(ierr); // this must be called BEFORE SetUniformCoordinates\n ierr = DMDASetUniformCoordinates(da,0.0,1.0,0.0,1.0,0.0,1.0); CHKERRQ(ierr);\n\n ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);\n ierr = SNESSetDM(snes,da); CHKERRQ(ierr);\n ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,\n (DMDASNESFunction)FormFunctionLocal,&user); CHKERRQ(ierr);\n // this is the Jacobian of the Poisson equation, thus ONLY APPROXIMATE;\n // generally use -snes_fd_color or -snes_mf_operator\n ierr = DMDASNESSetJacobianLocal(da,\n (DMDASNESJacobian)Poisson2DJacobianLocal,&user); CHKERRQ(ierr);\n if (monitor) {\n ierr = SNESMonitorSet(snes,MSEMonitor,&user,NULL); CHKERRQ(ierr);\n }\n ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);\n\n ierr = DMGetGlobalVector(da,&u_initial); CHKERRQ(ierr);\n if ((problem == CATENOID) && (mctx.q == -0.5) && (exact_init)) {\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n ierr = FormExactFromG(&info,u_initial,&user); CHKERRQ(ierr);\n } else {\n // initial iterate has u=g on boundary and u=0 in interior\n ierr = InitialState(da, ZEROS, PETSC_TRUE, u_initial, &user); CHKERRQ(ierr);\n }\n\n//STARTSNESSOLVE\n ierr = SNESSolve(snes,NULL,u_initial); CHKERRQ(ierr);\n ierr = DMRestoreGlobalVector(da,&u_initial); CHKERRQ(ierr);\n ierr = DMDestroy(&da); CHKERRQ(ierr);\n ierr = SNESGetDM(snes,&da); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\"done on %d x %d grid and problem %s\",\n info.mx,info.my,ProblemTypes[problem]); CHKERRQ(ierr);\n ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr);\n//ENDSNESSOLVE\n\n // evaluate numerical error in exact solution case\n if ((problem == CATENOID) && (mctx.q == -0.5)) {\n Vec u_exact;\n double errnorm;\n ierr = VecDuplicate(u,&u_exact); CHKERRQ(ierr);\n ierr = FormExactFromG(&info,u_exact,&user); CHKERRQ(ierr);\n ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); // u <- u + (-1.0) uexact\n ierr = VecDestroy(&u_exact); CHKERRQ(ierr);\n ierr = VecNorm(u,NORM_INFINITY,&errnorm); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \": error |u-uexact|_inf = %.5e\\n\",errnorm); CHKERRQ(ierr);\n } else {\n ierr = PetscPrintf(PETSC_COMM_WORLD,\" ...\\n\"); CHKERRQ(ierr);\n }\n\n ierr = SNESDestroy(&snes); CHKERRQ(ierr);\n return PetscFinalize();\n}\n\nPetscErrorCode FormExactFromG(DMDALocalInfo *info, Vec uexact,\n PoissonCtx *user) {\n PetscErrorCode ierr;\n int i, j;\n double xymin[2], xymax[2], hx, hy, x, y, **auexact;\n ierr = DMDAGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr);\n hx = (xymax[0] - xymin[0]) / (info->mx - 1);\n hy = (xymax[1] - xymin[1]) / (info->my - 1);\n ierr = DMDAVecGetArray(info->da,uexact,&auexact); CHKERRQ(ierr);\n for (j = info->ys; j < info->ys + info->ym; j++) {\n y = j * hy;\n for (i = info->xs; i < info->xs + info->xm; i++) {\n x = i * hx;\n auexact[j][i] = user->g_bdry(x,y,0.0,user);\n }\n }\n ierr = DMDAVecRestoreArray(info->da,uexact,&auexact); CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode FormFunctionLocal(DMDALocalInfo *info, double **au,\n double **FF, PoissonCtx *user) {\n PetscErrorCode ierr;\n MinimalCtx *mctx = (MinimalCtx*)(user->addctx);\n int i, j;\n double xymin[2], xymax[2], hx, hy, hxhy, hyhx, x, y,\n ue, uw, un, us, une, use, unw, usw,\n dux, duy, De, Dw, Dn, Ds;\n ierr = DMDAGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr);\n hx = (xymax[0] - xymin[0]) / (info->mx - 1);\n hy = (xymax[1] - xymin[1]) / (info->my - 1);\n hxhy = hx / hy;\n hyhx = hy / hx;\n for (j = info->ys; j < info->ys + info->ym; j++) {\n y = j * hy;\n for (i = info->xs; i < info->xs + info->xm; i++) {\n x = i * hx;\n if (j==0 || i==0 || i==info->mx-1 || j==info->my-1) {\n FF[j][i] = au[j][i] - user->g_bdry(x,y,0.0,user);\n } else {\n // assign neighbor values with either boundary condition or\n // current u at that point (==> symmetric matrix)\n ue = (i+1 == info->mx-1) ? user->g_bdry(x+hx,y,0.0,user)\n : au[j][i+1];\n uw = (i-1 == 0) ? user->g_bdry(x-hx,y,0.0,user)\n : au[j][i-1];\n un = (j+1 == info->my-1) ? user->g_bdry(x,y+hy,0.0,user)\n : au[j+1][i];\n us = (j-1 == 0) ? user->g_bdry(x,y-hy,0.0,user)\n : au[j-1][i];\n if (i+1 == info->mx-1 || j+1 == info->my-1) {\n une = user->g_bdry(x+hx,y+hy,0.0,user);\n } else {\n une = au[j+1][i+1];\n }\n if (i-1 == 0 || j+1 == info->my-1) {\n unw = user->g_bdry(x-hx,y+hy,0.0,user);\n } else {\n unw = au[j+1][i-1];\n }\n if (i+1 == info->mx-1 || j-1 == 0) {\n use = user->g_bdry(x+hx,y-hy,0.0,user);\n } else {\n use = au[j-1][i+1];\n }\n if (i-1 == 0 || j-1 == 0) {\n usw = user->g_bdry(x-hx,y-hy,0.0,user);\n } else {\n usw = au[j-1][i-1];\n }\n // gradient (dux,duy) at east point (i+1/2,j):\n dux = (ue - au[j][i]) / hx;\n duy = (un + une - us - use) / (4.0 * hy);\n De = DD(dux * dux + duy * duy, mctx->q);\n // ... at west point (i-1/2,j):\n dux = (au[j][i] - uw) / hx;\n duy = (unw + un - usw - us) / (4.0 * hy);\n Dw = DD(dux * dux + duy * duy, mctx->q);\n // ... at north point (i,j+1/2):\n dux = (ue + une - uw - unw) / (4.0 * hx);\n duy = (un - au[j][i]) / hy;\n Dn = DD(dux * dux + duy * duy, mctx->q);\n // ... at south point (i,j-1/2):\n dux = (ue + use - uw - usw) / (4.0 * hx);\n duy = (au[j][i] - us) / hy;\n Ds = DD(dux * dux + duy * duy, mctx->q);\n // evaluate residual\n FF[j][i] = - hyhx * (De * (ue - au[j][i]) - Dw * (au[j][i] - uw))\n - hxhy * (Dn * (un - au[j][i]) - Ds * (au[j][i] - us));\n }\n }\n }\n return 0;\n}\n\n// compute surface area and bounds on diffusivity using Q^1 elements and\n// tensor product gaussian quadrature\nPetscErrorCode MSEMonitor(SNES snes, int its, double norm, void *user) {\n PetscErrorCode ierr;\n PoissonCtx *pctx = (PoissonCtx*)(user);\n MinimalCtx *mctx = (MinimalCtx*)(pctx->addctx);\n DM da;\n Vec u, uloc;\n DMDALocalInfo info;\n const Quad1D q = gausslegendre[mctx->quaddegree-1]; // from ../quadrature.h\n double xymin[2], xymax[2], hx, hy, **au, x_i, y_j, x, y,\n ux, uy, W, D,\n Dminloc = PETSC_INFINITY, Dmaxloc = 0.0, Dmin, Dmax,\n arealoc = 0.0, area;\n int i, j, r, s;\n MPI_Comm comm;\n ierr = SNESGetDM(snes, &da); CHKERRQ(ierr);\n ierr = SNESGetSolution(snes, &u); CHKERRQ(ierr);\n ierr = DMGetLocalVector(da, &uloc); CHKERRQ(ierr);\n ierr = DMGlobalToLocalBegin(da, u, INSERT_VALUES, uloc); CHKERRQ(ierr);\n ierr = DMGlobalToLocalEnd(da, u, INSERT_VALUES, uloc); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n ierr = DMDAGetBoundingBox(info.da,xymin,xymax); CHKERRQ(ierr);\n hx = (xymax[0] - xymin[0]) / (info.mx - 1);\n hy = (xymax[1] - xymin[1]) / (info.my - 1);\n ierr = DMDAVecGetArrayRead(da,uloc,&au); CHKERRQ(ierr);\n//STARTMONITORLOOP\n // loop over rectangular cells in grid\n for (j = info.ys; j < info.ys + info.ym; j++) {\n if (j == 0)\n continue;\n y_j = j * hy; // NE corner of cell is (x_i,y_j)\n for (i = info.xs; i < info.xs + info.xm; i++) {\n if (i == 0)\n continue;\n x_i = i * hx;\n // loop over quadrature points in cell\n for (r = 0; r < q.n; r++) {\n x = x_i - hx + hx * 0.5 * (q.xi[r] + 1);\n for (s = 0; s < q.n; s++) {\n y = y_j - hy + hy * 0.5 * (q.xi[s] + 1);\n // gradient of u(x,y) at a quadrature point\n ux = (au[j][i] - au[j][i-1]) * (y - (y_j - hy))\n + (au[j-1][i] - au[j-1][i-1]) * (y_j - y);\n ux /= hx * hy;\n uy = (au[j][i] - au[j-1][i]) * (x - (x_i - hx))\n + (au[j][i-1] - au[j-1][i-1]) * (x_i - x);\n uy /= hx * hy;\n W = ux * ux + uy * uy;\n // min and max of diffusivity at quadrature points\n D = DD(W,mctx->q);\n Dminloc = PetscMin(Dminloc,D);\n Dmaxloc = PetscMax(Dmaxloc,D);\n // apply quadrature in surface area formula\n arealoc += q.w[r] * q.w[s] * PetscSqrtReal(1.0 + W);\n }\n }\n }\n }\n//ENDMONITORLOOP\n ierr = DMDAVecRestoreArrayRead(da,uloc,&au); CHKERRQ(ierr);\n ierr = DMRestoreLocalVector(da, &uloc); CHKERRQ(ierr);\n\n // do global reductions and report\n ierr = PetscObjectGetComm((PetscObject)da,&comm); CHKERRQ(ierr);\n arealoc *= hx * hy / 4.0; // from change of variables formula\n ierr = MPI_Allreduce(&arealoc,&area,1,MPI_DOUBLE,MPI_SUM,comm); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&Dminloc,&Dmin,1,MPI_DOUBLE,MPI_MIN,comm); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&Dmaxloc,&Dmax,1,MPI_DOUBLE,MPI_MAX,comm); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\"area = %.8f; %.4f <= D <= %.4f\\n\",\n area,Dmin,Dmax); CHKERRQ(ierr);\n return 0;\n}\n\n", "meta": {"hexsha": "9016ae45cd2d452c6bc62e0bef192cc874be3837", "size": 16125, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch7/minimal.c", "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/ch7/minimal.c", "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/ch7/minimal.c", "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0418994413, "max_line_length": 100, "alphanum_fraction": 0.5193178295, "num_tokens": 4742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.701822825843912}} {"text": "#include \n#include \n#include \n#include \n#include \n\nstatic int\nhilbert_matrix(gsl_matrix * m)\n{\n const size_t N = m->size1;\n const size_t M = m->size2;\n size_t i, j;\n\n for (i = 0; i < N; i++)\n {\n for (j = 0; j < M; j++)\n {\n gsl_matrix_set(m, i, j, 1.0/(i+j+1.0));\n }\n }\n\n return GSL_SUCCESS;\n}\n\nint\nmain()\n{\n const size_t n = 10; /* number of observations */\n const size_t p = 8; /* number of model parameters */\n size_t i;\n gsl_matrix *X = gsl_matrix_alloc(n, p);\n gsl_vector *y = gsl_vector_alloc(n);\n\n /* construct Hilbert matrix and rhs vector */\n hilbert_matrix(X);\n\n {\n double val = 1.0;\n for (i = 0; i < n; ++i)\n {\n gsl_vector_set(y, i, val);\n val *= -1.0;\n }\n }\n\n {\n const size_t npoints = 200; /* number of points on L-curve and GCV curve */\n gsl_multifit_linear_workspace *w =\n gsl_multifit_linear_alloc(n, p);\n gsl_vector *c = gsl_vector_alloc(p); /* OLS solution */\n gsl_vector *c_lcurve = gsl_vector_alloc(p); /* regularized solution (L-curve) */\n gsl_vector *c_gcv = gsl_vector_alloc(p); /* regularized solution (GCV) */\n gsl_vector *reg_param = gsl_vector_alloc(npoints);\n gsl_vector *rho = gsl_vector_alloc(npoints); /* residual norms */\n gsl_vector *eta = gsl_vector_alloc(npoints); /* solution norms */\n gsl_vector *G = gsl_vector_alloc(npoints); /* GCV function values */\n double lambda_l; /* optimal regularization parameter (L-curve) */\n double lambda_gcv; /* optimal regularization parameter (GCV) */\n double G_gcv; /* G(lambda_gcv) */\n size_t reg_idx; /* index of optimal lambda */\n double rcond; /* reciprocal condition number of X */\n double chisq, rnorm, snorm;\n\n /* compute SVD of X */\n gsl_multifit_linear_svd(X, w);\n\n rcond = gsl_multifit_linear_rcond(w);\n fprintf(stderr, \"matrix condition number = %e\\n\", 1.0 / rcond);\n\n /* unregularized (standard) least squares fit, lambda = 0 */\n gsl_multifit_linear_solve(0.0, X, y, c, &rnorm, &snorm, w);\n chisq = pow(rnorm, 2.0);\n\n fprintf(stderr, \"\\n=== Unregularized fit ===\\n\");\n fprintf(stderr, \"residual norm = %g\\n\", rnorm);\n fprintf(stderr, \"solution norm = %g\\n\", snorm);\n fprintf(stderr, \"chisq/dof = %g\\n\", chisq / (n - p));\n\n /* calculate L-curve and find its corner */\n gsl_multifit_linear_lcurve(y, reg_param, rho, eta, w);\n gsl_multifit_linear_lcorner(rho, eta, ®_idx);\n\n /* store optimal regularization parameter */\n lambda_l = gsl_vector_get(reg_param, reg_idx);\n\n /* regularize with lambda_l */\n gsl_multifit_linear_solve(lambda_l, X, y, c_lcurve, &rnorm, &snorm, w);\n chisq = pow(rnorm, 2.0) + pow(lambda_l * snorm, 2.0);\n\n fprintf(stderr, \"\\n=== Regularized fit (L-curve) ===\\n\");\n fprintf(stderr, \"optimal lambda: %g\\n\", lambda_l);\n fprintf(stderr, \"residual norm = %g\\n\", rnorm);\n fprintf(stderr, \"solution norm = %g\\n\", snorm);\n fprintf(stderr, \"chisq/dof = %g\\n\", chisq / (n - p));\n\n /* calculate GCV curve and find its minimum */\n gsl_multifit_linear_gcv(y, reg_param, G, &lambda_gcv, &G_gcv, w);\n\n /* regularize with lambda_gcv */\n gsl_multifit_linear_solve(lambda_gcv, X, y, c_gcv, &rnorm, &snorm, w);\n chisq = pow(rnorm, 2.0) + pow(lambda_gcv * snorm, 2.0);\n\n fprintf(stderr, \"\\n=== Regularized fit (GCV) ===\\n\");\n fprintf(stderr, \"optimal lambda: %g\\n\", lambda_gcv);\n fprintf(stderr, \"residual norm = %g\\n\", rnorm);\n fprintf(stderr, \"solution norm = %g\\n\", snorm);\n fprintf(stderr, \"chisq/dof = %g\\n\", chisq / (n - p));\n\n /* output L-curve and GCV curve */\n for (i = 0; i < npoints; ++i)\n {\n printf(\"%e %e %e %e\\n\",\n gsl_vector_get(reg_param, i),\n gsl_vector_get(rho, i),\n gsl_vector_get(eta, i),\n gsl_vector_get(G, i));\n }\n\n /* output L-curve corner point */\n printf(\"\\n\\n%f %f\\n\",\n gsl_vector_get(rho, reg_idx),\n gsl_vector_get(eta, reg_idx));\n\n /* output GCV curve corner minimum */\n printf(\"\\n\\n%e %e\\n\",\n lambda_gcv,\n G_gcv);\n\n gsl_multifit_linear_free(w);\n gsl_vector_free(c);\n gsl_vector_free(c_lcurve);\n gsl_vector_free(reg_param);\n gsl_vector_free(rho);\n gsl_vector_free(eta);\n gsl_vector_free(G);\n }\n\n gsl_matrix_free(X);\n gsl_vector_free(y);\n\n return 0;\n}\n", "meta": {"hexsha": "8f448d67371fb546e42c058ec245f37ff9ced79e", "size": 4632, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/fitreg2.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/fitreg2.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/fitreg2.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 32.3916083916, "max_line_length": 98, "alphanum_fraction": 0.5902417962, "num_tokens": 1359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88720460564669, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7013621440054625}} {"text": "#ifndef KABSCH_RMSD\n#define KABSCH_RMSD\n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\nnamespace kabsch\n{\n\n/**\n\n\tCalculates the RMSD \n\n\t@param P - coordinates of molecule P\n\t@param Q - coordinates of molecule Q\n\t@param N - number of atoms\n\n\t@return double - the RMSD\n\n**/\ntemplate \ndouble rmsd(\n\tM *P,\n\tM *Q,\n\tconst unsigned int N)\n{\n double rmsd {0.0};\n const unsigned int D {3};\n\tconst unsigned int size = N*D;\n\n for(unsigned int i = 0; i < size; ++i) {\n rmsd += (P[i] - Q[i])*(P[i] - Q[i]);\n }\n\n return sqrt(rmsd/N);\n}\n\n\ntemplate \nM* centroid(\n\tM *coordinates,\n\tunsigned int n_atoms)\n{\n double x {0};\n double y {0};\n double z {0};\n // unsigned int size = sizeof(coordinates);\n // unsigned int n_atoms = size / 3;\n\n\tconst unsigned int size = n_atoms*3;\n\n unsigned int i = 0;\n while(i\nMatrix* multiply(Matrix *A, Matrix *B,\n const int M,\n const int N,\n const int K)\n{\n double one = 1.0;\n\n\t// TODO Matrix C[M*N] = {0}\n\t// Compilers doesnt like the following syntax\n\tMatrix *C = new Matrix[M*N] {0};\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n M, N, K, one,\n A, K,\n B, N, one,\n C, N);\n\n return C;\n}\n\n\ntemplate \nMatrix* transpose_multiply(\n\tMatrix *A,\n\tMatrix *B,\n const int M,\n const int N,\n const int K)\n{\n double one = 1.0;\n\n Matrix *C = new Matrix[M*N] {0};\n\n cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans,\n M, N, K, one,\n A, M,\n B, N, one,\n C, N);\n\n return C;\n}\n\n\ntemplate \nstd::tuple matrix_svd(\n\tMatrix *A,\n\tint rows,\n\tint cols)\n{\n // lapack_int LAPACKE_dgesvd( int matrix_layout, char jobu, char jobvt,\n // lapack_int m, lapack_int n,\n // double* a, lapack_int lda,\n // double* s, double* u, lapack_int ldu,\n // double* vt, lapack_int ldvt,\n // double* superb );\n\n Matrix *U = new Matrix[cols*rows] {0};\n Matrix *S = new Matrix[rows] {0};\n Matrix *VT = new Matrix[cols*rows] {0};\n Matrix *superb = new Matrix[cols*rows] {0};\n int info;\n\n info = LAPACKE_dgesvd(LAPACK_ROW_MAJOR, 'A', 'A',\n rows, cols,\n A, rows,\n S,\n U, rows,\n VT, rows,\n superb);\n\n if(info > 0)\n {\n // TODO What if failed\n }\n\n\tdelete[] superb;\n\n return std::make_tuple(U, S, VT);\n}\n\n\ntemplate \ndouble determinant3x3(M A)\n{\n // determinant of a square 3x3 matrix\n double det = A[0]*A[4]*A[8]\n +A[1]*A[5]*A[6]\n +A[2]*A[3]*A[7]\n -A[2]*A[4]*A[6]\n -A[1]*A[3]*A[8]\n -A[0]*A[5]*A[7];\n\n return det;\n}\n\n\ntemplate \nM* kabsch(\n\tM *P,\n\tM *Q,\n\tconst T n_atoms)\n{\n\t// M *U = new M[3*3] {0};\n\t// U[0] = 1.0;\n\t// U[4] = 1.0;\n\t// U[8] = 1.0;\n\t// return U;\n\n M *U;\n M *S;\n M *V;\n\n M *C = transpose_multiply(P, Q, 3, 3, n_atoms);\n\n\tstd::tie(U, S, V) = matrix_svd(C, 3, 3);\n\n // Getting the sign of the det(U)*(V) to decide whether we need to correct\n // our rotation matrix to ensure a right-handed coordinate system.\n if(determinant3x3(U)*determinant3x3(V) < 0.0)\n {\n\t\tU[3*0+2] = -U[3*0+2];\n\t\tU[3*2+2] = -U[3*1+2];\n\t\tU[3*1+2] = -U[3*2+2];\n }\n\n\n M *rotation = multiply(U, V, 3, 3, 3);\n\n\tdelete[] C;\n\tdelete[] U;\n\tdelete[] S;\n\tdelete[] V;\n\n return rotation;\n}\n\n\ntemplate \nM* kabsch_rotate(\n\tM *P,\n\tM *Q,\n\tT n_atoms)\n{\n M *U = kabsch(P, Q, n_atoms);\n M *product = multiply(P, U, n_atoms, 3, 3);\n\tdelete[] U;\n return product;\n}\n\n\ntemplate \ndouble kabsch_rmsd(\n\tM *P,\n\tM *Q,\n\tT n_atoms)\n{\n M *P_rotated = kabsch_rotate(P, Q, n_atoms);\n\tdouble rmsdval = rmsd(P_rotated, Q, n_atoms);\n\tdelete[] P_rotated;\n\treturn rmsdval;\n}\n\n} // namespace rmsd\n\n#endif\n", "meta": {"hexsha": "9cc718d7d0cd29b5c9b2d47221c1509f50a8c9ce", "size": 4170, "ext": "h", "lang": "C", "max_stars_repo_path": "src/worker/deprecated/kabsch.h", "max_stars_repo_name": "chemspacelab/clockwork", "max_stars_repo_head_hexsha": "0956d8d29417a974809166857de9a978d7fac677", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/worker/deprecated/kabsch.h", "max_issues_repo_name": "chemspacelab/clockwork", "max_issues_repo_head_hexsha": "0956d8d29417a974809166857de9a978d7fac677", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2019-01-04T10:55:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-23T11:02:59.000Z", "max_forks_repo_path": "src/worker/deprecated/kabsch.h", "max_forks_repo_name": "chemspacelab/clockwork", "max_forks_repo_head_hexsha": "0956d8d29417a974809166857de9a978d7fac677", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-23T15:15:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-23T15:15:00.000Z", "avg_line_length": 16.9512195122, "max_line_length": 78, "alphanum_fraction": 0.5565947242, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.7012604471386028}} {"text": "\r\n#include \r\n#include \r\n\r\nint main (void)\r\n{\r\n int n = 11;\r\n double x[11] = {10.0, 8.0, 13.0, 9.0, 11.0,\r\n 14.0 ,6.0, 4.0 , 12.0,7.0,5.0};\r\n double y[11] = {8.04, 6.95,7.68, 8.81, 8.33,\r\n 9.96, 7.24,4.26,10.84, 4.82,5.68 };\r\n\r\n double c0, c1, cov00, cov01, cov11, sumsq;\r\n\r\n gsl_fit_linear(x, 1, y, 1, n,\r\n &c0, &c1, &cov00, &cov01, &cov11,\r\n &sumsq);\r\n\r\n printf (\"best fit: Y = %g + %g X\\n\", c0, c1);\r\n printf (\"covariance matrix:\\n\");\r\n printf (\"[ %g, %g\\n %g, %g]\\n\", cov00, cov01, cov01, cov11);\r\n printf (\"sumsq = %g\\n\", sumsq);\r\n printf (\"\\n\");\r\n \r\n // plot\r\n FILE *pipe = popen(\"gnuplot -persist\", \"w\"); // Open a pipe to gnuplot\r\n if (pipe) // If gnuplot is found\r\n { \r\n fprintf(pipe, \"set term wx\\n\"); // set the terminal\r\n fprintf(pipe, \"set xlabel 'X'\\n\");\r\n fprintf(pipe, \"set ylabel 'Y'\\n\");\r\n fprintf(pipe, \"set xrange [0:20]\\n\");\r\n fprintf(pipe, \"set yrange [2:14]\\n\");\r\n fprintf(pipe, \"set title ' and Linear fit:y=%.4f*x+%.4f'\\n\",c1,c0);\r\n \r\n /* In this case, the datafile is written directly to the gnuplot pipe with no need for a temporary file.\r\n The special filename '-' specifies that the data are inline; i.e., they follow the command.\r\n 1 sending gnuplot the plot '-' command \r\n 2 followed by data points \r\n 3 followed by the letter \"e\" \r\n */\r\n \r\n // 1 sending gnuplot the plot '-' command\r\n fprintf(pipe, \"plot '-' title '' with points pt 7 lc rgb 'blue',\\\r\n '-' title 'Line' with linespoints pt 6 lc rgb 'red'\\n\");\r\n \r\n // 2 followed by data points: \r\n for (int i = 0; i < n; i++)\r\n {\r\n fprintf(pipe, \"%lf %lf\\n\", x[i], y[i]);\r\n }\r\n // 3 followed by the letter \"e\" \r\n fprintf(pipe, \"e\");\r\n \r\n // linear fit\r\n fprintf(pipe,\"\\n\"); // start a new draw item\r\n fprintf(pipe, \"%lf %lf\\n\", 0.0, c0+c1*0,0);\r\n for (int i = 0; i < n; i++)\r\n {\r\n fprintf(pipe, \"%lf %lf\\n\", x[i], c0+c1*x[i]);\r\n }\r\n fprintf(pipe, \"%lf %lf\\n\", 20.0,c0+c1*20,0);\r\n fprintf(pipe, \"e\");\r\n \r\n fflush(pipe);\r\n fprintf(pipe, \"exit \\n\"); // exit gnuplot\r\n pclose(pipe); //close pipe\r\n }\r\n \r\n return 0;\r\n}\r\n", "meta": {"hexsha": "a0caf8402ed5b8f30fa064403a2db861ffd5873b", "size": 2343, "ext": "c", "lang": "C", "max_stars_repo_path": "notebook/demo/src/gnuplot_pipe_array.c", "max_stars_repo_name": "marketmodelbrokendown/1", "max_stars_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebook/demo/src/gnuplot_pipe_array.c", "max_issues_repo_name": "marketmodelbrokendown/1", "max_issues_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-18T21:55:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-18T21:55:20.000Z", "max_forks_repo_path": "notebook/demo/src/gnuplot_pipe_array.c", "max_forks_repo_name": "marketmodelbrokendown/1", "max_forks_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "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": 32.5416666667, "max_line_length": 110, "alphanum_fraction": 0.4950917627, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.7004715149103936}}