{"text": "/*****************************************\nEmitting C Generated Code\n*******************************************/\n#include \n#include \n#include \n#include \n#include \n/**************** Snippet ****************/\nvoid Snippet(int x0) {\n float x1[3] = { 1.0, 2.0, 3.0 };\n float x2[6] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };\n float x3[6] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };\n float* x4 = (float*)malloc(1 * sizeof(float));\n int x5 = 0;\n while (x5 != 3) {\n int x6 = x5;\n x4[0] = x4[0] + x1[x6] * x1[x6];\n x5 = x5 + 1;\n }\n int x7 = 0;\n while (x7 != 1) {\n printf(\"%f \", x4[x7]);\n x7 = x7 + 1;\n }\n float* x8 = (float*)malloc(2 * sizeof(float));\n cblas_sgemv(CblasRowMajor, CblasNoTrans, 2, 3, 1.0, x2, 3, x1, 1, 0.0, x8, 1);\n int x9 = 0;\n while (x9 != 2) {\n printf(\"%f \", x8[x9]);\n x9 = x9 + 1;\n }\n float* x10 = (float*)malloc(4 * sizeof(float));\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 2, 2, 3, 1.0, x2, 3, x3, 2, 0.0, x10, 2);\n int x11 = 0;\n while (x11 != 4) {\n printf(\"%f \", x10[x11]);\n x11 = x11 + 1;\n }\n}\n/*****************************************\nEnd of C Generated Code\n*******************************************/\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n printf(\"usage: %s \\n\", argv[0]);\n return 0;\n }\n Snippet(atoi(argv[1]));\n return 0;\n}\n", "meta": {"hexsha": "aa664a285934a236c5b0f73fb5c89f6b01a180d6", "size": 1372, "ext": "c", "lang": "C", "max_stars_repo_path": "src/out/transformer/tensor2/dot.check.c", "max_stars_repo_name": "Shangyint/lms-clean", "max_stars_repo_head_hexsha": "46dcf45b297bb537ce90d9c787dbf3700b47d54c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2017-04-19T17:19:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T04:14:18.000Z", "max_issues_repo_path": "src/out/transformer/tensor2/dot.check.c", "max_issues_repo_name": "Shangyint/lms-clean", "max_issues_repo_head_hexsha": "46dcf45b297bb537ce90d9c787dbf3700b47d54c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2019-09-10T01:17:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-14T21:22:03.000Z", "max_forks_repo_path": "src/out/transformer/tensor2/dot.check.c", "max_forks_repo_name": "Shangyint/lms-clean", "max_forks_repo_head_hexsha": "46dcf45b297bb537ce90d9c787dbf3700b47d54c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T12:16:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T04:45:52.000Z", "avg_line_length": 26.3846153846, "max_line_length": 98, "alphanum_fraction": 0.444606414, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5998718493161682}} {"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2019 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 main() {\n int n = 4;\n double** a = alloc_dmatrix(n, n);\n mat_elem(a, 0, 0) = 0.959291425205444;\n mat_elem(a, 0, 1) = 0.257508254123736;\n mat_elem(a, 0, 2) = 0.243524968724989;\n mat_elem(a, 0, 3) = 0.251083857976031;\n mat_elem(a, 1, 0) = 0.547215529963803;\n mat_elem(a, 1, 1) = 0.840717255983663;\n mat_elem(a, 1, 2) = 0.929263623187228;\n mat_elem(a, 1, 3) = 0.616044676146639;\n mat_elem(a, 2, 0) = 0.138624442828679;\n mat_elem(a, 2, 1) = 0.254282178971531;\n mat_elem(a, 2, 2) = 0.349983765984809;\n mat_elem(a, 2, 3) = 0.473288848902729;\n mat_elem(a, 3, 0) = 0.149294005559057;\n mat_elem(a, 3, 1) = 0.814284826068816;\n mat_elem(a, 3, 2) = 0.196595250431208;\n mat_elem(a, 3, 3) = 0.351659507062997;\n double* x = alloc_dvector(n);\n x[0] = 0.830828627896291;\n x[1] = 0.585264091152724;\n x[2] = 0.549723608291140;\n x[3] = 0.917193663829810;\n double* y = alloc_dvector(n);\n y[0] = 0.961898080855054;\n y[1] = 0.00463422413406744;\n y[2] = 0.774910464711502;\n y[3] = 0.817303220653433;\n double alpha = 2.3;\n double beta = 0.5;\n\n printf(\"a: \"); fprint_dmatrix(stdout, n, n, a);\n printf(\"x: \"); fprint_dvector(stdout, n, x);\n printf(\"y: \"); fprint_dvector(stdout, n, y);\n \n cblas_dgemv(CblasColMajor, CblasNoTrans, n, n, alpha, mat_ptr(a), n, vec_ptr(x), 1,\n beta, vec_ptr(y), 1);\n\n printf(\"%10.5f * a * x + %10.5f * y: \", alpha, beta); fprint_dvector(stdout, n, y);\n\n free_dmatrix(a);\n free_dvector(x);\n free_dvector(y);\n}\n\n/* gemv.m\n\nA = [0.959291425205444,0.257508254123736,0.243524968724989,0.251083857976031;0.547215529963803,0.840717255983663,0.929263623187228,0.616044676146639;0.138624442828679,0.254282178971531,0.349983765984809,0.473288848902729;0.149294005559057,0.814284826068816,0.196595250431208,0.351659507062997]\nx = [0.830828627896291;0.585264091152724;0.549723608291140;0.917193663829810]\ny = [0.961898080855054;0.00463422413406744;0.774910464711502;0.817303220653433]\n2.3 * A * x + 0.5 * y\n\n*/\n", "meta": {"hexsha": "116b5a9020b27fad80deed29fec629d791568a82", "size": 2486, "ext": "c", "lang": "C", "max_stars_repo_path": "example/blas/dgemv.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/blas/dgemv.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/blas/dgemv.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": 35.5142857143, "max_line_length": 293, "alphanum_fraction": 0.6460176991, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.5997881475386025}} {"text": "#include \n#include \n#include \n#include \n\n#define N_OF_RUNS 10\n\n#define RUSAGE_DIFF(r1, r2) \\\n ((double) ((r1).tv_sec - (r2).tv_sec) + (double) ((r1).tv_nsec - (r2).tv_nsec)/(double)1E9)\n\n\ngsl_matrix* random_matrix(size_t);\ninline gsl_matrix* zero_matrix(const size_t size);\n\ndouble* naive_test(size_t);\ndouble* better_test(size_t);\ndouble* dgemm_test(size_t);\n\nvoid test_suite(size_t, size_t, size_t, const char*);\n\nint main() {\n srand48((unsigned int)time(NULL));\n const char filename[] = \"results_unoptimized.csv\";\n test_suite(100, 1000, 100, filename);\n return 0;\n}\n\nvoid test_suite(const size_t from, const size_t to, const size_t step, const char* filename){\n FILE* file = fopen(filename, \"w\");\n if(file == NULL){\n printf(\"Error opening file, exiting \\r\\n\");\n exit(EXIT_FAILURE);\n }\n fprintf(file, \"METHOD,SIZE,TIME\\r\\n\");\n\n double* naive_result, * dgemm_result, * better_result;\n\n for(size_t i = from; i <= to; i += step){\n for(int j = 0; j < N_OF_RUNS; j++) {\n naive_result = naive_test(i);\n better_result = better_test(i);\n dgemm_result = dgemm_test(i);\n fprintf(file, \"Naive,%d,%lf\\r\\n\", (int) i, *naive_result);\n fprintf(file, \"Better,%d,%lf\\r\\n\", (int) i, *better_result);\n fprintf(file, \"BLAS,%d,%lf\\r\\n\", (int) i, *dgemm_result);\n free(naive_result);\n free(better_result);\n free(dgemm_result);\n }\n }\n\n fclose(file);\n}\n\n\ngsl_matrix* random_matrix(const size_t size) {\n gsl_matrix* a = gsl_matrix_calloc(size, size);\n for(int i = 0; i < size; i++)\n for(int j = 0; j < size; j++)\n gsl_matrix_set(a, (size_t)i, (size_t)j, drand48()*10);\n return a;\n}\n\ngsl_matrix* zero_matrix(const size_t size) {\n gsl_matrix* a = gsl_matrix_calloc(size, size);\n return a;\n}\n\ndouble** random_double_matrix(const size_t size) {\n double** a = calloc(size, sizeof(double*));\n for(int i = 0; i < size; i++)\n a[i] = calloc(size, sizeof(double));\n\n for(int i = 0; i < size; i++)\n for(int j = 0; j < size; j++)\n a[i][j] = drand48() * 10;\n return a;\n}\n\ndouble** zero_double_matrix(const size_t size) {\n double** a = calloc(size, sizeof(double*));\n for(int i = 0; i < size; i++)\n a[i] = calloc(size, sizeof(double));\n return a;\n}\n\nvoid free_double_matrix(double** matrix, const size_t size){\n for(int i = 0; i < size; i++)\n free(matrix[i]);\n free(matrix);\n}\n\ndouble* naive_test(const size_t size) {\n double** m_1 = random_double_matrix(size);\n double** m_2 = random_double_matrix(size);\n double** m_3 = zero_double_matrix(size);\n\n printf(\"Multiplying matrices of size %d using naive method\\r\\n\", (int)size);\n\n struct timespec real_start, real_end;\n clock_gettime(CLOCK_REALTIME, &real_start);\n\n for(int k = 0; k < size; k++)\n for(int j = 0; j < size; j++)\n for(int i = 0; i < size; i++)\n m_3[i][j] += m_1[i][k] * m_2[k][j];\n\n clock_gettime(CLOCK_REALTIME, &real_end);\n\n double* time = malloc(sizeof(double));\n *time = RUSAGE_DIFF(real_end, real_start);\n printf(\"Real time = %lf \\r\\n\", *time);\n free_double_matrix(m_1, size); free_double_matrix(m_2, size); free_double_matrix(m_3, size);\n return time;\n}\n\ndouble* better_test(const size_t size) {\n double** m_1 = random_double_matrix(size);\n double** m_2 = random_double_matrix(size);\n double** m_3 = zero_double_matrix(size);\n\n printf(\"Multiplying matrices of size %d using better method\\r\\n\", (int)size);\n\n struct timespec real_start, real_end;\n clock_gettime(CLOCK_REALTIME, &real_start);\n\n for(int i = 0; i < size; i++)\n for(int j = 0; j < size; j++)\n for(int k = 0; k < size; k++)\n m_3[i][j] += m_1[i][k] * m_2[k][j];\n\n clock_gettime(CLOCK_REALTIME, &real_end);\n\n double* time = malloc(sizeof(double));\n *time = RUSAGE_DIFF(real_end, real_start);\n printf(\"Real time = %lf \\r\\n\", *time);\n free_double_matrix(m_1, size); free_double_matrix(m_2, size); free_double_matrix(m_3, size);\n return time;\n}\n\ndouble* dgemm_test(const size_t size) {\n gsl_matrix* m_1 = random_matrix(size);\n gsl_matrix* m_2 = random_matrix(size);\n gsl_matrix* m_3 = zero_matrix(size);\n\n printf(\"Multiplying matrices of size %d using BLAS\\r\\n\", (int)size);\n\n struct timespec real_start, real_end;\n clock_gettime(CLOCK_REALTIME, &real_start);\n\n gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, m_1, m_2, 0.0, m_3);\n\n clock_gettime(CLOCK_REALTIME, &real_end);\n\n double* time = malloc(sizeof(double));\n *time = RUSAGE_DIFF(real_end, real_start);\n printf(\"Real time = %lf \\r\\n\", *time);\n gsl_matrix_free(m_1); gsl_matrix_free(m_2); gsl_matrix_free(m_3);\n return time;\n}", "meta": {"hexsha": "6d88989bbf2330eefacc8f28ee4764e288fe340f", "size": 4869, "ext": "c", "lang": "C", "max_stars_repo_path": "lab_3/main.c", "max_stars_repo_name": "kamilok1965/CMfSaT", "max_stars_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-09T18:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-09T18:59:11.000Z", "max_issues_repo_path": "lab_3/main.c", "max_issues_repo_name": "kamilok1965/CMfSaT", "max_issues_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "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": "lab_3/main.c", "max_forks_repo_name": "kamilok1965/CMfSaT", "max_forks_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-13T10:05:17.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-13T10:05:17.000Z", "avg_line_length": 30.43125, "max_line_length": 96, "alphanum_fraction": 0.6220989936, "num_tokens": 1419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.5997881422581891}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* Your function must have the following signature: */\n\nvoid sgemm( int m, int n, float *A, float *C );\n\n/* The benchmarking program */\n\nint main( int argc, char **argv )\n{\n srand(time(NULL));\n\n int n;\n double sum= 0;\n for(n = 32; n < 101; n+=54)\n \n /* Try different m */\n for( int m = 1000; m <10001; m+=511 )\n {\n /* Allocate and fill 2 random matrices A, C */\n float *A = (float*) malloc( m * n * sizeof(float) );\n float *C = (float*) malloc( m * m * sizeof(float) );\n \n for( int i = 0; i < m*n; i++ ) A[i] = 2 * drand48() - 1;\n for( int i = 0; i < m*m; i++ ) C[i] = 2 * drand48() - 1;\n \n /* measure Gflop/s rate; time a sufficiently long sequence of calls to eliminate noise */\n double Gflop_s, seconds = -1.0;\n for( int n_iterations = 1; seconds < 0.1; n_iterations *= 2 ) \n {\n /* warm-up */\n sgemm( m, n, A, C );\n /* measure time */\n struct timeval start, end;\n gettimeofday( &start, NULL );\n for( int i = 0; i < n_iterations; i++ )\n\tsgemm( m,n, A, C );\n gettimeofday( &end, NULL );\n seconds = (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);\n \n /* compute Gflop/s rate */\n Gflop_s = 2e-9 * n_iterations * m * m * n / seconds;\n\t }\n sum += Gflop_s;\n\n printf( \"%d by %d matrix \\t %g Gflop/s\\n\", m, n, Gflop_s );\n //printf( \"%g\\n\", Gflop_s );\n\n /* Ensure that error does not exceed the theoretical error bound */\n\t\t\n /* Set initial C to 0 and do matrix multiply of A*B */\n memset( C, 0, sizeof( float ) * m * m );\n sgemm( m,n, A, C );\n\n /* Subtract A*B from C using standard sgemm (note that this should be 0 to within machine roundoff) */\n cblas_sgemm( CblasColMajor,CblasNoTrans,CblasTrans, m,m,n, -1, A,m, A,m, 1, C,m );\n\n /* Subtract the maximum allowed roundoff from each element of C */\n for( int i = 0; i < m*n; i++ ) A[i] = fabs( A[i] );\n for( int i = 0; i < m*m; i++ ) C[i] = fabs( C[i] );\n cblas_sgemm( CblasColMajor,CblasNoTrans,CblasTrans, m,m,n, -3.0*FLT_EPSILON*n, A,m, A,m, 1, C,m );\n\n /* After this test if any element in C is still positive something went wrong in square_sgemm */\n for( int i = 0; i < m * m; i++ )\n if( C[i] > 0 ) {\n\tprintf( \"FAILURE: error in matrix multiply exceeds an acceptable margin\\n\" );\n\treturn -1;\n }\n\n /* release memory */\n free( C );\n free( A );\n }\n \n return 0;\n}\n", "meta": {"hexsha": "70bda94afb01266eb8740a2902c000eab5c13fad", "size": 2550, "ext": "c", "lang": "C", "max_stars_repo_path": "MatrixMultiply/benchmark.c", "max_stars_repo_name": "jasonaibrahim/AcademicWorks", "max_stars_repo_head_hexsha": "4c3e75f48bdafa02fabb551beb6ebf2fea871238", "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": "MatrixMultiply/benchmark.c", "max_issues_repo_name": "jasonaibrahim/AcademicWorks", "max_issues_repo_head_hexsha": "4c3e75f48bdafa02fabb551beb6ebf2fea871238", "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": "MatrixMultiply/benchmark.c", "max_forks_repo_name": "jasonaibrahim/AcademicWorks", "max_forks_repo_head_hexsha": "4c3e75f48bdafa02fabb551beb6ebf2fea871238", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3571428571, "max_line_length": 106, "alphanum_fraction": 0.5670588235, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5995414739130017}} {"text": "static char help[] =\n\"1D Stokes problem with DMDA and SNES. Option prefix -wel_.\\n\\n\";\n\n// show solution (staggered):\n// ./well -snes_monitor -snes_converged_reason -da_refine 7 -snes_monitor_solution draw -draw_pause 1\n\n// try:\n// -ksp_type preonly -pc_type svd [default]\n// -ksp_type minres -pc_type none -ksp_converged_reason\n// -ksp_type gmres -pc_type none -ksp_converged_reason\n// and fieldsplit below\n\n// Jacobian is correct and symmetric:\n// ./well -snes_monitor -da_refine 3 -snes_type test\n// ./well -snes_monitor -da_refine 3 -mat_is_symmetric\n\n// generate matrix in matlab\n// ./well -snes_converged_reason -da_refine 1 -mat_view ascii:foo.m:ascii_matlab\n// then:\n// >> M = [whos to get name]\n// >> A = M(1:2:end,1:2:end); BT = M(1:2:end,2:2:end); B = M(2:2:end,1:2:end); C = M(2:2:end,2:2:end); T = [A BT; B C]\n\n/* Schur-complement preconditioning:\n\n./well -snes_converged_reason -snes_monitor -da_refine 7 -ksp_type fgmres -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type lower -fieldsplit_pressure_pc_type none -ksp_converged_reason\n\n * see snes example ex70.c\n * note these -ksp_type also work: gmres, cgs, richardson\n * above is same as -fieldsplit_velocity_pc_type ilu\n\nwith minres need positive definite preconditioner so use -pc_fieldsplit_schur_fact_type diag (see http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/PC/PCFieldSplitSetSchurFactType.html):\n\n./well -snes_converged_reason -snes_monitor -da_refine 7 -ksp_type minres -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type diag -fieldsplit_pressure_pc_type none -ksp_converged_reason\n\nquote from http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/PC/PCFieldSplitSetSchurFactType.html:\n\n If applied exactly, FULL factorization is a direct solver. The preconditioned\n operator with LOWER or UPPER has all eigenvalues equal to 1 and minimal polynomial\n of degree 2, so KSPGMRES converges in 2 iterations. If the iteration count is very\n low, consider using KSPFGMRES or KSPGCR which can use one less preconditioner\n application in this case. Note that the preconditioned operator may be highly\n non-normal, so such fast convergence may not be observed in practice. With DIAG,\n the preconditioned operator has three distinct nonzero eigenvalues and minimal\n polynomial of degree at most 4, so KSPGMRES converges in at most 4 iterations.\n\n * indeed we see FULL converge in 1 iterations ... it IS a direct solver like SVD\n * and LOWER/UPPER + GMRES give convergence in 2 iterations as advertised\n * Murphy, Golub, Wathen (2000) explains final comment re DIAG and gmres\n * in practice DIAG + GMRES\n\nschur as direct solver:\n\n./well -snes_converged_reason -snes_monitor -da_refine 7 -ksp_type preonly -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type full -fieldsplit_pressure_pc_type none -ksp_converged_reason\n\nview all matrices (both interlaced and blocks) as dense with fieldsplit:\n\n./well -snes_converged_reason -snes_monitor -da_refine 1 -ksp_type preonly -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type full -fieldsplit_pressure_pc_type none -mat_view ::ascii_dense\n\nput diagonal blocks only in matlab files foov.m, foop.m (off-diagonal: how?)\n./well -snes_converged_reason -snes_monitor -da_refine 1 -ksp_type preonly -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type full -fieldsplit_pressure_pc_type none -fieldsplit_velocity_mat_view :foov.m:ascii_matlab -fieldsplit_pressure_mat_view :foop.m:ascii_matlab\n\n40 second run (linux-c-opt) on 8 million grid points:\n\ntimer ./well -snes_converged_reason -snes_monitor -da_refine 22 -ksp_type gmres -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type diag -fieldsplit_pressure_pc_type none -ksp_converged_reason -fieldsplit_velocity_ksp_type cg -fieldsplit_velocity_pc_type icc\n\n * also works with -ksp_type minres\n * also in parallel (no speedup) if -fieldsplit_velocity_pc_type bjacobi -fieldsplit_velocity_sub_pc_type icc\n*/\n\n#include \n#include \n\ntypedef enum {STAGGERED, REGULAR} SchemeType;\nstatic const char *SchemeTypes[] = {\"staggered\",\"regular\",\n \"SchemeType\", \"\", NULL};\n\ntypedef struct {\n double L, // length (height) of well (m)\n rho, // density of water (kg m-3)\n g, // acceleration of gravity (m s-2)\n mu; // dynamic viscosity of water (Pa s)\n SchemeType scheme;\n} AppCtx;\n\ntypedef struct {\n double u, p;\n} Field;\n\nPetscErrorCode ExactSolution(DMDALocalInfo *info, Vec X, AppCtx *user) {\n PetscErrorCode ierr;\n double h, x;\n Field *aX;\n int i;\n h = user->L / (info->mx-1);\n ierr = DMDAVecGetArray(info->da,X,&aX); CHKERRQ(ierr);\n for (i=info->xs; ixs+info->xm; i++) {\n aX[i].u = 0.0;\n if (user->scheme == STAGGERED)\n x = h * (i + 0.5);\n else\n x = h * i;\n if (i < info->mx - 1)\n aX[i].p = user->rho * user->g * (user->L - x);\n else\n aX[i].p = 0.0;\n }\n ierr = DMDAVecRestoreArray(info->da,X,&aX); CHKERRQ(ierr);\n return 0;\n}\n\n// the staggered version of residual evaluation F(X)\n// grid has p at staggered locations \"O\" where incompressibility u_x=0 is enforced\n// x_i-1 O x_i O x_i+1 O\n// u_i-1 u_i u_i+1\n// p_i-1 p_i p_i+1\nPetscErrorCode FormFunctionStaggeredLocal(DMDALocalInfo *info, Field *X,\n Field *F, AppCtx *user) {\n const double h = user->L / (info->mx-1),\n h2 = h * h;\n int i;\n for (i=info->xs; ixs+info->xm; i++) {\n if (i == 0) { // bottom of well\n F[i].u = X[i].u; // u(0) = 0\n F[i].p = - (X[i+1].u - 0.0) / h; // -u_x(0+1/2) = 0\n } else if (i == 1) {\n F[i].u = - user->mu * (X[i+1].u - 2 * X[i].u + 0.0) / h2 // -mu u_xx(x1) + p_x(x1) = - rho g\n + (X[i].p - X[i-1].p) / h\n + user->rho * user->g;\n F[i].p = - (X[i+1].u - X[i].u) / h; // - u_x(x1+1/2) = 0\n // generic cases: - mu u_xx(xi) + p_x(xi) = - rho g AND - u_x(xi+1/2) = 0\n } else if (i > 1 && i < info->mx - 1) {\n F[i].u = - user->mu * (X[i+1].u - 2 * X[i].u + X[i-1].u) / h2\n + (X[i].p - X[i-1].p) / h\n + user->rho * user->g;\n F[i].p = - (X[i+1].u - X[i].u) / h;\n } else if (i == info->mx - 1) { // top of well\n F[i].u = - user->mu * (- 2 * X[i].u + 2 * X[i-1].u) / h2 // -mu u_xx(xm-1) + p_x(xm-1) = - rho g\n + (- 2 * X[i-1].p) / h + user->rho * user->g; // and u_x(xm-1) = 0 and p(xm-1) = 0\n F[i].u /= 2; // for symmetry\n F[i].p = X[i].p; // no actual d.o.f. here\n } else {\n SETERRQ(PETSC_COMM_WORLD,1,\"no way to get here\");\n }\n }\n return 0;\n}\n\nPetscErrorCode FormFunctionRegularLocal(DMDALocalInfo *info, Field *X,\n Field *F, AppCtx *user) {\n const double h = user->L / (info->mx-1),\n h2 = h * h;\n int i;\n for (i=info->xs; ixs+info->xm; i++) {\n if (i == 0) { // bottom of well\n F[i].u = X[i].u; // u(0) = 0\n F[i].p = - (X[i+1].u - 0.0) / (2 * h); // -u_x(0+1/2) = 0 (and / 2 for symmetry)\n } else if (i == 1) {\n F[i].u = - user->mu * (X[i+1].u - 2 * X[i].u + 0.0) / h2 // -mu u_xx(x1) + p_x(x1) = - rho g\n + (X[i+1].p - X[i-1].p) / (2 * h)\n + user->rho * user->g;\n F[i].p = - (X[i+1].u - 0.0) / (2 * h); // - u_x(x1) = 0\n // generic cases: - mu u_xx(xi) + p_x(xi) = - rho g AND - u_x(xi) = 0\n//STARTREGFUNC\n } else if (i > 1 && i < info->mx - 2) {\n F[i].u = - user->mu * (X[i+1].u - 2 * X[i].u + X[i-1].u) / h2\n + (X[i+1].p - X[i-1].p) / (2 * h)\n + user->rho * user->g;\n F[i].p = - (X[i+1].u - X[i-1].u) / (2 * h);\n//ENDREGFUNC\n } else if (i == info->mx - 2) {\n F[i].u = - user->mu * (X[i+1].u - 2 * X[i].u + X[i-1].u) / h2 // -mu u_xx(xm-2) + p_x(xm-2) = - rho g\n + (0.0 - X[i-1].p) / (2 * h)\n + user->rho * user->g;\n F[i].p = - (X[i+1].u - X[i-1].u) / (2 * h); // - u_x(xm-2) = 0\n } else if (i == info->mx - 1) { // top of well\n F[i].u = - user->mu * (- 2 * X[i].u + 2 * X[i-1].u) / h2 // -mu u_xx(xm-1) + p_x(xm-1) = - rho g\n + (- X[i-1].p) / h + user->rho * user->g; // and u_x(xm-1) = 0 and p(xm-1) = 0\n F[i].u /= 2; // for symmetry\n F[i].p = X[i].p; // p(xm-1) = 0\n } else {\n SETERRQ(PETSC_COMM_WORLD,1,\"no way to get here\");\n }\n }\n return 0;\n}\n\nPetscErrorCode FormJacobianStaggeredLocal(DMDALocalInfo *info, double *X,\n Mat J, Mat P, AppCtx *user) {\n PetscErrorCode ierr;\n MatStencil col[5],row;\n double v[5];\n const double h = user->L / (info->mx-1),\n h2 = h * h;\n int i;\n for (i=info->xs; ixs+info->xm; i++) {\n row.i = i;\n if (i == 0) {\n row.c = 0; col[0].i = i; col[0].c = 0; v[0] = 1.0;\n ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);\n row.c = 1; col[0].i = i+1; col[0].c = 0; v[0] = - 1.0 / h;\n ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);\n } else if (i == 1) {\n row.c = 0;\n col[0].c = 0; col[0].i = i; v[0] = 2.0 * user->mu / h2;\n col[1].c = 0; col[1].i = i+1; v[1] = - user->mu / h2;\n col[2].c = 1; col[2].i = i; v[2] = 1.0 / h;\n col[3].c = 1; col[3].i = i-1; v[3] = - 1.0 / h;\n ierr = MatSetValuesStencil(P,1,&row,4,col,v,INSERT_VALUES); CHKERRQ(ierr);\n row.c = 1;\n col[0].c = 0; col[0].i = i; v[0] = 1.0 / h;\n col[1].c = 0; col[1].i = i+1; v[1] = - 1.0 / h;\n ierr = MatSetValuesStencil(P,1,&row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);\n } else if (i > 1 && i < info->mx - 1) {\n row.c = 0;\n col[0].c = 0; col[0].i = i; v[0] = 2.0 * user->mu / h2;\n col[1].c = 0; col[1].i = i-1; v[1] = - user->mu / h2;\n col[2].c = 0; col[2].i = i+1; v[2] = - user->mu / h2;\n col[3].c = 1; col[3].i = i; v[3] = 1.0 / h;\n col[4].c = 1; col[4].i = i-1; v[4] = - 1.0 / h;\n ierr = MatSetValuesStencil(P,1,&row,5,col,v,INSERT_VALUES); CHKERRQ(ierr);\n row.c = 1;\n col[0].c = 0; col[0].i = i; v[0] = 1.0 / h;\n col[1].c = 0; col[1].i = i+1; v[1] = - 1.0 / h;\n ierr = MatSetValuesStencil(P,1,&row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);\n } else if (i == info->mx - 1) {\n row.c = 0;\n col[0].c = 0; col[0].i = i; v[0] = user->mu / h2;\n col[1].c = 0; col[1].i = i-1; v[1] = - user->mu / h2;\n col[2].c = 1; col[2].i = i-1; v[2] = - 1.0 / h;\n ierr = MatSetValuesStencil(P,1,&row,3,col,v,INSERT_VALUES); CHKERRQ(ierr);\n row.c = 1;\n col[0].c = 1; col[0].i = i; v[0] = 1.0;\n ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);\n } else {\n SETERRQ(PETSC_COMM_WORLD,1,\"no way to get here\");\n }\n }\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 return 0;\n}\n\n\nPetscErrorCode FormJacobianRegularLocal(DMDALocalInfo *info, double *X,\n Mat J, Mat P, AppCtx *user) {\n PetscErrorCode ierr;\n MatStencil col[5],row;\n double v[5];\n const double h = user->L / (info->mx-1),\n h2 = h * h;\n int i;\n for (i=info->xs; ixs+info->xm; i++) {\n row.i = i;\n if (i == 0) {\n row.c = 0; col[0].i = i; col[0].c = 0; v[0] = 1.0;\n ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);\n row.c = 1; col[0].i = i+1; col[0].c = 0; v[0] = - 1.0 / (2.0 * h);\n ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);\n } else if (i == 1) {\n row.c = 0;\n col[0].c = 0; col[0].i = i; v[0] = 2.0 * user->mu / h2;\n col[1].c = 0; col[1].i = i+1; v[1] = - user->mu / h2;\n col[2].c = 1; col[2].i = i+1; v[2] = 1.0 / (2.0 * h);\n col[3].c = 1; col[3].i = i-1; v[3] = - 1.0 / (2.0 * h);\n ierr = MatSetValuesStencil(P,1,&row,4,col,v,INSERT_VALUES); CHKERRQ(ierr);\n row.c = 1;\n col[0].c = 0; col[0].i = i+1; v[0] = - 1.0 / (2.0 * h);\n ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);\n//STARTREGMAT\n } else if (i > 1 && i < info->mx - 2) {\n row.c = 0;\n col[0].c = 0; col[0].i = i; v[0] = 2.0 * user->mu / h2;\n col[1].c = 0; col[1].i = i-1; v[1] = - user->mu / h2;\n col[2].c = 0; col[2].i = i+1; v[2] = - user->mu / h2;\n col[3].c = 1; col[3].i = i+1; v[3] = 1.0 / (2.0 * h);\n col[4].c = 1; col[4].i = i-1; v[4] = - 1.0 / (2.0 * h);\n ierr = MatSetValuesStencil(P,1,&row,5,col,v,INSERT_VALUES); CHKERRQ(ierr);\n row.c = 1;\n col[0].c = 0; col[0].i = i-1; v[0] = 1.0 / (2.0 * h);\n col[1].c = 0; col[1].i = i+1; v[1] = - 1.0 / (2.0 * h);\n ierr = MatSetValuesStencil(P,1,&row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);\n//ENDREGMAT\n } else if (i == info->mx - 2) {\n row.c = 0;\n col[0].c = 0; col[0].i = i; v[0] = 2.0 * user->mu / h2;\n col[1].c = 0; col[1].i = i-1; v[1] = - user->mu / h2;\n col[2].c = 0; col[2].i = i+1; v[2] = - user->mu / h2;\n col[3].c = 1; col[3].i = i-1; v[3] = - 1.0 / (2.0 * h);\n ierr = MatSetValuesStencil(P,1,&row,4,col,v,INSERT_VALUES); CHKERRQ(ierr);\n row.c = 1;\n col[0].c = 0; col[0].i = i-1; v[0] = 1.0 / (2.0 * h);\n col[1].c = 0; col[1].i = i+1; v[1] = - 1.0 / (2.0 * h);\n ierr = MatSetValuesStencil(P,1,&row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);\n } else if (i == info->mx - 1) {\n row.c = 0;\n col[0].c = 0; col[0].i = i; v[0] = user->mu / h2;\n col[1].c = 0; col[1].i = i-1; v[1] = - user->mu / h2;\n col[2].c = 1; col[2].i = i-1; v[2] = - 1.0 / (2.0 * h);\n ierr = MatSetValuesStencil(P,1,&row,3,col,v,INSERT_VALUES); CHKERRQ(ierr);\n row.c = 1;\n col[0].c = 1; col[0].i = i; v[0] = 1.0;\n ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);\n } else {\n SETERRQ(PETSC_COMM_WORLD,1,\"no way to get here\");\n }\n }\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 return 0;\n}\n\n\nint main(int argc,char **args) {\n PetscErrorCode ierr;\n DM da;\n SNES snes;\n KSP ksp;\n PC pc;\n AppCtx user;\n Vec X, Xexact;\n PetscBool randominit = PETSC_FALSE, shorterrors = PETSC_FALSE;\n double uerrnorm, perrnorm, pnorm, setol = 1.0e-8;\n DMDALocalInfo info;\n\n PetscInitialize(&argc,&args,NULL,help);\n user.rho = 1000.0;\n user.g = 9.81;\n user.L = 10.0;\n user.mu = 1.0; // Pa s; = 1.0 for corn syrup; = 10^-3 for liquid water\n user.scheme = STAGGERED;\n\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD,\"well_\",\"options for well\",\"\"); CHKERRQ(ierr);\n ierr = PetscOptionsEnum(\"-scheme\",\"finite difference scheme type\",\n \"well.c\",SchemeTypes,\n (PetscEnum)user.scheme,(PetscEnum*)&user.scheme,NULL); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-randominit\",\"initialize u,p with random\",\n \"well.c\",randominit,&randominit,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-shorterrors\",\"abbreviated error output (e.g. for regression testing)\",\n \"well.c\",shorterrors,&shorterrors,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n ierr = DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,3,2,1,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 = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n ierr = DMDASetUniformCoordinates(da,0.0,user.L,0.0,1.0,0.0,1.0); CHKERRQ(ierr);\n ierr = DMDASetCoordinateName(da,0,\"x\"); CHKERRQ(ierr);\n ierr = DMDASetFieldName(da,0,\"velocity\"); CHKERRQ(ierr);\n ierr = DMDASetFieldName(da,1,\"pressure\"); CHKERRQ(ierr);\n\n ierr = DMCreateGlobalVector(da,&X); CHKERRQ(ierr);\n\n ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);\n ierr = SNESSetDM(snes,da); CHKERRQ(ierr);\n if (user.scheme == STAGGERED) {\n ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,\n (DMDASNESFunction)FormFunctionStaggeredLocal,&user); CHKERRQ(ierr);\n ierr = DMDASNESSetJacobianLocal(da,\n (DMDASNESJacobian)FormJacobianStaggeredLocal,&user); CHKERRQ(ierr);\n } else if (user.scheme == REGULAR) {\n ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,\n (DMDASNESFunction)FormFunctionRegularLocal,&user); CHKERRQ(ierr);\n ierr = DMDASNESSetJacobianLocal(da,\n (DMDASNESJacobian)FormJacobianRegularLocal,&user); CHKERRQ(ierr);\n } else {\n SETERRQ(PETSC_COMM_WORLD,1,\"no way to get here\");\n }\n // set defaults to -ksp_type preonly -pc_type svd ... which does not scale or parallelize but is robust\n ierr = SNESGetKSP(snes,&ksp); CHKERRQ(ierr);\n ierr = KSPSetType(ksp,KSPPREONLY); CHKERRQ(ierr);\n ierr = KSPGetPC(ksp,&pc); CHKERRQ(ierr);\n ierr = PCSetType(pc,PCSVD); CHKERRQ(ierr);\n ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);\n\n if (randominit) {\n PetscRandom rctx;\n ierr = PetscRandomCreate(PETSC_COMM_WORLD,&rctx); CHKERRQ(ierr);\n ierr = PetscRandomSetSeed(rctx,time(NULL)); CHKERRQ(ierr);\n ierr = PetscRandomSeed(rctx); CHKERRQ(ierr);\n ierr = VecSetRandom(X,rctx); CHKERRQ(ierr);\n ierr = PetscRandomDestroy(&rctx); CHKERRQ(ierr);\n } else {\n ierr = VecSet(X,0.0); CHKERRQ(ierr);\n }\n//ierr = VecView(X,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);\n\n ierr = SNESSolve(snes,NULL,X); CHKERRQ(ierr);\n\n ierr = VecDuplicate(X,&Xexact); CHKERRQ(ierr);\n ierr = ExactSolution(&info,Xexact,&user); CHKERRQ(ierr);\n\n//ierr = VecView(X,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);\n//ierr = VecView(Xexact,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);\n\n ierr = VecAXPY(X,-1.0,Xexact); CHKERRQ(ierr); // X <- X + (-1.0) Xexact\n ierr = VecStrideNorm(X,0,NORM_INFINITY,&uerrnorm); CHKERRQ(ierr);\n ierr = VecStrideNorm(X,1,NORM_INFINITY,&perrnorm); CHKERRQ(ierr);\n ierr = VecStrideNorm(Xexact,1,NORM_INFINITY,&pnorm); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"on %d point grid with h=%g and scheme = '%s':\\n\",\n info.mx,user.L/(info.mx-1),SchemeTypes[user.scheme]); CHKERRQ(ierr);\n if (shorterrors && uerrnorm < setol && perrnorm/pnorm < setol) {\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \" |u-uexact|_inf < %.1e, |p-pexact|_inf / |pexact|_inf < %.1e\\n\",\n setol,setol); CHKERRQ(ierr);\n } else {\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \" |u-uexact|_inf = %.3e, |p-pexact|_inf / |pexact|_inf = %.3e\\n\",\n uerrnorm,perrnorm/pnorm); CHKERRQ(ierr);\n }\n\n VecDestroy(&X); VecDestroy(&Xexact);\n SNESDestroy(&snes); DMDestroy(&da);\n return PetscFinalize();\n}\n\n", "meta": {"hexsha": "ff7b21b1c4adbdf6f7e626290b33800ba744c8a1", "size": 20997, "ext": "c", "lang": "C", "max_stars_repo_path": "c/junk/ch13/well.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/junk/ch13/well.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/junk/ch13/well.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": 49.058411215, "max_line_length": 292, "alphanum_fraction": 0.5346954327, "num_tokens": 7139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.5992117834907473}} {"text": "/* linalg/householdercomplex.c\n * \n * Copyright (C) 2001 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"gsl_linalg.h\"\n\ngsl_complex\ngsl_linalg_complex_householder_transform (gsl_vector_complex * v)\n{\n /* replace v[0:n-1] with a householder vector (v[0:n-1]) and\n coefficient tau that annihilate v[1:n-1] */\n\n const size_t n = v->size ;\n \n if (n == 1)\n {\n gsl_complex alpha = gsl_vector_complex_get (v, 0) ; \n double absa = gsl_complex_abs (alpha);\n double beta_r = - (GSL_REAL(alpha) >= 0 ? +1 : -1) * absa ;\n\n gsl_complex tau;\n GSL_REAL(tau) = (beta_r - GSL_REAL(alpha)) / beta_r ;\n GSL_IMAG(tau) = - GSL_IMAG(alpha) / beta_r ;\n\n {\n gsl_complex beta = gsl_complex_rect (beta_r, 0.0);\n gsl_vector_complex_set (v, 0, beta) ;\n }\n \n return tau;\n }\n else\n { \n gsl_complex tau ;\n double beta_r;\n\n gsl_vector_complex_view x = gsl_vector_complex_subvector (v, 1, n - 1) ; \n gsl_complex alpha = gsl_vector_complex_get (v, 0) ; \n double absa = gsl_complex_abs (alpha);\n double xnorm = gsl_blas_dznrm2 (&x.vector);\n \n if (xnorm == 0 && GSL_IMAG(alpha) == 0) \n {\n gsl_complex zero = gsl_complex_rect(0.0, 0.0);\n return zero; /* tau = 0 */\n }\n \n beta_r = - (GSL_REAL(alpha) >= 0 ? +1 : -1) * hypot(absa, xnorm) ;\n\n GSL_REAL(tau) = (beta_r - GSL_REAL(alpha)) / beta_r ;\n GSL_IMAG(tau) = - GSL_IMAG(alpha) / beta_r ;\n\n {\n gsl_complex amb = gsl_complex_sub_real(alpha, beta_r);\n gsl_complex s = gsl_complex_inverse(amb);\n gsl_blas_zscal (s, &x.vector);\n }\n \n {\n gsl_complex beta = gsl_complex_rect (beta_r, 0.0);\n gsl_vector_complex_set (v, 0, beta) ;\n }\n \n return tau;\n }\n}\n\nint\ngsl_linalg_complex_householder_hm (gsl_complex tau, const gsl_vector_complex * v, gsl_matrix_complex * A)\n{\n /* applies a householder transformation v,tau to matrix m */\n\n size_t i, j;\n\n if (GSL_REAL(tau) == 0.0 && GSL_IMAG(tau) == 0.0)\n {\n return GSL_SUCCESS;\n }\n\n /* w = (v' A)^T */\n\n for (j = 0; j < A->size2; j++)\n {\n gsl_complex tauwj;\n gsl_complex wj = gsl_matrix_complex_get(A,0,j); \n\n for (i = 1; i < A->size1; i++) /* note, computed for v(0) = 1 above */\n {\n gsl_complex Aij = gsl_matrix_complex_get(A,i,j);\n gsl_complex vi = gsl_vector_complex_get(v,i);\n gsl_complex Av = gsl_complex_mul (Aij, gsl_complex_conjugate(vi));\n wj = gsl_complex_add (wj, Av);\n }\n\n tauwj = gsl_complex_mul (tau, wj);\n\n /* A = A - v w^T */\n \n {\n gsl_complex A0j = gsl_matrix_complex_get (A, 0, j);\n gsl_complex Atw = gsl_complex_sub (A0j, tauwj);\n /* store A0j - tau * wj */\n gsl_matrix_complex_set (A, 0, j, Atw);\n }\n \n for (i = 1; i < A->size1; i++)\n {\n gsl_complex vi = gsl_vector_complex_get (v, i);\n gsl_complex tauvw = gsl_complex_mul(vi, tauwj);\n gsl_complex Aij = gsl_matrix_complex_get (A, i, j);\n gsl_complex Atwv = gsl_complex_sub (Aij, tauvw);\n /* store Aij - tau * vi * wj */\n gsl_matrix_complex_set (A, i, j, Atwv);\n }\n }\n \n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "9f0f5e91cdac3746c9714dbe61ab4b1230b6c383", "size": 4167, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/linalg/householdercomplex.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/householdercomplex.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/householdercomplex.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": 29.3450704225, "max_line_length": 105, "alphanum_fraction": 0.6025917927, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.7185944046238982, "lm_q1q2_score": 0.5988223973757721}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"tsvread.h\"\n\ntypedef struct {\n gsl_spline *spline;\n gsl_interp_accel *acc;\n int flags;\n double d;\n} f_param_t;\n\ndouble opt_func(unsigned n, const double *x, double *grad, void *f_data) {\n f_param_t *fparam = (f_param_t *)f_data;\n gsl_spline *spline_nu = fparam->spline;\n gsl_interp_accel *acc_nu = fparam->acc;\n int flags = fparam->flags;\n double d = fparam->d;\n return gsl_spline_eval(spline_nu, x[0], acc_nu);\n}\n\nint main(int argc, char **argv) {\n /* open file for reading data */\n tsv_t *tsv = tsv_fread(argv[1]);\n\n if (tsv->columns != 2) {\n fprintf(stderr, \"input file must be 2 colums tab seperated\\n\");\n return -1;\n }\n\n double *x_nu = (double *)malloc(tsv->rows * sizeof(double));\n double *y_nu = (double *)malloc(tsv->rows * sizeof(double));\n assert(x_nu != NULL);\n assert(y_nu != NULL);\n\n unsigned int i;\n for (i = 0; i < tsv->rows; i++) {\n x_nu[i] = tsv->data[i][0];\n y_nu[i] = tsv->data[i][1];\n }\n\n gsl_interp_accel *acc_nu = gsl_interp_accel_alloc();\n gsl_spline *spline_nu = gsl_spline_alloc(gsl_interp_cspline, tsv->rows);\n gsl_spline_init(spline_nu, x_nu, y_nu, tsv->rows);\n\n double x[1]; /* initial guess */\n double lb[1]; /* lower bound */\n double ub[1]; /* upper bound */\n double minf = 0;\n lb[0] = x_nu[0];\n ub[0] = x_nu[tsv->rows - 1];\n x[0] = x_nu[tsv->rows / 2];\n\n f_param_t *fparam = (f_param_t *)malloc(1 * sizeof(f_param_t));\n fparam->spline = spline_nu;\n fparam->acc = acc_nu;\n fparam->flags = 0;\n void *fvparam;\n fvparam = fparam;\n\n nlopt_opt opt;\n opt = nlopt_create(NLOPT_LN_NELDERMEAD, 1);\n nlopt_set_lower_bounds(opt, lb);\n nlopt_set_upper_bounds(opt, ub);\n nlopt_set_max_objective(opt, opt_func, fvparam);\n nlopt_set_xtol_rel(opt, 1e-16);\n // nlopt_set_ftol_abs(opt,1e-6);\n // nlopt_set_maxtime(opt,4);\n\n int err;\n double max_nu;\n err = nlopt_optimize(opt, x, &minf);\n if (err < 0) {\n fprintf(stderr, \"nlopt failed! %d\\n\", err);\n fprintf(stderr, \"lower: %g\\n\", lb[0]);\n fprintf(stderr, \"upper: %g\\n\", ub[0]);\n fprintf(stderr, \"guess: %g\\n\", x[0]);\n if (lb[0] > ub[0]) {\n fprintf(stderr, \"lower bigger than upper\\n\");\n }\n } else {\n max_nu = gsl_spline_eval(spline_nu, x[0], acc_nu);\n printf(\"Maximum: %.20g %.20g \\n\", x[0], max_nu);\n }\n\n nlopt_destroy(opt);\n tsv_free(tsv);\n free(x_nu);\n free(y_nu);\n\n return 0;\n}\n", "meta": {"hexsha": "2e43b04d832d5b5bdb75d00c6ffbbe583c329bcc", "size": 2596, "ext": "c", "lang": "C", "max_stars_repo_path": "extras/findmax/findmax.c", "max_stars_repo_name": "AaronWebster/directdebye", "max_stars_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "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": "extras/findmax/findmax.c", "max_issues_repo_name": "AaronWebster/directdebye", "max_issues_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "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": "extras/findmax/findmax.c", "max_forks_repo_name": "AaronWebster/directdebye", "max_forks_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4509803922, "max_line_length": 74, "alphanum_fraction": 0.6413713405, "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.59882237450649}} {"text": "static char help[] =\n\"Solve nonlinear Liouville-Bratu equation in 2D on a structured-grid. Option prefix lb_.\\n\"\n\"Solves\\n\"\n\" - nabla^2 u - lambda e^u = 0\\n\"\n\"on the unit square [0,1]x[0,1] subject to zero Dirichlet boundary conditions.\\n\"\n\"Critical value occurs about at lambda = 6.808. Optional exact solution\\n\"\n\"(Liouville 1853) in case lambda=1.0.\\n\\n\";\n\n/* compare:\ntimer ./bratu2D -snes_monitor -snes_converged_reason -ksp_converged_reason -pc_type mg -da_refine 8\n\ntimer ./bratu2D -snes_monitor -snes_converged_reason -ksp_converged_reason -pc_type mg -da_refine 8 -snes_fd_color\n\ntimer ./bratu2D -snes_monitor -snes_converged_reason -ksp_converged_reason -pc_type mg -da_refine 8 -snes_mf_operator\n\ntimer ./bratu2D -snes_monitor -snes_converged_reason -ksp_converged_reason -pc_type mg -snes_grid_sequence 8\n\ntimer ./bratu2D -snes_monitor -snes_converged_reason -lb_showcounts -da_refine 8 -snes_type fas -fas_levels_snes_type ngs -fas_coarse_snes_type ngs\n\ntimer mpiexec -n 4 ./bratu2D -snes_monitor -snes_converged_reason -lb_showcounts -da_refine 8 -snes_type fas -fas_levels_snes_type ngs -fas_coarse_snes_type ngs\n\ntimer ./bratu2D -snes_monitor -snes_converged_reason -lb_showcounts -da_refine 8 -snes_type fas -fas_levels_snes_type ngs -fas_coarse_snes_type ngs -fas_levels_snes_ngs_sweeps 2\n\ntimer ./bratu2D -snes_monitor -snes_converged_reason -lb_showcounts -da_refine 8 -snes_type fas -fas_levels_snes_type ngs -fas_coarse_snes_type newtonls -fas_coarse_ksp_type preonly -fas_coarse_pc_type cholesky\n\ntimer ./bratu2D -snes_monitor -snes_converged_reason -lb_showcounts -da_refine 8 -snes_type fas -fas_levels_snes_type ngs -fas_coarse_snes_type newtonls -fas_coarse_ksp_type cg -fas_coarse_pc_type icc -snes_fas_monitor -snes_fas_levels 6\n*/\n\n/* excellent evidence of convergence in Liouville exact solution case:\n$ for LEV in 3 4 5 6 7 8 9; do ./bratu2D -da_refine $LEV -snes_monitor -snes_fd_color -snes_rtol 1.0e-10 -lb_exact -pc_type mg; done\n*/\n\n#include \n#include \"../../ch6/poissonfunctions.h\"\n\ntypedef struct {\n PetscReal lambda;\n PetscBool exact;\n int residualcount, ngscount;\n} BratuCtx;\n\nstatic PetscReal g_zero(PetscReal x, PetscReal y, PetscReal z, void *ctx) {\n return 0.0;\n}\n\nstatic PetscReal g_liouville(PetscReal x, PetscReal y, PetscReal z, void *ctx) {\n PetscReal r2 = (x + 1.0) * (x + 1.0) + (y + 1.0) * (y + 1.0),\n qq = r2 * r2 + 1.0,\n omega = r2 / (qq * qq);\n return 32.0 * omega;\n}\n\nextern PetscErrorCode FormUExact(DMDALocalInfo*, Vec, PoissonCtx*);\nextern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, PetscReal **,\n PetscReal**, PoissonCtx*);\nextern PetscErrorCode NonlinearGS(SNES, Vec, Vec, void*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n DM da, da_after;\n SNES snes;\n Vec u, uexact;\n PoissonCtx user;\n BratuCtx bctx;\n DMDALocalInfo info;\n PetscBool showcounts = PETSC_FALSE;\n PetscLogDouble flops;\n PetscReal errinf;\n\n PetscInitialize(&argc,&argv,NULL,help);\n user.Lx = 1.0;\n user.Ly = 1.0;\n user.Lz = 1.0;\n user.cx = 1.0;\n user.cy = 1.0;\n user.cz = 1.0;\n user.g_bdry = &g_zero;\n bctx.lambda = 1.0;\n bctx.exact = PETSC_FALSE;\n bctx.residualcount = 0;\n bctx.ngscount = 0;\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD,\"lb_\",\"Liouville-Bratu equation solver options\",\"\"); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-lambda\",\"coefficient of e^u (reaction) term\",\n \"bratu2D.c\",bctx.lambda,&(bctx.lambda),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-exact\",\"use case of Liouville exact solution\",\n \"bratu2D.c\",bctx.exact,&(bctx.exact),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-showcounts\",\"at finish, print numbers of calls to call-back functions\",\n \"bratu2D.c\",showcounts,&showcounts,NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n if (bctx.exact) {\n if (bctx.lambda != 1.0) {\n SETERRQ(PETSC_COMM_SELF,1,\"Liouville exact solution only implemented for lambda = 1.0\\n\");\n }\n user.g_bdry = &g_liouville;\n }\n user.addctx = &bctx;\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 ierr = SNESSetNGS(snes,NonlinearGS,&user); CHKERRQ(ierr);\n // this is the Jacobian of the Poisson equation, thus ONLY APPROXIMATE\n // ... consider using -snes_fd_color or -snes_mf_operator\n ierr = DMDASNESSetJacobianLocal(da,\n (DMDASNESJacobian)Poisson2DJacobianLocal,&user); CHKERRQ(ierr);\n ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);\n\n ierr = DMGetGlobalVector(da,&u); CHKERRQ(ierr);\n ierr = VecSet(u,0.0); CHKERRQ(ierr); // initialize to zero\n ierr = SNESSolve(snes,NULL,u); CHKERRQ(ierr);\n ierr = DMRestoreGlobalVector(da,&u);CHKERRQ(ierr);\n ierr = DMDestroy(&da); CHKERRQ(ierr);\n\n if (showcounts) {\n ierr = PetscGetFlops(&flops); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\"flops = %.3e, residual calls = %d, NGS calls = %d\\n\",\n flops,bctx.residualcount,bctx.ngscount); CHKERRQ(ierr);\n }\n\n ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr);\n if (bctx.exact) {\n ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr); // SNES owns u; we do not destroy it\n ierr = VecDuplicate(u,&uexact); CHKERRQ(ierr);\n ierr = FormUExact(&info,uexact,&user); CHKERRQ(ierr);\n ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uexact\n ierr = VecDestroy(&uexact); CHKERRQ(ierr); // no longer needed\n ierr = VecNorm(u,NORM_INFINITY,&errinf); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"done on %d x %d grid: error |u-uexact|_inf = %.3e\\n\",\n info.mx,info.my,errinf); CHKERRQ(ierr);\n } else {\n ierr = PetscPrintf(PETSC_COMM_WORLD,\"done on %d x %d grid ...\\n\",info.mx,info.my); CHKERRQ(ierr);\n }\n\n ierr = SNESDestroy(&snes); CHKERRQ(ierr);\n return PetscFinalize();\n}\n\nPetscErrorCode FormUExact(DMDALocalInfo *info, Vec u, PoissonCtx* user) {\n PetscErrorCode ierr;\n BratuCtx *bctx = (BratuCtx*)(user->addctx);\n PetscInt i, j;\n PetscReal hx, hy, x, y, **au;\n if (user->g_bdry != &g_liouville) {\n SETERRQ(PETSC_COMM_SELF,1,\"exact solution only implemented for g_liouville() boundary conditions\\n\");\n }\n if (bctx->lambda != 1.0) {\n SETERRQ(PETSC_COMM_SELF,2,\"Liouville exact solution only implemented for lambda = 1.0\\n\");\n }\n hx = 1.0 / (PetscReal)(info->mx - 1);\n hy = 1.0 / (PetscReal)(info->my - 1);\n ierr = DMDAVecGetArray(info->da, u, &au);CHKERRQ(ierr);\n for (j=info->ys; jys+info->ym; j++) {\n y = j * hy;\n for (i=info->xs; ixs+info->xm; i++) {\n x = i * hx;\n au[j][i] = user->g_bdry(x,y,0.0,bctx);\n }\n }\n ierr = DMDAVecRestoreArray(info->da, u, &au);CHKERRQ(ierr);\n return 0;\n}\n\n// compute F(u), the residual of the discretized PDE on the given grid\nPetscErrorCode FormFunctionLocal(DMDALocalInfo *info, PetscReal **au,\n PetscReal **FF, PoissonCtx *user) {\n PetscErrorCode ierr;\n BratuCtx *bctx = (BratuCtx*)(user->addctx);\n PetscInt i, j;\n PetscReal hx, hy, darea, hxhy, hyhx, x, y;\n\n hx = 1.0 / (PetscReal)(info->mx - 1);\n hy = 1.0 / (PetscReal)(info->my - 1);\n darea = hx * hy;\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 if (j==0 || i==0 || i==info->mx-1 || j==info->my-1) {\n x = i * hx;\n FF[j][i] = au[j][i] - user->g_bdry(x,y,0.0,bctx);\n } else {\n FF[j][i] = hyhx * (2.0 * au[j][i] - au[j][i-1] - au[j][i+1])\n + hxhy * (2.0 * au[j][i] - au[j-1][i] - au[j+1][i])\n - darea * bctx->lambda * PetscExpScalar(au[j][i]);\n }\n }\n }\n ierr = PetscLogFlops(12.0 * info->xm * info->ym); CHKERRQ(ierr);\n (bctx->residualcount)++;\n return 0;\n}\n\n// do nonlinear Gauss-Seidel (processor-block) sweeps on\n// F(u) = b\nPetscErrorCode NonlinearGS(SNES snes, Vec u, Vec b, void *ctx) {\n PetscErrorCode ierr;\n PetscInt i, j, k, maxits, totalits=0, sweeps, l;\n PetscReal atol, rtol, stol, hx, hy, darea, hxhy, hyhx, x, y,\n **au, **ab, bij, uu, phi0, phi, dphidu, s;\n DM da;\n DMDALocalInfo info;\n PoissonCtx *user = (PoissonCtx*)(ctx);\n BratuCtx *bctx = (BratuCtx*)(user->addctx);\n Vec uloc;\n\n ierr = SNESNGSGetSweeps(snes,&sweeps);CHKERRQ(ierr);\n ierr = SNESNGSGetTolerances(snes,&atol,&rtol,&stol,&maxits);CHKERRQ(ierr);\n ierr = SNESGetDM(snes,&da);CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n\n hx = 1.0 / (PetscReal)(info.mx - 1);\n hy = 1.0 / (PetscReal)(info.my - 1);\n darea = hx * hy;\n hxhy = hx / hy;\n hyhx = hy / hx;\n\n ierr = DMGetLocalVector(da,&uloc);CHKERRQ(ierr);\n for (l=0; lg_bdry(x,y,0.0,bctx);\n } else {\n if (b)\n bij = ab[j][i];\n else\n bij = 0.0;\n // do pointwise Newton iterations on scalar function\n // phi(u) = hyhx * (2 u - au[j][i-1] - au[j][i+1])\n // + hxhy * (2 u - au[j-1][i] - au[j+1][i])\n // - darea * lambda * e^u - bij\n uu = au[j][i];\n phi0 = 0.0;\n for (k = 0; k < maxits; k++) {\n phi = hyhx * (2.0 * uu - au[j][i-1] - au[j][i+1])\n + hxhy * (2.0 * uu - au[j-1][i] - au[j+1][i])\n - darea * bctx->lambda * PetscExpScalar(uu) - bij;\n if (k == 0)\n phi0 = phi;\n dphidu = 2.0 * (hyhx + hxhy)\n - darea * bctx->lambda * PetscExpScalar(uu);\n s = - phi / dphidu; // Newton step\n uu += s;\n totalits++;\n if ( atol > PetscAbsReal(phi)\n || rtol*PetscAbsReal(phi0) > PetscAbsReal(phi)\n || stol*PetscAbsReal(uu) > PetscAbsReal(s) ) {\n break;\n }\n }\n au[j][i] = uu;\n }\n }\n }\n ierr = DMDAVecRestoreArray(da,uloc,&au);CHKERRQ(ierr);\n ierr = DMLocalToGlobalBegin(da,uloc,INSERT_VALUES,u);CHKERRQ(ierr);\n ierr = DMLocalToGlobalEnd(da,uloc,INSERT_VALUES,u);CHKERRQ(ierr);\n }\n ierr = DMRestoreLocalVector(da,&uloc);CHKERRQ(ierr);\n if (b) {\n ierr = DMDAVecRestoreArrayRead(da,b,&ab);CHKERRQ(ierr);\n }\n ierr = PetscLogFlops(21.0 * totalits); CHKERRQ(ierr);\n (bctx->ngscount)++;\n return 0;\n}\n\n", "meta": {"hexsha": "dc5fa4c51b276bfab4a86622781fb200f184abc1", "size": 12558, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch7/solns/bratu2D.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/ch7/solns/bratu2D.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/ch7/solns/bratu2D.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": 43.6041666667, "max_line_length": 237, "alphanum_fraction": 0.5785953177, "num_tokens": 3904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5987275687227918}} {"text": "/*\n * GaussianMixtureModel.h\n * Provides implementation of Gaussian Mixture Model return type.\n *\n Copyright 2017 Michal Gallus\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n#pragma once\n#include \n#include \n\nnamespace spectre::unsupervised::gmm\n{\n/// \n/// Represents a single component of a Gaussian Mixture.\n/// \nstruct GaussianComponent\n{\n /// \n /// Mean value of the component or peak's location.\n /// \n double mean;\n\n /// \n /// Standard deviation of the component or peak's width.\n /// \n double deviation;\n\n /// \n /// Weight of the component or peak's height.\n /// \n double weight;\n};\n\n/// \n/// Represents a composite of gaussian distribution components \n/// that build up a Gaussian Mixture Model.\n/// \nstruct GaussianMixtureModel\n{\n /// \n /// Constructor used for initialization of m/z, intesities and gaussian components\n /// collections.\n /// \n /// M/z data shared by all spectra.\n /// Mean intensities at each point.\n /// Number of Gaussian Components to be set.\n GaussianMixtureModel(const gsl::span &mzArray,\n const gsl::span &intensities,\n const std::vector &&components) :\n originalMzArray(mzArray.begin(), mzArray.end()),\n originalMeanSpectrum(intensities.begin(), intensities.end()),\n components(std::move(components)),\n isMerged(), isNoiseReduced(), mzMergingThreshold() // will be used in future.\n { }\n\n /// \n /// Collection of Gaussian components.\n /// \n const std::vector components;\n\n /// \n /// Collection of initially supplied mz values.\n /// \n const std::vector originalMzArray;\n\n /// \n /// Collection of average supplied spectra.\n /// \n const std::vector originalMeanSpectrum;\n\n /// \n /// M/z threshold used in components merging.\n /// \n const double mzMergingThreshold;\n\n /// \n /// Value indicating whether this instance is merged.\n /// \n const bool isMerged;\n\n /// \n /// Gets a value indicating whether this instance is noise components reduced.\n /// \n const bool isNoiseReduced;\n};\n}\n", "meta": {"hexsha": "7ef2eedcb322dcfd6ce0888377f4ac60517c3a03", "size": 3056, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Spectre.libGaussianMixtureModelling/GaussianMixtureModel.h", "max_stars_repo_name": "spectre-team/native-algorithms", "max_stars_repo_head_hexsha": "e5e4a65b52d44bc6c0efe68743eae83a08871664", "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/Spectre.libGaussianMixtureModelling/GaussianMixtureModel.h", "max_issues_repo_name": "spectre-team/native-algorithms", "max_issues_repo_head_hexsha": "e5e4a65b52d44bc6c0efe68743eae83a08871664", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2017-12-31T16:44:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-03T21:18:46.000Z", "max_forks_repo_path": "src/Spectre.libGaussianMixtureModelling/GaussianMixtureModel.h", "max_forks_repo_name": "spectre-team/native-algorithms", "max_forks_repo_head_hexsha": "e5e4a65b52d44bc6c0efe68743eae83a08871664", "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": 30.56, "max_line_length": 89, "alphanum_fraction": 0.6636125654, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5984829531992535}} {"text": "#include \n#include \n#include \n#include \n#include \n\ndouble f(double x, void *p) {\n (void) (p); /* avoid unused parameter warning */\n return pow(0.5, pow(x, 2) + 2 * x);\n}\n\nint main(void) {\n int i, j, n = 10000;\n gsl_function F;\n F.function = f;\n F.params = 0;\n gsl_cheb_series *cs = gsl_cheb_alloc(40);\n FILE *file;\n double *x = malloc(2 * n * sizeof(double));\n double *w = malloc(2 * n * sizeof(double));\n double *y = malloc(2 * n * sizeof(double));\n for (i = -n, j = 0; i < n; i++, j++) {\n double xf = i / (double) n;\n x[j] = xf;\n w[j] = 1;\n y[j] = GSL_FN_EVAL (&F, xf);\n }\n double c0, c1, cov00, cov01, cov11, chisq;\n gsl_fit_wlinear(x, 1, w, 1, y, 1, n,\n &c0, &c1, &cov00, &cov01, &cov11,\n &chisq);\n gsl_cheb_init(cs, &F, -1.0, 1.0);\n file = fopen(\"dalsze.dat\", \"w\");\n for (i = -n; i < n; i++) {\n double xf = i / (double) n;\n double yf, yf_err;\n gsl_fit_linear_est(xf,\n c0, c1,\n cov00, cov01, cov11,\n &yf, &yf_err);\n double r10 = gsl_cheb_eval_n(cs, 10, xf);\n double r40 = gsl_cheb_eval(cs, xf);\n fprintf(file, \"%g %g %g %g %g\\n\",\n xf, GSL_FN_EVAL (&F, xf), yf, r10, r40);\n }\n free(x);\n free(y);\n free(w);\n gsl_cheb_free(cs);\n fclose(file);\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "0f1af8ec2fbf222a60707e54d32d050d75da14c5", "size": 1515, "ext": "c", "lang": "C", "max_stars_repo_path": "lab3/dalsze.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": "lab3/dalsze.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": "lab3/dalsze.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": 28.5849056604, "max_line_length": 56, "alphanum_fraction": 0.4864686469, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5984829372805606}} {"text": "/* integration/qk.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \"err.c\"\n\nvoid\ngsl_integration_qk (const int n, \n const double xgk[], const double wg[], const double wgk[],\n double fv1[], double fv2[],\n const gsl_function * f, double a, double b,\n double *result, double *abserr,\n double *resabs, double *resasc)\n{\n\n const double center = 0.5 * (a + b);\n const double half_length = 0.5 * (b - a);\n const double abs_half_length = fabs (half_length);\n const double f_center = GSL_FN_EVAL (f, center);\n\n double result_gauss = 0;\n double result_kronrod = f_center * wgk[n - 1];\n\n double result_abs = fabs (result_kronrod);\n double result_asc = 0;\n double mean = 0, err = 0;\n\n int j;\n\n if (n % 2 == 0)\n {\n result_gauss = f_center * wg[n / 2 - 1];\n }\n\n for (j = 0; j < (n - 1) / 2; j++)\n {\n const int jtw = j * 2 + 1;\t/* j=1,2,3 jtw=2,4,6 */\n const double abscissa = half_length * xgk[jtw];\n const double fval1 = GSL_FN_EVAL (f, center - abscissa);\n const double fval2 = GSL_FN_EVAL (f, center + abscissa);\n const double fsum = fval1 + fval2;\n fv1[jtw] = fval1;\n fv2[jtw] = fval2;\n result_gauss += wg[j] * fsum;\n result_kronrod += wgk[jtw] * fsum;\n result_abs += wgk[jtw] * (fabs (fval1) + fabs (fval2));\n }\n\n for (j = 0; j < n / 2; j++)\n {\n int jtwm1 = j * 2;\n const double abscissa = half_length * xgk[jtwm1];\n const double fval1 = GSL_FN_EVAL (f, center - abscissa);\n const double fval2 = GSL_FN_EVAL (f, center + abscissa);\n fv1[jtwm1] = fval1;\n fv2[jtwm1] = fval2;\n result_kronrod += wgk[jtwm1] * (fval1 + fval2);\n result_abs += wgk[jtwm1] * (fabs (fval1) + fabs (fval2));\n };\n\n mean = result_kronrod * 0.5;\n\n result_asc = wgk[n - 1] * fabs (f_center - mean);\n\n for (j = 0; j < n - 1; j++)\n {\n result_asc += wgk[j] * (fabs (fv1[j] - mean) + fabs (fv2[j] - mean));\n }\n\n /* scale by the width of the integration region */\n\n err = (result_kronrod - result_gauss) * half_length;\n\n result_kronrod *= half_length;\n result_abs *= abs_half_length;\n result_asc *= abs_half_length;\n\n *result = result_kronrod;\n *resabs = result_abs;\n *resasc = result_asc;\n *abserr = rescale_error (err, result_abs, result_asc);\n\n}\n", "meta": {"hexsha": "4b62a17365495ca9a189a3863dd0ad1fefc79d74", "size": 3172, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/integration/qk.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/integration/qk.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/integration/qk.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": 30.7961165049, "max_line_length": 78, "alphanum_fraction": 0.6179066835, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5984780893967488}} {"text": "/* specfunc/gsl_sf_psi.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 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_PSI_H__\n#define __GSL_SF_PSI_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/* Poly-Gamma Functions\n *\n * psi(m,x) := (d/dx)^m psi(0,x) = (d/dx)^{m+1} log(gamma(x))\n */\n\n\n/* Di-Gamma Function psi(n) = psi(0,n)\n *\n * n > 0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_psi_int_e(const int n, gsl_sf_result * result);\ndouble gsl_sf_psi_int(const int n);\n\n\n/* Di-Gamma Function psi(x) = psi(0, x)\n *\n * x != 0.0, -1.0, -2.0, ...\n * exceptions: GSL_EDOM, GSL_ELOSS\n */\nint gsl_sf_psi_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_psi(const double x);\n\n\n/* Di-Gamma Function Re[psi(1 + I y)]\n *\n * exceptions: none\n */\nint gsl_sf_psi_1piy_e(const double y, gsl_sf_result * result);\ndouble gsl_sf_psi_1piy(const double y);\n\n\n/* Di-Gamma Function psi(z) for general complex argument z = x + iy\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_complex_psi_e(\n const double x,\n const double y,\n gsl_sf_result * result_re,\n gsl_sf_result * result_im\n );\n\n\n/* Tri-Gamma Function psi^(1)(n)\n *\n * n > 0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_psi_1_int_e(const int n, gsl_sf_result * result);\ndouble gsl_sf_psi_1_int(const int n);\n\n\n/* Tri-Gamma Function psi^(1)(x)\n *\n * x != 0.0, -1.0, -2.0, ...\n * exceptions: GSL_EDOM, GSL_ELOSS\n */\nint gsl_sf_psi_1_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_psi_1(const double x);\n\n\n/* Poly-Gamma Function psi^(n)(x)\n *\n * n >= 0, x > 0.0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_psi_n_e(const int n, const double x, gsl_sf_result * result);\ndouble gsl_sf_psi_n(const int n, const double x);\n\n\n__END_DECLS\n\n#endif /* __GSL_SF_PSI_H__ */\n", "meta": {"hexsha": "ec61179064badea3ab91c368f6d2d1b8286512e3", "size": 2683, "ext": "h", "lang": "C", "max_stars_repo_path": "315/gsltest/gsl/include/gsl/gsl_sf_psi.h", "max_stars_repo_name": "shi-bash-cmd/qtTest", "max_stars_repo_head_hexsha": "3eb0cf4b8fcfa2c36e133e4df2b2a3e6d2d3e589", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/gsl_sf_psi.h", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/gsl_sf_psi.h", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-02-01T15:12:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T23:53:15.000Z", "avg_line_length": 23.5350877193, "max_line_length": 81, "alphanum_fraction": 0.6913902348, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5980855562862017}} {"text": "/*\nBallistic: a software to benchmark ballistic models.\n\nAUTHORS: Javier Burguete Tolosa.\n\nCopyright 2018, AUTHORS.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\nIN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\nOF SUCH DAMAGE.\n*/\n\n/**\n * \\file runge-kutta.c\n * \\brief Source file to define the Runge-Kutta method data and functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2018.\n */\n#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"config.h\"\n#include \"utils.h\"\n#include \"equation.h\"\n#include \"method.h\"\n#include \"runge-kutta.h\"\n\n#define DEBUG_RUNGE_KUTTA 0 ///< macro to debug the Runge-Kutta functions.\n\n///> 1st array of 1st order Runge-Kutta b coefficients.\nstatic const long double rk_b1_1[1] = { 1.L };\n\n///> matrix of 1st order Runge-Kutta b coefficients.\nstatic const long double *rk_b1[1] = { rk_b1_1 };\n\n///> array of 1st order Runge-Kutta t coefficients.\nstatic const long double rk_t1[1] = { 1.L };\n\n///> array of 1st order Runge-Kutta error coefficients.\nstatic const long double rk_e1[1] = { -1.L };\n\n\n///> 1st array of 1st order Runge-Kutta b coefficients.\nstatic const long double rk_b2_1[1] = { 1.L };\n\n///> 2nd array of 2nd order Runge-Kutta b coefficients.\nstatic const long double rk_b2_2[2] = { 0.5L, 0.5L };\n\n///> matrix of 2nd order Runge-Kutta b coefficients.\nstatic const long double *rk_b2[2] = { rk_b2_1, rk_b2_2 };\n\n///> array of 2nd order Runge-Kutta t coefficients.\nstatic const long double rk_t2[2] = { 1.L, 1.L };\n\n///> array of 2nd order Runge-Kutta error coefficients.\nstatic const long double rk_e2[2] = { 0.5L, -0.5L };\n\n\n///> 1st array of 3rd order Runge-Kutta b coefficients.\nstatic const long double rk_b3_1[1] = { 1.L };\n\n///> 2nd array of 3rd order Runge-Kutta b coefficients.\nstatic const long double rk_b3_2[2] = { 0.25L, 0.25L };\n\n///> 3rd array of 3rd order Runge-Kutta b coefficients.\nstatic const long double rk_b3_3[3] = { 1.L / 6.L, 1.L / 6.L, 2.L / 3.L };\n\n///> matrix of 3rd order Runge-Kutta b coefficients.\nstatic const long double *rk_b3[3] = { rk_b3_1, rk_b3_2, rk_b3_3 };\n\n///> array of 3rd order Runge-Kutta t coefficients.\nstatic const long double rk_t3[3] = { 1.L, 0.5L, 1.L };\n\n///> array of 3rd order Runge-Kutta error coefficients.\nstatic const long double rk_e3[3] = { 1.L / 12.L, 1.L / 12.L, -1.L / 6.L };\n\n\n///> 1st array of 4th order Runge-Kutta b coefficients.\nstatic const long double rk_b4_1[1] = { 0.5L };\n\n///> 2nd array of 4th order Runge-Kutta b coefficients.\nstatic const long double rk_b4_2[2] = { 0.L, 0.5L };\n\n///> 3rd array of 4th order Runge-Kutta b coefficients.\nstatic const long double rk_b4_3[3] = { 0.L, 0.L, 1.L };\n\n///> 4th array of 4th order Runge-Kutta b coefficients.\nstatic const long double rk_b4_4[4] =\n { 1.L / 6.L, 1.L / 3.L, 1.L / 3.L, 1.L / 6.L };\n\n///> matrix of 4th order Runge-Kutta b coefficients.\nstatic const long double *rk_b4[4] = { rk_b4_1, rk_b4_2, rk_b4_3, rk_b4_4 };\n\n///> array of 4th order Runge-Kutta t coefficients.\nstatic const long double rk_t4[4] = { 0.5L, 0.5L, 1.L, 1.L };\n\n\n/**\n * Function to init the coefficients of the 1st order Runge-Kutta method.\n */\nstatic inline void\nrunge_kutta_init_1 (RungeKutta * rk) ///< RungeKutta struct.\n{\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_init_1: start\\n\");\n#endif\n method_init (RUNGE_KUTTA_METHOD (rk), 1, 1);\n rk->b = rk_b1;\n rk->t = rk_t1;\n rk->e = rk_e1;\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_init_1: end\\n\");\n#endif\n}\n\n/**\n * Function to init the coefficients of the 2nd order Runge-Kutta method.\n */\nstatic inline void\nrunge_kutta_init_2 (RungeKutta * rk) ///< RungeKutta struct.\n{\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_init_2: start\\n\");\n#endif\n method_init (RUNGE_KUTTA_METHOD (rk), 2, 2);\n rk->b = rk_b2;\n rk->t = rk_t2;\n rk->e = rk_e2;\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_init_2: end\\n\");\n#endif\n}\n\n/**\n * Function to init the coefficients of the 3rd order Runge-Kutta method.\n */\nstatic inline void\nrunge_kutta_init_3 (RungeKutta * rk) ///< RungeKutta struct.\n{\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_init_3: start\\n\");\n#endif\n method_init (RUNGE_KUTTA_METHOD (rk), 3, 3);\n rk->b = rk_b3;\n rk->t = rk_t3;\n rk->e = rk_e3;\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_init_3: end\\n\");\n#endif\n}\n\n/**\n * Function to init the coefficients of the 4th order Runge-Kutta method.\n */\nstatic inline void\nrunge_kutta_init_4 (RungeKutta * rk) ///< RungeKutta struct.\n{\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_init_4: start\\n\");\n#endif\n method_init (RUNGE_KUTTA_METHOD (rk), 4, 4);\n rk->b = rk_b4;\n rk->t = rk_t4;\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_init_4: end\\n\");\n#endif\n}\n\n/**\n * Function to init the variables used by the Runge-Kutta methods.\n */\nvoid\nrunge_kutta_init_variables (RungeKutta * rk)\n{\n\tMethod *m;\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_init_variables: start\\n\");\n#endif\n\tm = RUNGE_KUTTA_METHOD (rk);\n\tm->nsteps = 1;\n method_init_variables (m);\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_init_variables: end\\n\");\n#endif\n}\n\n/**\n * Function to perform a step of the Runge-Kutta method.\n */\nvoid\nrunge_kutta_step (RungeKutta * rk, ///< RungeKutta struct.\n Equation * eq, ///< Equation struct.\n long double t, ///< current time.\n long double dt) ///< time step size.\n{\n Method *m;\n const long double *b;\n unsigned int i, j, n;\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_step: start\\n\");\n fprintf (stderr, \"runge_kutta_step: t=%Lg dt=%Lg\\n\", t, dt);\n#endif\n m = RUNGE_KUTTA_METHOD (rk);\n memcpy (m->r0[0], r0, 3 * sizeof (long double));\n memcpy (m->r1[0], r1, 3 * sizeof (long double));\n memcpy (m->r2[0], r2, 3 * sizeof (long double));\n#if DEBUG_RUNGE_KUTTA\n for (i = 0; i < 3; ++i)\n fprintf (stderr, \"runge_kutta_step: r0[0][%u]=%Lg\\n\", i, m->r0[0][i]);\n for (i = 0; i < 3; ++i)\n fprintf (stderr, \"runge_kutta_step: r1[0][%u]=%Lg\\n\", i, m->r1[0][i]);\n#endif\n n = m->nsteps;\n for (i = 1; i <= n; ++i)\n {\n b = rk->b[i - 1];\n#if DEBUG_RUNGE_KUTTA\n for (j = 0; j < i; ++j)\n fprintf (stderr, \"runge_kutta_step: b%u-%u=%Lg\\n\", i, j, b[j]);\n#endif\n memcpy (m->r0[i], r0, 3 * sizeof (long double));\n memcpy (m->r1[i], r1, 3 * sizeof (long double));\n for (j = 0; j < i; ++j)\n {\n m->r0[i][0] += dt * b[j] * m->r1[j][0];\n m->r0[i][1] += dt * b[j] * m->r1[j][1];\n m->r0[i][2] += dt * b[j] * m->r1[j][2];\n m->r1[i][0] += dt * b[j] * m->r2[j][0];\n m->r1[i][1] += dt * b[j] * m->r2[j][1];\n m->r1[i][2] += dt * b[j] * m->r2[j][2];\n }\n equation_acceleration (eq, m->r0[i], m->r1[i], m->r2[i],\n t + rk->t[i - 1] * dt);\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_step: t%u=%Lg\\n\", i, rk->t[i - 1]);\n#endif\n }\n --i;\n memcpy (r0, m->r0[i], 3 * sizeof (long double));\n memcpy (r1, m->r1[i], 3 * sizeof (long double));\n memcpy (r2, m->r2[i], 3 * sizeof (long double));\n#if DEBUG_RUNGE_KUTTA\n for (i = 0; i < 3; ++i)\n fprintf (stderr, \"runge_kutta_step: r0[0][%u]=%Lg\\n\", i, r0[i]);\n for (i = 0; i < 3; ++i)\n fprintf (stderr, \"runge_kutta_step: r1[0][%u]=%Lg\\n\", i, r1[i]);\n fprintf (stderr, \"runge_kutta_step: end\\n\");\n#endif\n}\n\n/**\n * Function to estimate the error on a Runge-Kutta step.\n */\nvoid\nrunge_kutta_error (RungeKutta * rk, ///< Runge-Kutta struct.\n long double dt) ///< time step size.\n{\n long double e0[3], e1[3];\n Method *m;\n unsigned int i;\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_error: start\\n\");\n#endif\n m = RUNGE_KUTTA_METHOD (rk);\n e0[0] = e0[1] = e0[2] = e1[0] = e1[1] = e1[2] = 0.L;\n for (i = 0; i < m->nsteps; ++i)\n {\n e0[0] += dt * rk->e[i] * m->r1[i][0];\n e0[1] += dt * rk->e[i] * m->r1[i][1];\n e0[2] += dt * rk->e[i] * m->r1[i][2];\n e1[0] += dt * rk->e[i] * m->r2[i][0];\n e1[1] += dt * rk->e[i] * m->r2[i][1];\n e1[2] += dt * rk->e[i] * m->r2[i][2];\n }\n m->e0 = sqrtl (e0[0] * e0[0] + e0[1] * e0[1] + e0[2] * e0[2]);\n m->e1 = sqrtl (e1[0] * e1[0] + e1[1] * e1[1] + e1[2] * e1[2]);\n m->et0 += m->e0;\n m->et1 += m->e1;\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_error: e0=%Lg et0=%Lg\\n\", m->e0, m->et0);\n fprintf (stderr, \"runge_kutta_error: e1=%Lg et1=%Lg\\n\", m->e1, m->et1);\n fprintf (stderr, \"runge_kutta_error: end\\n\");\n#endif\n}\n\n/**\n * Function to run the Runge-Kutta method bucle.\n *\n * \\return final time. \n */\nlong double\nrunge_kutta_run (RungeKutta * rk, ///< RungeKutta struct.\n Equation * eq) ///< Equation struct.\n{\n Method *m;\n long double t, to, dt, dto, et0o, et1o;\n\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_run: start\\n\");\n#endif\n\n // variables backup \n m = RUNGE_KUTTA_METHOD (rk);\n memcpy (ro0, r0, 3 * sizeof (long double));\n memcpy (ro1, r1, 3 * sizeof (long double));\n memcpy (ro2, r2, 3 * sizeof (long double));\n\n // temporal bucle\n for (t = 0.L; 1;)\n {\n\n // time step size\n if (t > 0.L && m->error_dt)\n {\n dto = dt;\n dt = method_dt (m, dt);\n\n // revert the step if big error\n if (dt < m->beta * dto)\n {\n t = to;\n m->et0 = et0o;\n m->et1 = et1o;\n memcpy (r0, ro0, 3 * sizeof (long double));\n memcpy (r1, ro1, 3 * sizeof (long double));\n memcpy (r2, ro2, 3 * sizeof (long double));\n }\n }\n else\n dt = equation_step_size (eq);\n\n // checking trajectory end\n to = t;\n if (equation_land (eq, to, &t, &dt))\n break;\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_run: t=%Lg dt=%Lg\\n\", t, dt);\n#endif\n\n // backup of variables\n memcpy (ro0, r0, 3 * sizeof (long double));\n memcpy (ro1, r1, 3 * sizeof (long double));\n memcpy (ro2, r2, 3 * sizeof (long double));\n\n // Runge-Kutta step\n runge_kutta_step (rk, eq, to, dt);\n\n // error estimate\n if (m->error_dt)\n {\n et0o = m->et0;\n et1o = m->et1;\n runge_kutta_error (rk, dt);\n }\n }\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_run: end\\n\");\n#endif\n return t;\n}\n\n/**\n * Function to free the memory used by a RungeKutta struct.\n */\nvoid\nrunge_kutta_delete (RungeKutta * rk) ///< RungeKutta struct.\n{\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_delete: start\\n\");\n#endif\n method_delete (RUNGE_KUTTA_METHOD (rk));\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_delete: end\\n\");\n#endif\n}\n\n/**\n * Function to read the Runge-Kutta method data on a XML node.\n *\n * \\return 1 on success, 0 on error.\n */\nint\nrunge_kutta_read_xml (RungeKutta * rk, ///< RungeKutta struct.\n xmlNode * node) ///< XML node.\n{\n const char *message[] = {\n \"Bad type\",\n \"Bad method data\",\n \"Unknown Runge-Kutta method\"\n };\n int e, error_code;\n unsigned int type;\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_read_xml: start\\n\");\n#endif\n type = xml_node_get_uint (node, XML_TYPE, &error_code);\n if (error_code)\n {\n e = 0;\n goto fail;\n }\n if (!method_read_xml (RUNGE_KUTTA_METHOD (rk), node))\n {\n e = 1;\n goto fail;\n }\n switch (type)\n {\n case 1:\n runge_kutta_init_1 (rk);\n break;\n case 2:\n runge_kutta_init_2 (rk);\n break;\n case 3:\n runge_kutta_init_3 (rk);\n break;\n case 4:\n runge_kutta_init_4 (rk);\n break;\n default:\n e = 2;\n goto fail;\n }\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_read_xml: success\\n\");\n fprintf (stderr, \"runge_kutta_read_xml: end\\n\");\n#endif\n return 1;\n\nfail:\n error_add (message[e]);\n#if DEBUG_RUNGE_KUTTA\n fprintf (stderr, \"runge_kutta_read_xml: error\\n\");\n fprintf (stderr, \"runge_kutta_read_xml: end\\n\");\n#endif\n return 0;\n}\n", "meta": {"hexsha": "2a0175012904007328a18b002967a7857efdd1a2", "size": 13178, "ext": "c", "lang": "C", "max_stars_repo_path": "1.1.0/runge-kutta.c", "max_stars_repo_name": "jburguete/ballistic", "max_stars_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-02T14:03:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-02T14:03:09.000Z", "max_issues_repo_path": "1.1.0/runge-kutta.c", "max_issues_repo_name": "jburguete/ballistic", "max_issues_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "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": "1.1.0/runge-kutta.c", "max_forks_repo_name": "jburguete/ballistic", "max_forks_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-24T07:19:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-24T07:19:47.000Z", "avg_line_length": 28.5856832972, "max_line_length": 80, "alphanum_fraction": 0.6214144787, "num_tokens": 4493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.5979115016897163}} {"text": "/*\n * PIXON\n * A Pixon-based method for reconstructing velocity-delay map in reverberation mapping.\n * \n * Yan-Rong Li, liyanrong@mail.ihep.ac.cn\n * \n */\n\n/*!\n * \\file mathfun.c\n * \\brief mathematic functions.\n */\n \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"mathfun.h\"\n\n#define EPS (DBL_MIN)\n\n/*!\n * This function calculates matrix multiply C(nxn) = A(nxn) * B(nxn).\n */\nvoid multiply_mat(double * a, double *b, double *c, int n)\n{\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0f\n , a, n, b, n, 0.0f, c, n);\n}\n\n/*!\n * This function calculates matrix multiply C(nxn) = A^T(nxn) * B(nxn).\n */\nvoid multiply_mat_transposeA(double * a, double *b, double *c, int n)\n{\n cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, n, n, 1.0f\n , a, n, b, n, 0.0f, c, n);\n}\n\n/*!\n * This function calculates matrix multiply C(nxn) = A(nxn) * B^T(nxn).\n */\nvoid multiply_mat_transposeB(double * a, double *b, double *c, int n)\n{\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0f\n , a, n, b, n, 0.0f, c, n);\n}\n\n/*!\n * This function calculates matrix multiply Y(n) = A^T(nxn) * X(n).\n */\nvoid multiply_matvec_transposeA(double *a, double *x, int n, double *y)\n{\n cblas_dgemv(CblasRowMajor, CblasTrans, n, n, 1.0f, a, n, x, 1, 0.0f, y, 1);\n}\n\n/*!\n * This function calculates matrix multiply Y(n) = A(nxn) * X(n).\n */\nvoid multiply_matvec(double *a, double *x, int n, double *y)\n{\n cblas_dgemv(CblasRowMajor, CblasNoTrans, n, n, 1.0f, a, n, x, 1, 0.0f, y, 1);\n}\n\n/*!\n * This function calculates Y(m) = A(m, n) * X(n).\n */\nvoid multiply_matvec_MN(double * a, int m, int n, double *x, double *y)\n{\n cblas_dgemv(CblasRowMajor, CblasNoTrans, m, n, 1.0f, a, n, x, 1, 0.0f, y, 1);\n}\n\n/* C(m*n) = A(m*k) * B(k*n) */\nvoid multiply_mat_MN(double * a, double *b, double *c, int m, int n, int k)\n{\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0f\n , a, k, b, n, 0.0f, c, n);\n}\n\n/* C(m*n) = A^T(m*k) * B(k*n) */\nvoid multiply_mat_MN_transposeA(double * a, double *b, double *c, int m, int n, int k)\n{\n cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, m, n, k, 1.0f\n , a, m, b, n, 0.0f, c, n);\n}\n/* C(m*n) = A(m*k) * B^T(k*n) */\nvoid multiply_mat_MN_transposeB(double * a, double *b, double *c, int m, int n, int k)\n{\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, 1.0f\n , a, k, b, k, 0.0f, c, n);\n}\n\n/* A(mxm)^-1 * B(mxn), store the output in B\n * note that A will be changed on exit. */\nint multiply_mat_MN_inverseA(double * a, double *b, int m, int n)\n{\n int * ipiv, info;\n ipiv=malloc(m*sizeof(int));\n\n info=LAPACKE_dgetrf(LAPACK_ROW_MAJOR, m, m, a, m, ipiv);\n if(info!=0)\n {\n printf(\"multiply_mat_MN_inverseA 1.\\n this usually caused by improper nc.\\n increase the low limit of nc\");\n exit(0);\n return info;\n }\n info = LAPACKE_dgetrs(LAPACK_ROW_MAJOR, 'N', m, n, a, m, ipiv, b, n);\n if(info!=0)\n {\n printf(\"multiply_mat_MN_inverseA 2\\n this usually caused by improper nc.\\n increase the low limit of nc\");\n exit(0);\n return info;\n }\n\n free(ipiv);\n return info;\n}\n\n/*!\n * This functions calculate A^-1(nxn).\n * A is a generic matrix.\n */\nvoid inverse_mat(double * a, int n, int *info)\n{\n int * ipiv;\n ipiv=malloc(n*sizeof(int));\n\n// dgetrf_(&n, &n, a, &n, ipiv, info);\n// dgetri_(&n, a, &n, ipiv, work, &lwork, info);\n\n LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, a, n, ipiv);\n LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, a, n, ipiv);\n\n free(ipiv);\n return;\n}\n\n/*!\n * This functions calculate A^-1(nxn).\n * A is a symmetric matrix.\n */\nvoid inverse_symat(double * a, int n, int *info)\n{\n int * ipiv, i, j;\n ipiv=malloc(n*sizeof(int));\n\n LAPACKE_dsytrf(LAPACK_ROW_MAJOR, 'U', n, a, n, ipiv);\n LAPACKE_dsytri(LAPACK_ROW_MAJOR, 'U', n, a, n, ipiv);\n\n /* fill up the lower triangle */\n for(i=0; i0)\n {\n fprintf(stderr, \"The leading minor of order %d is not positive definite, and the factorization could not be completed.\\n\", *info);\n// exit(-1);\n return;\n }\n\n // only the upper triangle is referenced by dpotrf output, \n // so the strictly lower triangle must be set to zero\n for(i=0;i0)\n {\n fprintf(stderr, \"The leading minor of order %d is not positive definite, and the factorization could not be completed.\\n\", *info);\n// exit(-1);\n return;\n }\n\n // only the lower triangle is referenced by dpotrf output, \n // so the strictly upper triangle must be set to zero\n for(i=0;i=0; i--)\n {\n g = phi[i+1] *(g + a1*z[i+1]);\n z[i] = z[i]/D[i] - W[i]*g;\n }\n}\n/*\n * Z = C^-1 x Y\n * \n * Y is an (nxm) matrix. \n * Note that Y is row-major\n */\nvoid multiply_mat_semiseparable_drw(double *Y, double *W, double *D, double *phi, int n, int m, double a1, double *Z)\n{\n int i, j;\n double f, g;\n\n // forward substitution\n for(j=0; j=0; i--)\n {\n g = phi[i+1] *(g + a1*Z[(i+1)*m+j]);\n Z[i*m+j] = Z[i*m+j]/D[i] - W[i]*g;\n }\n }\n}\n\n/*\n * Z = C^-1 x Y^T\n * \n * Y is an (mxn) matrix. \n * Note that Y is row-major\n */\nvoid multiply_mat_transposeB_semiseparable_drw(double *Y, double *W, double *D, double *phi, int n, int m, double a1, double *Z)\n{\n int i, j;\n double f, g;\n\n // forward substitution\n for(j=0; j=0; i--)\n {\n g = phi[i+1] *(g + a1*Z[(i+1)*m+j]);\n Z[i*m+j] = Z[i*m+j]/D[i] - W[i]*g;\n }\n }\n}\n\n/**\n * calculate A^-1.\n * \n * A = LxDxL^T, L = I + tril(UxW^T), D is a diagonal matrix.\n * \n * M = LxD^1/2, A = MxM^T, A^-1 = (M^T)^-1xM^-1.\n */\nvoid inverse_semiseparable(double *t, int n, double a1, double c1, double *sigma, \n double syserr, double *W, double *D, double *phi,\n double *A, double *lndet)\n{\n int i, j;\n\n compute_semiseparable_drw(t, n, a1, c1, sigma, syserr, W, D, phi);\n \n *lndet = 0.0;\n for(i=0; i0; i--)\n {\n u[i] = (1.0 - b[i]*v[i]*u[i+1] * phi[i+1] )/(a[i]*v[i]+b[i-1]*v[i-1]*phi[i]);\n }\n u[0] = (1.0-b[0]*v[0]*u[1] * phi[1] )/(a[0]*v[0]);\n\n /* calculate W, D */\n D[0] = u[0]*v[0];\n W[0] = 1.0/D[0];\n for(i=1; i *(double *)b)\n\t\treturn 1;\n\telse if (*(double *)a < *(double *)b)\n\t\treturn -1;\n\treturn 0;\n}", "meta": {"hexsha": "4c5941e10e9d5849f5c5d41c7bba68056b1dc26e", "size": 16931, "ext": "c", "lang": "C", "max_stars_repo_path": "src/pycali/pycali/mathfun.c", "max_stars_repo_name": "LiyrAstroph/PyCALI", "max_stars_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-14T01:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T09:23:59.000Z", "max_issues_repo_path": "src/pycali/pycali/mathfun.c", "max_issues_repo_name": "LiyrAstroph/pyCALI", "max_issues_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pycali/pycali/mathfun.c", "max_forks_repo_name": "LiyrAstroph/pyCALI", "max_forks_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-05T02:01:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-06T11:26:06.000Z", "avg_line_length": 22.2776315789, "max_line_length": 135, "alphanum_fraction": 0.5244817199, "num_tokens": 6660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5975407038463317}} {"text": "/* specfunc/gsl_sf_coulomb.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author: G. Jungman */\n\n#ifndef __GSL_SF_COULOMB_H__\n#define __GSL_SF_COULOMB_H__\n\n#include \n#include \n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n\n/* Normalized hydrogenic bound states, radial dependence. */\n\n/* R_1 := 2Z sqrt(Z) exp(-Z r)\n */\nint gsl_sf_hydrogenicR_1_e(const double Z, const double r, gsl_sf_result * result);\ndouble gsl_sf_hydrogenicR_1(const double Z, const double r);\n\n/* R_n := norm exp(-Z r/n) (2Z/n)^l Laguerre[n-l-1, 2l+1, 2Z/n r]\n *\n * normalization such that psi(n,l,r) = R_n Y_{lm}\n */\nint gsl_sf_hydrogenicR_e(const int n, const int l, const double Z, const double r, gsl_sf_result * result);\ndouble gsl_sf_hydrogenicR(const int n, const int l, const double Z, const double r);\n\n\n/* Coulomb wave functions F_{lam_F}(eta,x), G_{lam_G}(eta,x)\n * and their derivatives; lam_G := lam_F - k_lam_G\n *\n * lam_F, lam_G > -0.5\n * x > 0.0\n *\n * Conventions of Abramowitz+Stegun.\n *\n * Because there can be a large dynamic range of values,\n * overflows are handled gracefully. If an overflow occurs,\n * GSL_EOVRFLW is signalled and exponent(s) are returned\n * through exp_F, exp_G. These are such that\n *\n * F_L(eta,x) = fc[k_L] * exp(exp_F)\n * G_L(eta,x) = gc[k_L] * exp(exp_G)\n * F_L'(eta,x) = fcp[k_L] * exp(exp_F)\n * G_L'(eta,x) = gcp[k_L] * exp(exp_G)\n */\nint\ngsl_sf_coulomb_wave_FG_e(const double eta, const double x,\n const double lam_F,\n\t\t\t const int k_lam_G,\n gsl_sf_result * F, gsl_sf_result * Fp,\n\t\t\t gsl_sf_result * G, gsl_sf_result * Gp,\n\t\t\t double * exp_F, double * exp_G);\n\n\n/* F_L(eta,x) as array */\nint gsl_sf_coulomb_wave_F_array(\n double lam_min, int kmax,\n double eta, double x,\n double * fc_array,\n double * F_exponent\n );\n\n/* F_L(eta,x), G_L(eta,x) as arrays */\nint gsl_sf_coulomb_wave_FG_array(double lam_min, int kmax,\n double eta, double x,\n double * fc_array, double * gc_array,\n\t\t\t\tdouble * F_exponent,\n\t\t\t\tdouble * G_exponent\n );\n\n/* F_L(eta,x), G_L(eta,x), F'_L(eta,x), G'_L(eta,x) as arrays */\nint gsl_sf_coulomb_wave_FGp_array(double lam_min, int kmax,\n double eta, double x,\n double * fc_array, double * fcp_array,\n\t\t\t\tdouble * gc_array, double * gcp_array,\n\t\t\t\tdouble * F_exponent,\n\t\t\t\tdouble * G_exponent\n );\n\n/* Coulomb wave function divided by the argument,\n * F(eta, x)/x. This is the function which reduces to\n * spherical Bessel functions in the limit eta->0.\n */\nint gsl_sf_coulomb_wave_sphF_array(double lam_min, int kmax,\n double eta, double x,\n\t \t double * fc_array,\n\t\t\t double * F_exponent\n\t \t \t );\n\n\n/* Coulomb wave function normalization constant.\n * [Abramowitz+Stegun 14.1.8, 14.1.9]\n */\nint gsl_sf_coulomb_CL_e(double L, double eta, gsl_sf_result * result);\nint gsl_sf_coulomb_CL_array(double Lmin, int kmax, double eta, double * cl);\n\n\n__END_DECLS\n\n#endif /* __GSL_SF_COULOMB_H__ */\n", "meta": {"hexsha": "65f0ac8da4549e57139b1164a9376022bbcfafd4", "size": 4140, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_coulomb.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_coulomb.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_coulomb.h", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 32.0930232558, "max_line_length": 107, "alphanum_fraction": 0.6473429952, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5968704851338846}} {"text": "#include \n#include \n#include \n#include \"eigenmap.h\"\n#include \n#include \n\nstatic void diag(double *d, const double *w, int n_patch);\nstatic void compute_l(double *w, int n_patch);\n\nstatic void diag_similarity_transform(double *w, int n_patch);\n\n/*\n * laplacian computes the Laplacian matrix based on the weight matrix.\n *\n * w: the weight matrix\n * n_patch: the dimension of dev_w and dev_l\n * Note: the Laplacian matrix is computed in-place and overwrites w.\n */\nvoid laplacian(double *w, int n_patch)\n{\n /* ---- corresponding Matlab code ----\n * D = diag(sum(W));\n * L = eye(n_patch) - D^(-1/2)*W*D^(-1/2);\n */\n\n // W <- D^(-1/2) * W * D^(-1/2)\n diag_similarity_transform(w, n_patch);\n // L <- I - W\n compute_l(w, n_patch);\n}\n\nstatic void diag_similarity_transform(double *w, int n_patch)\n{\n double *d = (double *)calloc(n_patch, sizeof(double));\n int i;\n\n diag(d, w, n_patch);\n\n // row operations\n for (i = 0; i < n_patch; i++)\n cblas_dscal(n_patch, d[i], &w[i], n_patch);\n // column operations\n for (i = 0; i < n_patch; i++)\n cblas_dscal(n_patch, d[i], &w[i * n_patch], 1);\n\n free(d);\n}\n\nstatic void diag(double *d, const double *w, int n_patch)\n{\n int i, j;\n double sum;\n for (j = 0; j < n_patch; j++){\n sum = 0;\n for (i = 0; i < n_patch; i++)\n sum += w[i + j * n_patch];\n d[j] = 1 / sqrt(sum);\n } \n}\n\nstatic void compute_l(double *w, int n_patch)\n{\n int N = n_patch * n_patch;\n int i;\n\n for (i = 0; i < N; i++)\n w[i] = ((i % (n_patch + 1) == 0) ? 1.0 : 0.0) - w[i];\n}\n", "meta": {"hexsha": "dec0d80d097b71a985dbf1e0e8f27de0e7aafdf7", "size": 1646, "ext": "c", "lang": "C", "max_stars_repo_path": "C_serial/laplacian.c", "max_stars_repo_name": "hcho3/eigenmap_gpu", "max_stars_repo_head_hexsha": "add646dbf220da2143f289f058abed172ab8a637", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-06T03:40:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-28T06:20:14.000Z", "max_issues_repo_path": "C_serial/laplacian.c", "max_issues_repo_name": "hcho3/eigenmap_gpu", "max_issues_repo_head_hexsha": "add646dbf220da2143f289f058abed172ab8a637", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T09:43:40.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-23T14:56:32.000Z", "max_forks_repo_path": "C_serial/laplacian.c", "max_forks_repo_name": "hcho3/eigenmap_gpu", "max_forks_repo_head_hexsha": "add646dbf220da2143f289f058abed172ab8a637", "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.5142857143, "max_line_length": 70, "alphanum_fraction": 0.5698663426, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5968622305128474}} {"text": "#include \n#include \n#include \n#include \n#include \"../ulmblas.h\"\n#define M 1024\n#define K 128\n#define N 1024\n\nvoid\nULMBLAS(dgemm)(const enum Trans transA,\n const enum Trans transB,\n const int m,\n const int n,\n const int k,\n const double alpha,\n const double *A,\n const int ldA,\n const double *B,\n const int ldB,\n const double beta,\n double *C,\n const int ldC);\nint main(){\n // init\n double (*a)[K] = (double (*)[K])malloc(sizeof(double)*M*K);\n double (*b)[N] = (double (*)[N])malloc(sizeof(double)*N*K);\n double (*c)[N] = (double (*)[N])malloc(sizeof(double)*M*N);\n struct timeval stop, start;\n for(int i=0;i> make\n * >> ./coupled_oscillators\n * \n * Deux fichiers sont générés en sortie:\n * osc.txt : series temporelles\n * order.txt: paramètre d'ordre\n *\n * Le fichier osc.txt contient est structuré en colonnes::\n * 0 w1 w2 ... wNOSC \n * t1 1 2 3 ... NOSC\n * \n * La premiere ligne est composee des frequences des oscillateurs. Les\n * oscillateurs sont places en ordre croissant de frequence.\n * t est le temps, r le module du paramètre d'ordre, psi l'argument du paramètre\n * d'ordre, 1...NOSC les phases des oscillateur.\n * Les phases des oscillateurs sont dans R (pas dans [0, 2*pi]).\n *\n * Pour visualiser les résultats, on peut utiliser gnuplot ou Matlab\n *\n * GNUPLOT:\n * plot 'osc.txt' u 1:2:(sin($3)) nonuniform matrix with image\n * \n * Pour tracer le paramètre d'ordre\n *\n * pour r:\n * plot 'order.txt' using 1:2 w lines\n *\n * pour psi:\n * plot 'order.txt' using 1:3 w lines\n *\n * Pour Matlab, utiliser le script coupled_oscillators.m\n * \n */\n\n/* ================================================================= */\n/* Libraries */\n/* ================================================================= */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct par {\n uint32_t NOSC;\n double K;\n double *w;\n};\n\nint ode_rhs(double t, const double y[], double f[], void *params);\nint compare(const void *, const void *);\n\nint main ( int argc, char *argv[] )\n{\n uint32_t NOSC=50; /* nbr oscillators */\n double K=.5; /* coupling stength */\n double sigma=0.5; /* std w distribution */\n double *y; /* phase of oscillators */\n struct par mu; /* parameters */\n FILE *file_order,*file_out;\n uint32_t i;\n double t,tfinal;\n double h,hmin;\n double w_mean;\n double r,psi, rx, ry;\n\n\t/* get command line input parameters */\n\tif (argc == 4)\n {\n NOSC = strtoul(argv[1],NULL,10);\t\n \tK = strtod(argv[2],NULL);\n tfinal = strtod(argv[3],NULL);\n }\t\n\telse\n {\n \tfprintf(stderr, \"Error: call to coupled_oscillators must have the following three mandatory arguments: unsigned long NOSC, double K, and double tfinal\\n\");\n \texit(EXIT_FAILURE);\n }\n\n\t/* init random number generator */\n\tconst gsl_rng_type * rngT;\n\tgsl_rng * rand_nbr_gen;\n\tgsl_rng_env_setup();\n\trngT = gsl_rng_default;\n\trand_nbr_gen = gsl_rng_alloc(rngT);\n\n /* gsl ode */\n const gsl_odeiv2_step_type * odeT;\n gsl_odeiv2_step * s;\n gsl_odeiv2_control * c;\n gsl_odeiv2_evolve * e;\n gsl_odeiv2_system sys; \n int status;\n \n mu.NOSC = NOSC;\n mu.K = K;\n mu.w = malloc(NOSC*sizeof(double));\n y = malloc(NOSC*sizeof(double));\n w_mean = 0.0;\n for (i = 0; i < NOSC; i++)\n {\n y[i] = 2*M_PI*gsl_rng_uniform(rand_nbr_gen)-M_PI;\n mu.w[i] = gsl_ran_gaussian(rand_nbr_gen,sigma*sigma);\n w_mean += mu.w[i];\n }\n w_mean /= NOSC;\n \n /* sort the frequencies from slowest to fastest */\n qsort(mu.w, NOSC, sizeof(double), compare);\n\n /* remove the mean to mu.w */\n file_out = fopen(\"osc.txt\",\"w\");\n fprintf(file_out,\"%.5e \",0.0);\n for ( i = 0; i < NOSC; i++)\n {\n mu.w[i] -= w_mean;\n fprintf(file_out,\"%.5e \",mu.w[i]);\n }\n fprintf(file_out,\"\\n\");\n /* DO NOT TOUCH mu.w BELOW */\n\n /* initialise the ode solver */\n /* the solver used is a Runge-Kutta-Fehlberg (4, 5) method */\n odeT = gsl_odeiv2_step_rkf45;\n s = gsl_odeiv2_step_alloc(odeT,NOSC);\n c = gsl_odeiv2_control_y_new(1e-6,0.0);\n e = gsl_odeiv2_evolve_alloc(NOSC);\n \n h = 1e-2;\n hmin = 1e-5;\n t = 0.0;\n\n file_order = fopen(\"order.txt\",\"w\");\n while (t < tfinal )\n {\n\n /* apply one step of the ode solver */\n sys = (gsl_odeiv2_system) {ode_rhs, NULL, NOSC, &mu};\n status = gsl_odeiv2_evolve_apply(e,c,s,&sys,&t,tfinal,&h,y);\n if (status != GSL_SUCCESS)\n break;\n\n rx = 0;\n ry = 0;\n for ( i = 0; i < NOSC; i++)\n {\n rx += cos(y[i]);\n ry += sin(y[i]);\n \n }\n rx /= NOSC;\n ry /= NOSC;\n r = hypot(rx,ry);\n psi = atan2(ry,rx);\n \n if (h < hmin) h = hmin;\n printf(\".\\n\");\n\n fprintf(file_order,\"%.5e %.5e %.5e\\n\",t,r,psi); \n fprintf(file_out,\"%.5e \",t);\n\n for (i = 0; i < NOSC; i++)\n {\n fprintf (file_out,\"%.5e \",y[i]); \n }\n fprintf(file_out,\"\\n\");\n \n\n }\n\n gsl_odeiv2_evolve_free(e);\n gsl_odeiv2_control_free(c);\n gsl_odeiv2_step_free(s);\n\n fclose(file_out);\n fclose(file_order);\n\n free(y);\n free(mu.w);\n\n\treturn 0;\n}\n\n\nint ode_rhs(double t, const double y[], double f[], void *params)\n{\n\n struct par mu = *(struct par*)params;\n uint32_t NOSC = mu.NOSC;\n double K = mu.K;\n double *w = mu.w;\n uint32_t i,j;\n double *c;\n\n /* printf(\"call to ode_rhs, NOSC=%d\\n\",NOSC); */\n c = malloc(NOSC*sizeof(double));\n /* compute coupling */\n for ( i = 0; i < NOSC; i++)\n {\n c[i] = 0.0;\n for ( j = 0; j < NOSC; j++)\n {\n c[i] += sin(y[j]-y[i]);\n }\n\n f[i] = w[i] + K/NOSC*c[i];\n /* printf(\"f[%d]=%f\\n\",i,f[i]); */\n\n }\n\n free(c);\n\n return GSL_SUCCESS;\n\n}\n\nint compare(const void *a, const void *b)\n{\n const double *da = (const double *) a;\n const double *db = (const double *) b;\n\n return (*da > *db) - (*da < *db);\n}\n", "meta": {"hexsha": "67651775e5d6cd050a35d95b3ae53ef8000c5f4b", "size": 5858, "ext": "c", "lang": "C", "max_stars_repo_path": "coupled_oscillators/coupled_oscillators.c", "max_stars_repo_name": "samubernard/popdyn", "max_stars_repo_head_hexsha": "aed21ddb6b45db5d526b6003495972773131e9d2", "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": "coupled_oscillators/coupled_oscillators.c", "max_issues_repo_name": "samubernard/popdyn", "max_issues_repo_head_hexsha": "aed21ddb6b45db5d526b6003495972773131e9d2", "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": "coupled_oscillators/coupled_oscillators.c", "max_forks_repo_name": "samubernard/popdyn", "max_forks_repo_head_hexsha": "aed21ddb6b45db5d526b6003495972773131e9d2", "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.4083333333, "max_line_length": 160, "alphanum_fraction": 0.5515534312, "num_tokens": 1763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5959804509078732}} {"text": "/**\n@file\n@brief Utilities to perform vectorized LU and LDU decomposition with complete\nrow and column pivoting, based on nonvectorized version of LU decomposition\nwith complete row and column pivoting written by Roger Wehage.\n@author Kristopher Wehage\n@date 2016\n@version 1.1\n@remark\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\nOR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\nOUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGE.\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef KSL_WITH_BLAS_\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n#endif\n\n#include \"ksl/array.h\"\n#include \"ksl/linalg.h\"\n\n/*!\n@brief Function for performing modified double precision Gram-Schmidt\northonormalization\n\nThis function implements a compact version of the Gram-Schmidt\nalgorithm to orthonormalize the columns of a matrix which has\nfull column rank. The matrix, whose columns are to be\northonormalized, is passed in as A[m][n] where m and n are the\nrespective row and column dimensions of A[][]. The\northonormalized columns are passed back in A[][].\n\n@param m row dimension\n@param n column dimension\n@param A[m][n] a rectangular matrix to be orthonormalized, the orthonormalized\n matrix is returned in A\n*/\nvoid ksl_linalg_gramSchmidt(double* restrict A, const int m, const int n) {\n for(int k = 0; k < n; k++) {\n#ifdef KSL_WITH_BLAS\n double R = 1.0 / cblas_dnrm2(m, A + k, n);\n cblas_dscal(m, R, A + k, n);\n#else\n double R = 0.0;\n for(int i = 0; i < m; i++) {\n R += A[i * n + k] * A[i * n + k];\n }\n R = 1.0 / sqrt(R);\n for(int i = 0; i < m; i++) {\n A[i * n + k] *= R;\n }\n#endif\n for(int j = k + 1; j < n; j++) {\n R = 0;\n for(int i = 0; i < m; i++) {\n R += A[i * n + k] * A[i * n + j];\n }\n for(int i = 0; i < m; i++) {\n A[i * n + j] -= A[i * n + k] * R;\n }\n }\n }\n}\n\n/*!\n@brief Function for performing single precision modified Gram-Schmidt\northonormalization\n\nThis function implements a compact version of the Gram-Schmidt\nalgorithm to orthonormalize the columns of a matrix which has\nfull column rank. The matrix, whose columns are to be\northonormalized, is passed in as A[m][n] where m and n are the\nrespective row and column dimensions of A[][]. The\northonormalized columns are passed back in A[][].\n\n@param m row dimension\n@param n column dimension\n@param A[m][n] a rectangular matrix to be orthonormalized, the orthonormalized\n matrix is returned in A\n*/\nvoid ksl_linalg_gramSchmidtf(float* restrict A, const int m, const int n) {\n for(int k = 0; k < n; k++) {\n#ifdef KSL_WITH_BLAS\n double R = 1.0 / cblas_snrm2(m, A + k, n);\n cblas_sscal(m, R, A + k, n);\n#else\n double R = 0.0;\n for(int i = 0; i < m; i++) {\n R += A[i * n + k] * A[i * n + k];\n }\n R = 1.0 / sqrt(R);\n for(int i = 0; i < m; i++) {\n A[i * n + k] *= R;\n }\n#endif\n for(int j = k + 1; j < n; j++) {\n R = 0;\n for(int i = 0; i < m; i++) {\n R += A[i * n + k] * A[i * n + j];\n }\n for(int i = 0; i < m; i++) {\n A[i * n + j] -= A[i * n + k] * R;\n }\n }\n }\n}\n\n/*!\n@brief Row Major Order LU Decomposition with complete row and column pivoting\n\nksl_linalg_lu_full_rmo factors a double precision matrix, A[rowDim * colDim],\nstored in Row Major Order using full row and column pivoting. Matrix A need\nnot have full row or column rank. The integer variable 'rank' represents the\nmatrix rank and internally is always one less than the true rank to be\nconsistent with C's indexing from zero. Upon return from the function,\nrank will be set to the correct value.\n\nThe lower triangular (rank+1) by (rank+1) Lr matrix, except its unity\ndiagonal, is stored below the diagonal in A[0:rank][0:rank]. The upper\ntriangular (rank+1) by (rank+1) Ur matrix is stored on and above the\ndiagonal in A[0:rank][0:rank].\n\nFollowing the first major matrix decomposition step, A[0:rank][rank+1:colDim]\nstores the residual matrix UR and A[rank+1:rowDim][0:rank] stores the residual\nmatrix LR.\n\nThe following operations on this matrix are optionally performed after\nksl_linalg_lu_full_rmo() has factored A.\n\nksl_linalg_lu_setBMatrix_rmo() computes and stores B = inverse(Ur)*UR and stores\nit back in A[0:rank][rank+1:colDim].\nksl_linalg_lu_setCMatrix_rmo() computes and stores C = LR*inverse(Lr) and stores\nit back in A[rank+1:rowDim][0:rank].\n\nThe remaining A[rank+1:rowDim][rank+1:colDim] submatrix contains numbers whose\nabsolute values are all smaller than eps times the absolutely largest\nentry in the original matrix. This part of the matrix is not used.\n\n@param rowDim [in] row dimension of matrix A.\n@param colDim [in] column dimension of matrix A.\n@param *A [in/out] matrix to be factored with dimensions\nA[0:rowDim-1][0:colDim-1], LU factors are overwritten in original matrix\n@param eps [in] input tolerance on the order of machine roundoff.\n@param pr [out] output row permutation array with dimensions pr[0:rowDim-1]\n@param pc [out] output column permutation array with dimensions pc[0:colDim-1]\n@return rank of matrix A\n*/\nint ksl_linalg_lu_full_rmo(const int rowDim, const int colDim,\n double* restrict A, const double eps,\n int* restrict pr, int* restrict pc) {\n\n // printf(\"Jacobian matrix in fullFactor_LU\\n\");\n // for(int i = 0; i < rowDim; i++) {\n // for(int j = 0; j < colDim; j++)\n // printf(\"% 2.4f \", A[i * colDim + j]);\n // printf(\"\\n\");\n // }\n\n int rank; /* (rank+1) is the matrix rank */\n int pivotRow; /* row with current pivotal element */\n int pivotCol; /* column with current pivotal element */\n double pivot = 0.0;\n /* current pivotal element, holds the current pivotal element\n value */\n double tol; /* tolerance for checking residual matrix\n infinity norm against */\n double save; /* variable for holding intermediate results*/\n double size = rowDim * colDim; /*overall size of matrix */\n\n /*\n Return failure if a bad row or column dimension was found.\n */\n if((rowDim <= 0) || (colDim <= 0)) {\n return (-1);\n }\n\n /*\n Consistent with C-indexing, rank always has a value of\n one less than the true value. rank+1 is returned.\n */\n rank = -1; /* initialize for indexing */\n\n /*\n Search through the entire A matrix to find the\n absolutely largest element for assigning to pivot.\n Save that row and column number in pivotRow and\n pivotCol. Also intialize the row permutation array pr.\n */\n#ifdef KSL_WITH_BLAS_\n int index = cblas_idamax(size, A, 1);\n#else\n int index = ksl_maxIndex(size, A);\n#endif\n // div_t result = div(index, colDim);\n // pivotRow = result.quot;\n // pivotCol = result.rem;\n pivotRow = index / colDim;\n pivotCol = index - pivotRow * colDim;\n pivot = A[index];\n // printf(\"pivotRow: %d, pivotCol: %d\\n\", pivotRow, pivotCol);\n\n /* Initialize the column permutation array. */\n for(int col = 0; col < colDim; col++) {\n pc[col] = col;\n }\n for(int row = 0; row < rowDim; row++) {\n pr[row] = row;\n }\n\n /* Set tolerance to check all zero-elements against.\n pivot = infinity norm of A.\n */\n tol = fabs(eps * pivot);\n\n /*\n Major loop to permute and factor the matrix.\n Generate factors column by column, so outer loop\n sweeps over columns.\n */\n for(int col = 0; col < colDim; col++) {\n /*\n If the current pivotal element is <= tol, the\n remaining submatrix is zero and factorization\n is complete. The else statement for the following if test\n breaks out of this loop so not to waste time\n going through the remaining columns.\n */\n if(fabs(pivot) > tol) {\n /* Increase rank for the current column. */\n ++rank;\n\n /*\n pivotRow can never be less than rank.\n If pivotRow==rank, then no permutation is needed.\n If pivotRow>rank, then need to swap rows.\n */\n if(pivotRow > rank) {\n /*\n Swap entire rows A[rank][:] and A[pivotRow][:].\n This also swaps rows in the LR matrix to this point.\n\n swap rows:\n N = colDim\n stride = 1\n Start of replaced row is A + colDim * rank & stride is 1\n Start of pivot row is A + colDim * pivotRow & stride is 1\n */\n#ifdef KSL_WITH_BLAS_\n cblas_dswap(colDim, A + colDim * rank, 1, A + colDim * pivotRow, 1);\n#else\n ksl_swapArray(colDim, A + colDim * rank, 1, A + colDim * pivotRow, 1);\n#endif\n /*\n Swap row permutation entries pr[rank] and\n pr[pivotRow] to reflect row swaps in A.\n */\n ksl_swapi(pr + rank, pr + pivotRow);\n }\n\n /* pivotCol can never be less than rank.\n If pivotCol==rank, then no permutation is needed.\n If pivotCol>rank, then need to swap columns. */\n if(pivotCol > rank) {\n // printf(\"rank: %d, pivotCol: %d\\n\", rank, pivotCol);\n // printf(\"colDim %d\\n\", colDim);\n /*\n Swap entire columns A[:][rank] and A[:][pivotCol].\n This also swaps columns in the UR matrix to this point.\n swap columns:\n N = rowDim\n stride = colDim\n Start of replaced column is A + rank & stride is colDim\n Start of pivot column is A + pivotCol & stride is colDim\n */\n#ifdef KSL_WITH_BLAS_\n cblas_dswap(rowDim, A + rank, colDim, A + pivotCol, colDim);\n#else\n ksl_swapArray(rowDim, A + rank, colDim, A + pivotCol, colDim);\n#endif\n /*\n Swap column permutation entries pc[rank] and\n pr[pivotCol] to reflect column swaps.\n */\n ksl_swapi(pc + rank, pc + pivotCol);\n }\n\n /*\n rank cannot be > rowDim-1. If rank < rowDim-1\n there is still some processing left to do. If\n rank == rowDim-1, there is only a 1 on the\n diagonal of this column of Lr. This loop factors\n the matrix and searches for a new pivotal element\n for the next factorization step.\n */\n if(rank < rowDim - 1) {\n\n /*\n Copy the current pivotal element into save so new\n pivotal element can be stored back in pivot.\n */\n save = pivot;\n pivot = 0;\n\n /* Need only process the rows from rank+1 to rowDim. */\n for(int i = rank + 1; i < rowDim; i++) {\n\n /* Evaluate the current entry in the L matrix.*/\n A[i * colDim + rank] /= save;\n\n /*\n rank cannot be >= colDim. If rank < colDim\n there is still some processing left to do. If\n rank == colDim-1, only a pivot remains on the\n diagonal.\n */\n if(rank < colDim) {\n\n /*\n This next loop computes the remaining U matrix,\n searches for the largest pivotal element, and\n remembers the new pivotal element row and colum.\n */\n for(int j = rank + 1; j < colDim; j++) {\n A[i * colDim + j] -= A[i * colDim + rank] * A[rank * colDim + j];\n if(fabs(A[i * colDim + j]) > fabs(pivot)) {\n pivot = A[i * colDim + j];\n pivotRow = i;\n pivotCol = j;\n } /*End if*/\n } /*End for j*/\n } /*End if rank*/\n } /*Endfor i = rank+1*/\n } /*Endif (rank fabs(pivot)) {\n pivot = A[row * colDim + col];\n pivotRow = row;\n pivotCol = col;\n }\n }\n }\n // printf(\"pivotRow: %d, pivotCol: %d\\n\", pivotRow, pivotCol);\n\n /* Set tolerance to check all zero-elements against.\n pivot = infinity norm of A.\n */\n tol = fabs(eps * pivot);\n\n /*\n Major loop to permute and factor the matrix.\n Generate factors column by column, so outer loop\n sweeps over columns.\n */\n for(int col = 0; col < colDim; col++) {\n /*\n If the current pivotal element is <= tol, the\n remaining submatrix is zero and factorization\n is complete. The else statement for the following if test\n breaks out of this loop so not to waste time\n going through the remaining columns.\n */\n if(fabs(pivot) > tol) {\n /* Increase rank for the current column. */\n ++rank;\n\n /*\n pivotRow can never be less than rank.\n If pivotRow==rank, then no permutation is needed.\n If pivotRow>rank, then need to swap rows.\n */\n if(pivotRow > rank) {\n /*\n Need to swap entire row A[rank][:] and A[pivotRow][:].\n This also swaps rows in the Lr matrix to this point.\n swap rows:\n N = colDim\n stride = 1\n Start of replaced row is A + colDim * rank & stride is 1\n Start of pivot row is A + colDim * pivotRow & stride is 1\n */\n#ifdef KSL_WITH_BLAS_\n cblas_dswap(colDim, A + colDim * rank, 1, A + colDim * pivotRow, 1);\n#else\n ksl_swapArray(colDim, A + colDim * rank, 1, A + colDim * pivotRow, 1);\n#endif\n /*\n Swap row permutation entries pr[rank] and\n pr[pivotRow] to reflect row swaps in A.\n */\n ksl_swapi(pr + rank, pr + pivotRow);\n }\n\n /*\n pivotCol can never be less than rank.\n If pivotCol==rank, then no permutation is needed.\n If pivotCol>rank, then need to swap columns.\n */\n if(pivotCol > rank) {\n // printf(\"rank: %d, pivotCol: %d\\n\", rank, pivotCol);\n // printf(\"colDim %d\\n\", colDim);\n /*\n Swap entire columns A[:][rank] and A[:][pivotCol].\n This also swaps columns in the UR matrix to this point.\n swap columns:\n N = rowDim\n stride = colDim\n Start of replaced column is A + rank & stride is colDim\n Start of pivot column is A + pivotCol & stride is colDim\n */\n#ifdef KSL_WITH_BLAS_\n cblas_dswap(rowDim, A + rank, colDim, A + pivotCol, colDim);\n#else\n ksl_swapArray(rowDim, A + rank, colDim, A + pivotCol, colDim);\n#endif\n /*\n Swap column permutation entries pc[rank] and\n pr[pivotCol] to reflect column swaps.\n */\n ksl_swapi(pc + rank, pc + pivotCol);\n }\n\n /*\n rank cannot be > rowDim-1. If rank < rowDim-1\n there is still some processing left to do. If\n rank == rowDim-1, there is only a 1 on the\n diagonal of this column of Lr. This loop factors\n the matrix and searches for a new pivotal element\n for the next factorization step.\n */\n if(rank < rowDim - 1) {\n\n /*\n Copy the current pivotal element into save so new\n pivotal element can be stored back in pivot.\n */\n save = pivot;\n pivot = 0;\n\n /* Need only process the rows from rank+1 to rowDim. */\n for(int i = rank + 1; i < rowDim; i++) {\n\n /* Evaluate the current entry in the L matrix.*/\n A[i * colDim + rank] /= save;\n\n /*\n rank cannot be >= colDim. If rank < colDim\n there is still some processing left to do. If\n rank == colDim-1, only a pivot remains on the\n diagonal.\n */\n if(rank < colDim) {\n\n /*\n This next loop computes the remaining U matrix,\n searches for the largest pivotal element, and\n remembers the new pivotal element row and colum.\n */\n for(int j = rank + 1; j < colDim; j++) {\n A[i * colDim + j] -= A[i * colDim + rank] * A[rank * colDim + j];\n }\n for(int j = rank + 1; j < colDim - 1; j++) {\n if(fabs(A[i * colDim + j]) > fabs(pivot)) {\n pivot = A[i * colDim + j];\n pivotRow = i;\n pivotCol = j;\n } /*End if*/\n } /*End for j*/\n } /*End if rank*/\n } /*Endfor i = rank+1*/\n } /*Endif (rank colDim) {\n // Error message & exit\n }\n\n /*\n Major loop to factor the matrix.\n Generate factors column by column\n */\n for(int row = 0; row < rank; row++) {\n\n /* i iterates over rows of A, up to rank-1 */\n for(int i = row + 1; i < rank; i++) {\n\n /* Evaluate the current entry in the L matrix.*/\n A[i * colDim + row] /= A[row * colDim + row];\n\n /* Compute U matrix */\n for(int j = row + 1; j < colDim; j++) {\n A[i * colDim + j] -= A[i * colDim + row] * A[row * colDim + j];\n }\n }\n }\n}\n\n/*!\n@brief compute Row Major Order B matrix (inverse(Ur) * UR)\n\nThis block overwrites UR with inverse(Ur) * UR\nIf rank == 0 or rank == colDim nothing to process, so exit with message.\nThis loop computes A[0:rank-1][rank:colDim-1] = inverse(Ur)*UR\nwhere UR is stored in A[0:rank-1][rank:colDim-1]\nand Ur is stored in upper part of A[0:rank-1][0:rank-1].\ni is the row number in Ur.\nj is the column number in Ur & row number in UR.\nk is the column number in UR.\n\n@param rowDim [in] row dimension of matrix A.\n@param colDim [in] column dimension of matrix A.\n@param rank [in] rank of matrix A.\n@param *A [in/out] matrix with dimensions A[0:rowDim-1][0:colDim-1]:\n\n*/\ninline void ksl_linalg_lu_setBMatrix_rmo(const int rowDim, const int colDim,\n const int rank, double* restrict A) {\n\n if(rank > 0 && rank < colDim) {\n for(int i = rank - 1; i > -1; i--) { /* rows of B */\n for(int k = rank; k < colDim; k++) { /* columns of B */\n double save = 0;\n for(int j = rank - 1; j > i; j--) { /* columns of Ur */\n save += A[i * colDim + j] * A[j * colDim + k];\n }\n A[i * colDim + k] = (A[i * colDim + k] - save) / A[i * colDim + i];\n }\n }\n } else {\n // Error & do something.\n }\n}\n\n/*!\n@brief compute Row Major Order C matrix\n\nThis block overwrites LR with LR*inverse(Lr)\nIf rank==1, the Lr matrix is a 1 by 1 identity\nmatrix, so there is nothing to do here. This loop\ncomputes A[rank:rowDim-1][0:rank-1]=LR*inverse(Lr)\nwhere LR is stored in A[rank:rowDim-1][0:rank-1]\nand Lr is stored in A[0:rank-1][0:rank-1].\nj is the column number in LR. It ends at 1\nbecause the diagonal entry in row 0 of Lr is 1.\ni is the row number in LR.\nk is the column number in Lr\n\n@param rowDim [in] row dimension of matrix A.\n@param colDim [in] column dimension of matrix A.\n@param rank [in] rank of matrix A.\n@param *A [in/out] matrix with dimensions A[0:rowDim-1][0:colDim-1]:\n\n*/\nvoid ksl_linalg_lu_setCMatrix_rmo(int rowDim, int colDim, int rank, double* A) {\n\n if(rank > 1) {\n for(int j = rank - 1; j > 0; j--) {\n for(int i = rowDim - 1; i > rank - 1; i--) {\n for(int k = 0; k < j; k++)\n A[i * colDim + k] -= A[i * colDim + j] * A[j * colDim + k];\n }\n }\n } else {\n // Error & do something.\n }\n}\n\n/*!\n@brief computes the Row Major Order L D L^T decomposition of a symmetric\npositive definite matrix without pivoting\n\nreturns the matrix L D L^T in the original matrix A\n\n@param *A [in/out] matrix with dimensions A[0:n-1][0:n-1]:\n@param n row and column dimension of matrix A.\n\n*/\nint ksl_linalg_ldlt_rmo(double* restrict A, const int n) {\n for(int k = 0; k < n; k++) {\n double pivot_inv = A[k * n + k];\n if(pivot_inv > 0.0) {\n pivot_inv = 1.0 / A[k * n + k];\n } else {\n return k + 1;\n }\n for(int j = k + 1; j < n; j++) {\n A[k * n + j] = A[j * n + k];\n A[j * n + k] *= pivot_inv;\n }\n for(int j = k + 1; j < n; j++) {\n for(int i = k + 1; i < j + 1; i++) {\n A[j * n + i] -= A[j * n + k] * A[k * n + i];\n }\n }\n }\n for(int i = 0; i < n; i++) {\n for(int j = i + 1; j < n; j++) {\n A[i * n + j] = A[j * n + i];\n }\n }\n return 0;\n}\n\n/*!\n@brief perform Row Major Order Cholesky (L * L^T) decomposition of a symmetric\nmatrix without pivoting\n\nreturns the matrix factor L in the lower triangular portion of matrix A\n\n@param *A [in/out] matrix with dimensions A[0:n-1][0:n-1]:\n@param n row and column dimension of matrix A.\n\n*/\nint ksl_linalg_cholesky_rmo(double* restrict A, const int n) {\n for(int k = 0; k < n; k++) {\n if(A[k * n + k] > 0.0) {\n A[k * n + k] = sqrt(A[k * n + k]);\n } else {\n return k + 1;\n }\n double pivot_inv = 1.0 / A[k * n + k];\n for(int j = k + 1; j < n; j++) {\n A[j * n + k] *= pivot_inv;\n }\n for(int j = k + 1; j < n; j++) {\n for(int i = k + 1; i < j + 1; i++) {\n A[j * n + i] -= A[j * n + k] * A[i * n + k];\n }\n }\n }\n for(int i = 0; i < n; i++) {\n for(int j = i + 1; j < n; j++) {\n A[i * n + j] = A[j * n + i];\n }\n }\n return 0;\n}\n\n/*!\n@brief used to solve a system of equations\n\nL * y = b\n\nfor y using forward elimination where L IS Row Major Order unit lower triangular\n\ny = L^-1 * b\n\n@param *L [in] n by n matrix L[0:n-1][0:n-1]:\n@param *b [in] n by 1 column of right-hand side y[0:n-1].\n@param *y [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], b[], y[]:\n\n*/\ninline void ksl_linalg_ldlt_forwardElimination_rmo(const double* restrict L,\n const double* restrict b,\n double* restrict y,\n const int n) {\n for(int i = 0; i < n; i++) {\n y[i] = b[i];\n for(int j = 0; j < i; j++) {\n y[i] -= L[i * n + j] * y[j];\n }\n }\n}\n\n/*!\n@brief used to solve a system of equations\n\nL^T * x = y\n\nusing backward substitution where L IS Row Major Order unit lower triangular\n\nx = L^-T * y\n\n@param *L [in] n by n matrix L[0:n-1][0:n-1]:\n@param *y [in] n by 1 column of right-hand side b[0:n-1].\n@param *x [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], y[], x[]:\n\n*/\ninline void ksl_linalg_ldlt_backwardSubstitution_rmo(const double* restrict L,\n const double* restrict y,\n double* restrict x,\n const int n) {\n x[n - 1] = y[n - 1];\n for(int i = n - 2; i > -1; i--) {\n x[i] = y[i];\n for(int j = i + 1; j < n; j++) {\n x[i] -= L[j * n + i] * x[j];\n }\n }\n}\n\n/*!\n@brief used to solve a system of equations\n\nL * y = b\n\nfor y using forward elimination where L is Row Major Order and IS NOT unit lower\ntriangular\n\ny = L^-1 * b\n\n@param *L [in] n by n matrix L[0:n-1][0:n-1]:\n@param *b [in] n by 1 column of right-hand side y[0:n-1].\n@param *y [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], b[], y[]:\n\n*/\ninline void ksl_linalg_cholesky_forwardElimination_rmo(const double* restrict L,\n const double* restrict b,\n double* restrict y,\n const int n) {\n for(int i = 0; i < n; i++) {\n double t = b[i];\n for(int j = 0; j < i; j++) {\n t -= L[i * n + j] * y[j];\n }\n y[i] = t / L[i * n + i];\n }\n}\n\n/*!\n@brief used to solve a system of equations\n\nL^T * x = y\n\nusing backward substitution where L is Row Major Order and IS NOT unit lower\ntriangular\n\nx = L^-T * y\n\n@param *L [in] n by n matrix L[0:n-1][0:n-1]:\n@param *y [in] n by 1 column of right-hand side y[0:n-1].\n@param *x [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], y[], x[]:\n\n*/\ninline void\nksl_linalg_cholesky_backwardSubstitution_rmo(const double* restrict L,\n const double* restrict y,\n double* restrict x, const int n) {\n x[n - 1] = y[n - 1] / L[(n - 1) * n + (n - 1)];\n for(int i = n - 2; i > -1; i--) {\n double t = y[i];\n for(int j = i + 1; j < n; j++) {\n t -= L[j * n + i] * x[j];\n }\n x[i] = t / L[i * n + i];\n }\n}\n\n/*!\n@brief solve the system of equations A * x = b where A is Row Major Order and\na symmetric positive definite matrix A\n\nksl_linalg_ldlt must be called on A prior to calling this function\n\n@param *A [in] n by n matrix A[0:n-1][0:n-1] containing Choleski-factored\nmatrix:\n@param *b [in] n by 1 column of right-hand side y[0:n-1].\n@param *x [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], b[], y[]:\n\n*/\ninline void ksl_linalg_ldlt_solve_rmo(const double* restrict A,\n const double* restrict b,\n double* restrict x, const int n) {\n double y[n];\n ksl_linalg_ldlt_forwardElimination_rmo(A, b, y, n);\n for(int i = 0; i < n; i++) {\n y[i] /= A[i * n + i];\n }\n ksl_linalg_ldlt_backwardSubstitution_rmo(A, y, x, n);\n}\n\n/*!\n@brief solve the system of equations A * x = b where A is Row Major Order and\na symmetric positive definite matrix A\n\nksl_linalg_cholesky must be called on A prior to calling this function\n\n@param *L [in] n by n matrix L[0:n-1][0:n-1]:\n@param *b [in] n by 1 column of right-hand side y[0:n-1].\n@param *y [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], b[], y[]:\n\n*/\ninline void ksl_linalg_cholesky_solve_rmo(const double* restrict A,\n const double* restrict b,\n double* restrict x, const int n) {\n double y[n];\n ksl_linalg_cholesky_forwardElimination_rmo(A, b, y, n);\n ksl_linalg_cholesky_backwardSubstitution_rmo(A, y, x, n);\n}\n\n/*!\n@brief compute inverse of a symmetric positive definite matrix A\nwhere A and A_inverse are in Row Major Order.\n*/\n\ninline int ksl_linalg_symmetricMatrixInverse_rmo(double* restrict A,\n const int n) {\n int status = ksl_linalg_ldlt_rmo(A, n);\n if(status > 0) {\n return status;\n }\n for(int i = 0; i < n - 1; i++) {\n for(int j = i + 1; j < n; j++) {\n A[i * n + j] = 0.0;\n }\n }\n for(int i = 0; i < n; i++) {\n A[i * n + i] = 1.0 / A[i * n + i];\n }\n for(int i = n - 2; i >= 0; i--) { // i = n-1:-1:1\n for(int j = n - 1; j > i; j--) { // j = n:-1:i+1\n for(int k = j; k > i; k--) { // k = j:-1:i+1\n A[i * n + j] -=\n A[k * n + i] * A[k * n + j]; // A(i,j) = A(i,j) - A(k,i)*A(k,j);\n }\n }\n }\n for(int i = n - 2; i >= 0; i--) { // i = n-1:-1:1\n for(int j = 0; j <= i; j++) { // j = 1:1:i\n for(int k = i + 1; k < n; k++) { // k = i+1:1:n\n A[j * n + i] -=\n A[j * n + k] * A[k * n + i]; // A(j,i) = A(j,i) - A(j,k)*A(k,i);\n }\n }\n }\n for(int i = 0; i < n - 1; i++) {\n for(int j = i + 1; j < n; j++) {\n A[j * n + i] = A[i * n + j];\n }\n }\n return 0;\n}\n\n// inline int ksl_linalg_symmetricMatrixInverse_rmo(double* restrict A, const\n// int n) {\n// double A_inverse[n * n];\n// double a[n];\n//\n// int status = ksl_linalg_ldlt_rmo(A, n);\n// if(status > 0) {\n// return status;\n// }\n// for(int i = 0; i < n; i++) {\n// memset(a, 0, n * sizeof(double));\n// a[i] = 1.0;\n// ksl_linalg_ldlt_solve_rmo(A, a, &A_inverse[i * n + 0], n);\n// }\n// memcpy(A, A_inverse, n * n * sizeof(double));\n// return 0;\n// }\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n/*!\n@brief Column Major Order LU Decomposition with complete row and column pivoting\n\nksl_linalg_lu_full_cmo factors a double precision matrix, A[rowDim * colDim],\nstored in Column Major Order using full row and column pivoting. Matrix A need\nnot have full row or column rank. The integer variable 'rank' represents the\nmatrix rank and internally is always one less than the true rank to be\nconsistent with C's indexing from zero. Upon return from the function,\nrank will be set to the correct value.\n\nThe lower triangular (rank+1) by (rank+1) Lr matrix, except its unity\ndiagonal, is stored below the diagonal in A[0:rank][0:rank]. The upper\ntriangular (rank+1) by (rank+1) Ur matrix is stored on and above the\ndiagonal in A[0:rank][0:rank].\n\nFollowing the first major matrix decomposition step, A[0:rank][rank+1:colDim]\nstores the residual matrix UR and A[rank+1:rowDim][0:rank] stores the residual\nmatrix LR.\n\nThe following operations on this matrix are optionally performed after\nksl_linalg_lu_full_cmo() has factored A.\n\nksl_linalg_lu_setBMatrix_cmo() computes and stores B = inverse(Ur)*UR and stores\nit back in A[0:rank][rank+1:colDim].\nksl_linalg_lu_setCMatrix_cmo() computes and stores C = LR*inverse(Lr) and stores\nit back in A[rank+1:rowDim][0:rank].\n\nThe remaining A[rank+1:rowDim][rank+1:colDim] submatrix contains numbers whose\nabsolute values are all smaller than eps times the absolutely largest\nentry in the original matrix. This part of the matrix is not used.\n\n@param rowDim [in] row dimension of matrix A.\n@param colDim [in] column dimension of matrix A.\n@param *A [in/out] matrix to be factored with dimensions\nA[0:rowDim-1][0:colDim-1], LU factors are overwritten in original matrix\n@param eps [in] input tolerance on the order of machine roundoff.\n@param pr [out] output row permutation array with dimensions pr[0:rowDim-1]\n@param pc [out] output column permutation array with dimensions pc[0:colDim-1]\n@return rank of matrix A\n*/\nint ksl_linalg_lu_full_cmo(const int rowDim, const int colDim,\n double* restrict A, const double eps,\n int* restrict pr, int* restrict pc) {\n\n // printf(\"Jacobian matrix in fullFactor_LU\\n\");\n // for(int i = 0; i < rowDim; i++) {\n // for(int j = 0; j < colDim; j++)\n // printf(\"% 2.4f \", A[j * rowDim + i]);\n // printf(\"\\n\");\n // }\n\n int rank; /* (rank+1) is the matrix rank */\n int pivotRow; /* row with current pivotal element */\n int pivotCol; /* column with current pivotal element */\n double pivot = 0.0;\n /* current pivotal element, holds the current pivotal element\n value */\n double tol; /* tolerance for checking residual matrix\n infinity norm against */\n double save; /* variable for holding intermediate results*/\n double size = rowDim * colDim; /*overall size of matrix */\n\n /*\n Return failure if a bad row or column dimension was found.\n */\n if((rowDim <= 0) || (colDim <= 0)) {\n return (-1);\n }\n\n /*\n Consistent with C-indexing, rank always has a value of\n one less than the true value. rank+1 is returned.\n */\n rank = -1; /* initialize for indexing */\n\n /*\n Search through the entire A matrix to find the\n absolutely largest element for assigning to pivot.\n Save that row and column number in pivotRow and\n pivotCol. Also intialize the row permutation array pr.\n */\n#ifdef KSL_WITH_BLAS_\n int index = cblas_idamax(size, A, 1);\n#else\n int index = ksl_maxIndex(size, A);\n#endif\n // div_t result = div(index, colDim);\n // pivotRow = result.quot;\n // pivotCol = result.rem;\n pivotCol = index / rowDim;\n pivotRow = index - pivotCol * rowDim;\n pivot = A[index];\n // printf(\"pivotRow: %d, pivotCol: %d\\n\", pivotRow, pivotCol);\n\n /* Initialize the column permutation array. */\n for(int col = 0; col < colDim; col++) {\n pc[col] = col;\n }\n for(int row = 0; row < rowDim; row++) {\n pr[row] = row;\n }\n\n /* Set tolerance to check all zero-elements against.\n pivot = infinity norm of A.\n */\n tol = fabs(eps * pivot);\n\n /*\n Major loop to permute and factor the matrix.\n Generate factors column by column, so outer loop\n sweeps over columns.\n */\n for(int col = 0; col < colDim; col++) {\n /*\n If the current pivotal element is <= tol, the\n remaining submatrix is zero and factorization\n is complete. The else statement for the following if test\n breaks out of this loop so not to waste time\n going through the remaining columns.\n */\n if(fabs(pivot) > tol) {\n /* Increase rank for the current column. */\n ++rank;\n\n /*\n pivotRow can never be less than rank.\n If pivotRow==rank, then no permutation is needed.\n If pivotRow>rank, then need to swap rows.\n */\n if(pivotRow > rank) {\n /*\n Swap entire rows A[rank][:] and A[pivotRow][:].\n This also swaps rows in the LR matrix to this point.\n\n swap rows:\n N = colDim\n stride = rowDim\n Start of replaced row is A + rank & stride is rowDim\n Start of pivot row is A + pivotRow & stride is rowDim\n */\n#ifdef KSL_WITH_BLAS_\n cblas_dswap(colDim, A + rank, rowDim, A + pivotRow, rowDim);\n#else\n ksl_swapArray(colDim, A + rank, rowDim, A + pivotRow, rowDim);\n#endif\n /*\n Swap row permutation entries pr[rank] and\n pr[pivotRow] to reflect row swaps in A.\n */\n ksl_swapi(pr + rank, pr + pivotRow);\n }\n\n /* pivotCol can never be less than rank.\n If pivotCol==rank, then no permutation is needed.\n If pivotCol>rank, then need to swap columns. */\n if(pivotCol > rank) {\n // printf(\"rank: %d, pivotCol: %d\\n\", rank, pivotCol);\n // printf(\"colDim %d\\n\", colDim);\n /*\n Swap entire columns A[:][rank] and A[:][pivotCol].\n This also swaps columns in the UR matrix to this point.\n swap columns:\n N = rowDim\n stride = 1\n Start of replaced column is A + rowDim * rank & stride is 1\n Start of pivot column is A + rowDim * pivotCol & stride is 1\n */\n#ifdef KSL_WITH_BLAS_\n cblas_dswap(rowDim, A + rowDim * rank, 1, A + rowDim * pivotCol, 1);\n#else\n ksl_swapArray(rowDim, A + rowDim * rank, 1, A + rowDim * pivotCol, 1);\n#endif\n /*\n Swap column permutation entries pc[rank] and\n pr[pivotCol] to reflect column swaps.\n */\n ksl_swapi(pc + rank, pc + pivotCol);\n }\n\n /*\n rank cannot be > rowDim-1. If rank < rowDim-1\n there is still some processing left to do. If\n rank == rowDim-1, there is only a 1 on the\n diagonal of this column of Lr. This loop factors\n the matrix and searches for a new pivotal element\n for the next factorization step.\n */\n if(rank < rowDim - 1) {\n\n /*\n Copy the current pivotal element into save so new\n pivotal element can be stored back in pivot.\n */\n save = pivot;\n pivot = 0;\n\n /* Need only process the rows from rank+1 to rowDim. */\n for(int i = rank + 1; i < rowDim; i++) {\n\n /*\n Evaluate the current entry in the L matrix.\n (rank is always one less than the true rank.)\n The first rank columns of the A matrix are complete.\n Now working in column rank of the A matrix, so the offset\n to the start of the working column is rank * rowDim.\n */\n A[rank * rowDim + i] /= save;\n\n /*\n rank cannot be >= colDim. If rank < colDim\n there is still some processing left to do. If\n rank == colDim-1, only a pivot remains on the\n diagonal.\n */\n if(rank < colDim) {\n\n /*\n This next loop computes the remaining U matrix,\n searches for the largest pivotal element, and\n remembers the new pivotal element row and colum.\n */\n for(int j = rank + 1; j < colDim; j++) {\n A[j * rowDim + i] -= A[rank * rowDim + i] * A[j * rowDim + rank];\n if(fabs(A[j * rowDim + i]) > fabs(pivot)) {\n pivot = A[j * rowDim + i];\n pivotRow = i;\n pivotCol = j;\n } /*End if*/\n } /*End for j*/\n } /*End if rank*/\n } /*Endfor i = rank+1*/\n } /*Endif (rank fabs(pivot)) {\n pivot = A[col * rowDim + row];\n pivotRow = row;\n pivotCol = col;\n }\n }\n }\n // printf(\"pivotRow: %d, pivotCol: %d\\n\", pivotRow, pivotCol);\n\n /* Set tolerance to check all zero-elements against.\n pivot = infinity norm of A.\n */\n tol = fabs(eps * pivot);\n\n /*\n Major loop to permute and factor the matrix.\n Generate factors column by column, so outer loop\n sweeps over columns.\n */\n for(int col = 0; col < colDim; col++) {\n /*\n If the current pivotal element is <= tol, the\n remaining submatrix is zero and factorization\n is complete. The else statement for the following if test\n breaks out of this loop so not to waste time\n going through the remaining columns.\n */\n if(fabs(pivot) > tol) {\n /* Increase rank for the current column. */\n ++rank;\n\n /*\n pivotRow can never be less than rank.\n If pivotRow==rank, then no permutation is needed.\n If pivotRow>rank, then need to swap rows.\n */\n if(pivotRow > rank) {\n /*\n Need to swap entire row A[rank][:] and A[pivotRow][:].\n This also swaps rows in the Lr matrix to this point.\n swap rows:\n N = colDim\n stride = rowDim\n Start of replaced row is A + rank & stride is rowDim\n Start of pivot row is A + pivotRow & stride is rowDim\n */\n#ifdef KSL_WITH_BLAS_\n cblas_dswap(colDim, A + rank, rowDim, A + pivotRow, rowDim);\n#else\n ksl_swapArray(colDim, A + rank, rowDim, A + pivotRow, rowDim);\n#endif\n /*\n Swap row permutation entries pr[rank] and\n pr[pivotRow] to reflect row swaps in A.\n */\n ksl_swapi(pr + rank, pr + pivotRow);\n }\n\n /*\n pivotCol can never be less than rank.\n If pivotCol==rank, then no permutation is needed.\n If pivotCol>rank, then need to swap columns.\n */\n if(pivotCol > rank) {\n // printf(\"rank: %d, pivotCol: %d\\n\", rank, pivotCol);\n // printf(\"colDim %d\\n\", colDim);\n /*\n Swap entire columns A[:][rank] and A[:][pivotCol].\n This also swaps columns in the UR matrix to this point.\n swap columns:\n N = rowDim\n stride = 1\n Start of replaced column is A + rowDim * rank & stride is 1\n Start of pivot column is A + rowDim * pivotCol & stride is 1\n */\n#ifdef KSL_WITH_BLAS_\n cblas_dswap(rowDim, A + rowDim * rank, 1, A + rowDim * pivotCol, 1);\n#else\n ksl_swapArray(rowDim, A + rowDim * rank, 1, A + rowDim * pivotCol, 1);\n#endif\n /*\n Swap column permutation entries pc[rank] and\n pr[pivotCol] to reflect column swaps.\n */\n ksl_swapi(pc + rank, pc + pivotCol);\n }\n\n /*\n rank cannot be > rowDim-1. If rank < rowDim-1\n there is still some processing left to do. If\n rank == rowDim-1, there is only a 1 on the\n diagonal of this column of Lr. This loop factors\n the matrix and searches for a new pivotal element\n for the next factorization step.\n */\n if(rank < rowDim - 1) {\n\n /*\n Copy the current pivotal element into save so new\n pivotal element can be stored back in pivot.\n */\n save = pivot;\n pivot = 0;\n\n /* Need only process the rows from rank+1 to rowDim. */\n for(int i = rank + 1; i < rowDim; i++) {\n\n /* Evaluate the current entry in the L matrix.*/\n A[rank * rowDim + i] /= save;\n\n /*\n rank cannot be >= colDim. If rank < colDim\n there is still some processing left to do. If\n rank == colDim-1, only a pivot remains on the\n diagonal.\n */\n if(rank < colDim) {\n\n /*\n This next loop computes the remaining U matrix,\n searches for the largest pivotal element, and\n remembers the new pivotal element row and colum.\n */\n for(int j = rank + 1; j < colDim; j++) {\n A[j * rowDim + i] -= A[rank * rowDim + i] * A[j * rowDim + rank];\n }\n for(int j = rank + 1; j < colDim - 1; j++) {\n if(fabs(A[j * rowDim + i]) > fabs(pivot)) {\n pivot = A[j * rowDim + i];\n pivotRow = i;\n pivotCol = j;\n } /*End if*/\n } /*End for j*/\n } /*End if rank*/\n } /*Endfor i = rank+1*/\n } /*Endif (rank colDim) {\n // Error message & exit\n }\n\n /*\n Major loop to factor the matrix.\n Generate factors column by column\n */\n for(int row = 0; row < rank; row++) {\n\n /* i iterates over rows of A, up to rank-1 */\n for(int i = row + 1; i < rank; i++) {\n\n /* Evaluate the current entry in the L matrix.*/\n A[row * rank + i] /= A[row * rank + row];\n\n /* Compute U matrix */\n for(int j = row + 1; j < colDim; j++) {\n A[j * rank + i] -= A[row * rank + i] * A[j * rank + row];\n }\n }\n }\n}\n\n/*!\n@brief compute Column Major Order B matrix (inverse(Ur) * UR)\n\n\nThis block overwrites UR with inverse(Ur) * UR\nIf rank == 0 or rank == colDim nothing to process, so exit with message.\nThis loop computes A[0:rank-1][rank:colDim-1] = inverse(Ur)*UR\nwhere UR is stored in A[0:rank-1][rank:colDim-1]\nand Ur is stored in upper part of A[0:rank-1][0:rank-1].\ni is the row number in Ur.\nj is the column number in Ur & row number in UR.\nk is the column number in UR.\n\n@param rowDim [in] row dimension of matrix A.\n@param colDim [in] column dimension of matrix A.\n@param rank [in] rank of matrix A.\n@param *A [in/out] matrix with dimensions A[0:rowDim-1][0:colDim-1]:\n\n*/\ninline void ksl_linalg_lu_setBMatrix_cmo(const int rowDim, const int colDim,\n const int rank, double* restrict A) {\n\n if(rank > 0 && rank < colDim) {\n for(int i = rank - 1; i > -1; i--) { /* rows of B */\n for(int k = rank; k < colDim; k++) { /* columns of B */\n double save = 0;\n for(int j = rank - 1; j > i; j--) { /* columns of Ur */\n save += A[j * rowDim + i] * A[k * rowDim + j];\n }\n A[k * rowDim + i] = (A[k * rowDim + i] - save) / A[i * rowDim + i];\n }\n }\n } else {\n // Error & do something.\n }\n}\n\n/*!\n@brief compute Column Major Order C matrix\n\nThis block overwrites LR with LR*inverse(Lr)\nIf rank==1, the Lr matrix is a 1 by 1 identity\nmatrix, so there is nothing to do here. This loop\ncomputes A[rank:rowDim-1][0:rank-1]=LR*inverse(Lr)\nwhere LR is stored in A[rank:rowDim-1][0:rank-1]\nand Lr is stored in A[0:rank-1][0:rank-1].\nj is the column number in LR. It ends at 1\nbecause the diagonal entry in row 0 of Lr is 1.\ni is the row number in LR.\nk is the column number in Lr\n\n@param rowDim [in] row dimension of matrix A.\n@param colDim [in] column dimension of matrix A.\n@param rank [in] rank of matrix A.\n@param *A [in/out] matrix with dimensions A[0:rowDim-1][0:colDim-1]:\n*/\nvoid ksl_linalg_lu_setCMatrix_cmo(int rowDim, int colDim, int rank, double* A) {\n\n if(rank > 1) {\n for(int j = rank - 1; j > 0; j--) {\n for(int i = rowDim - 1; i > rank - 1; i--) {\n for(int k = 0; k < j; k++)\n A[k * rowDim + i] -= A[j * rowDim + i] * A[k * rowDim + j];\n }\n }\n } else {\n // Error & do something.\n }\n}\n\n/*!\n@brief computes the Column Major Order L D L^T decomposition of a symmetric\nmatrix without pivoting\n\nreturns the matrix L D L^T in the original matrix A\n\n@param *A [in/out] matrix with dimensions A[0:n-1][0:n-1]:\n@param n row and column dimension of matrix A.\n\n*/\nint ksl_linalg_ldlt_cmo(double* restrict A, const int n) {\n for(int k = 0; k < n; k++) {\n double pivot_inv = A[k * n + k];\n if(pivot_inv > 0.0) {\n pivot_inv = 1.0 / A[k * n + k];\n } else {\n return k + 1;\n }\n for(int j = k + 1; j < n; j++) {\n A[j * n + k] = A[k * n + j];\n A[k * n + j] *= pivot_inv;\n }\n for(int j = k + 1; j < n; j++) {\n for(int i = k + 1; i < j + 1; i++) {\n A[i * n + j] -= A[k * n + j] * A[i * n + k];\n }\n }\n }\n for(int i = 0; i < n; i++) {\n for(int j = i + 1; j < n; j++) {\n A[j * n + i] = A[i * n + j];\n }\n }\n return 0;\n}\n\n/*!\n@brief perform Column Major Order Cholesky (L * L^T) decomposition of a\nsymmetric matrix without pivoting\n\nreturns the matrix factor L in the lower triangular portion of matrix A\n\n@param *A [in/out] matrix with dimensions A[0:n-1][0:n-1]:\n@param n row and column dimension of matrix A.\n\n*/\nint ksl_linalg_cholesky_cmo(double* restrict A, const int n) {\n for(int k = 0; k < n; k++) {\n if(A[k * n + k] > 0.0) {\n A[k * n + k] = sqrt(A[k * n + k]);\n } else {\n return k + 1;\n }\n double pivot_inv = 1.0 / A[k * n + k];\n for(int j = k + 1; j < n; j++) {\n A[k * n + j] *= pivot_inv;\n }\n for(int j = k + 1; j < n; j++) {\n for(int i = k + 1; i < j + 1; i++) {\n A[i * n + j] -= A[k * n + j] * A[k * n + i];\n }\n }\n }\n for(int i = 0; i < n; i++) {\n for(int j = i + 1; j < n; j++) {\n A[j * n + i] = A[i * n + j];\n }\n }\n return 0;\n}\n\n/*!\n@brief used to solve a system of equations\n\nL * y = b\n\nfor y using forward elimination where L IS Column Major Order unit lower\ntriangular\n\ny = L^-1 * b\n\n@param *L [in] n by n matrix L[0:n-1][0:n-1]:\n@param *b [in] n by 1 column of right-hand side y[0:n-1].\n@param *y [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], b[], y[]:\n\n*/\ninline void ksl_linalg_ldlt_forwardElimination_cmo(const double* restrict L,\n const double* restrict b,\n double* restrict y,\n const int n) {\n for(int i = 0; i < n; i++) {\n y[i] = b[i];\n }\n for(int i = 0; i < n; i++) {\n for(int j = i + 1; j < n; j++) {\n y[j] -= L[i * n + j] * y[i];\n }\n }\n}\n\n/*!\n@brief used to solve a system of equations\n\nL^T * x = y\n\nusing backward substitution where L IS Column Major Order unit lower triangular\n\nx = L^-T * y\n\n@param *L [in] n by n matrix L[0:n-1][0:n-1]:\n@param *y [in] n by 1 column of right-hand side y[0:n-1].\n@param *x [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], y[], x[]:\n\n*/\ninline void ksl_linalg_ldlt_backwardSubstitution_cmo(const double* restrict L,\n const double* restrict y,\n double* restrict x,\n const int n) {\n for(int i = n - 1; i > -1; i--) {\n x[i] = y[i];\n }\n for(int i = n - 2; i > -1; i--) {\n for(int j = n - 1; j > i; j--) {\n x[i] -= L[i * n + j] * x[j];\n }\n }\n}\n\n/*!\n@brief used to solve a system of equations\n\nL * y = b\n\nfor y using forward elimination where L is Column Major Order and IS NOT unit\nlower triangular\n\ny = L^-1 * b\n\n@param *L [in] n by n matrix L[0:n-1][0:n-1]:\n@param *b [in] n by 1 column of right-hand side y[0:n-1].\n@param *y [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], b[], y[]:\n\n*/\ninline void ksl_linalg_cholesky_forwardElimination_cmo(const double* restrict L,\n const double* restrict b,\n double* restrict y,\n const int n) {\n for(int i = 0; i < n; i++) {\n y[i] = b[i];\n }\n for(int i = 0; i < n; i++) {\n y[i] /= L[i * n + i];\n for(int j = i + 1; j < n; j++) {\n y[j] -= L[j * n + i] * y[i];\n }\n }\n}\n\n/*!\n@brief used to solve a system of equations\n\nL^T * x = y\n\nusing backward substitution where L is Column Major Order and IS NOT unit lower\ntriangular\n\nx = L^-T * y\n\n@param *L [in] n by n matrix L[0:n-1][0:n-1]:\n@param *y [in] n by 1 column of right-hand side y[0:n-1].\n@param *x [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], y[], x[]:\n\n*/\ninline void\nksl_linalg_cholesky_backwardSubstitution_cmo(const double* restrict L,\n const double* restrict y,\n double* restrict x, const int n) {\n for(int i = 0; i < n; i++) {\n x[i] = y[i];\n }\n x[n - 1] /= L[(n - 1) * n + (n - 1)];\n for(int i = n - 2; i > -1; i--) {\n for(int j = i + 1; j < n; j++) {\n x[i] -= L[i * n + j] * x[j];\n }\n x[i] /= L[i * n + i];\n }\n}\n\n/*!\n@brief solve the system of equations A * x = b where A is Column Major Order and\na symmetric positive definite matrix A\n\nksl_linalg_ldlt_cmo must be called on A prior to calling this function\n\n@param *A [in] n by n matrix A[0:n-1][0:n-1] containing Choleski-factored\nmatrix:\n@param *b [in] n by 1 column of right-hand side y[0:n-1].\n@param *x [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], b[], y[]:\n\n*/\ninline void ksl_linalg_ldlt_solve_cmo(const double* restrict A,\n double* const restrict b,\n double* restrict x, const int n) {\n double y[n];\n ksl_linalg_ldlt_forwardElimination_cmo(A, b, y, n);\n for(int i = 0; i < n; i++) {\n y[i] /= A[i * n + i];\n }\n ksl_linalg_ldlt_backwardSubstitution_cmo(A, y, x, n);\n}\n\n/*!\n@brief solve the system of equations A * x = b where A is Column Major Order and\na symmetric positive definite matrix A\n\n@param *A [in] n by n matrix A[0:n-1][0:n-1] containing Choleski-factored\nmatrix:\n@param *b [in] n by 1 column of right-hand side y[0:n-1].\n@param *x [out] n by 1 column of unknowns.\n@param n [in] dimension of L[][], b[], y[]:\n\nksl_linalg_cholesky must be called on A prior to calling this function\n*/\ninline void ksl_linalg_cholesky_solve_cmo(const double* restrict A,\n const double* restrict b,\n double* restrict x, const int n) {\n double y[n];\n ksl_linalg_cholesky_forwardElimination_cmo(A, b, y, n);\n ksl_linalg_cholesky_backwardSubstitution_cmo(A, y, x, n);\n}\n\n/*!\n@brief compute inverse of a symmetric positive definite matrix A\nwhere A and A_inverse are in Column Major Order.\n*/\n\ninline int ksl_linalg_symmetricMatrixInverse_cmo(double* restrict A,\n const int n) {\n int status = ksl_linalg_ldlt_cmo(A, n);\n if(status > 0) {\n return status;\n }\n for(int i = 0; i < n - 1; i++) {\n for(int j = i + 1; j < n; j++) {\n A[j * n + i] = 0.0;\n }\n }\n for(int i = 0; i < n; i++) {\n A[i * n + i] = 1.0 / A[i * n + i];\n }\n for(int i = n - 2; i >= 0; i--) { // i = n-1:-1:1\n for(int j = n - 1; j > i; j--) { // j = n:-1:i+1\n for(int k = j; k > i; k--) { // k = j:-1:i+1\n A[j * n + i] -=\n A[i * n + k] * A[j * n + k]; // A(j,i) = A(j,i) - A(i,k)*A(j,k);\n }\n }\n }\n for(int i = n - 2; i >= 0; i--) { // i = n-1:-1:1\n for(int j = 0; j <= i; j++) { // j = 1:1:i\n for(int k = i + 1; k < n; k++) { // k = i+1:1:n\n A[i * n + j] -=\n A[k * n + j] * A[i * n + k]; // A(i,j) = A(i,j) - A(k,j)*A(k,i);\n }\n }\n }\n for(int i = 0; i < n - 1; i++) {\n for(int j = i + 1; j < n; j++) {\n A[i * n + j] = A[j * n + i];\n }\n }\n return 0;\n}\n\n// inline int ksl_linalg_symmetricMatrixInverse_cmo(double* restrict A, const\n// int n) {\n// double A_inverse[n * n];\n// double a[n];\n//\n// int status = ksl_linalg_ldlt_cmo(A, n);\n// if(status > 0) {\n// return status;\n// }\n// for(int i = 0; i < n; i++) {\n// memset(a, 0, n * sizeof(double));\n// a[i] = 1.0;\n// ksl_linalg_ldlt_solve_cmo(A, a, &A_inverse[i * n + 0], n);\n// }\n// memcpy(A, A_inverse, n * n * sizeof(double));\n// return 0;\n// }\n", "meta": {"hexsha": "64185021cd9d9b8b4e5347764b016140682d5768", "size": 64483, "ext": "c", "lang": "C", "max_stars_repo_path": "src/linalg.c", "max_stars_repo_name": "ideaplexus/ksl", "max_stars_repo_head_hexsha": "574b0121bcfca8e252a8bc8b55b25ee9775b1285", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-22T05:52:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-22T05:52:08.000Z", "max_issues_repo_path": "src/linalg.c", "max_issues_repo_name": "ideaplexus/ksl", "max_issues_repo_head_hexsha": "574b0121bcfca8e252a8bc8b55b25ee9775b1285", "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/linalg.c", "max_forks_repo_name": "ideaplexus/ksl", "max_forks_repo_head_hexsha": "574b0121bcfca8e252a8bc8b55b25ee9775b1285", "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": 32.5507319536, "max_line_length": 80, "alphanum_fraction": 0.5810988943, "num_tokens": 18395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.595670801582339}} {"text": "//\n// SPDX-License-Identifier: MIT\n// Copyright (C) 2020 - 2021 by the ryujin authors\n//\n\n#pragma once\n\n#ifdef DEAL_II_WITH_GSL\n#include \n\nnamespace ryujin\n{\n /**\n * A cubic spline class implemented as a thin wrapper around the GSL\n * spline library functions.\n *\n * Usage:\n * @code\n * std::vector xs{0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n * std::vector ys{1.0, 0.2, 5.0, 2.0, 1.0, 10.0};\n * CubicSpline spline(xs, ys);\n *\n * spline.eval(0.5);\n * @endcode\n *\n * @ingroup Mesh\n */\n class CubicSpline\n {\n public:\n /**\n * Constructor.\n *\n * @pre The supplied vectors @p x and @p y must have the same size and\n * must contain at least two elements. The vector @p x must be sorted\n */\n CubicSpline(const std::vector &x,\n const std::vector &y) noexcept\n : x_(x)\n , y_(y)\n {\n AssertNothrow(x_.size() == y_.size(), dealii::ExcInternalError());\n AssertNothrow(x_.size() >= 2, dealii::ExcInternalError());\n AssertNothrow(std::is_sorted(x_.begin(), x_.end()),\n dealii::ExcInternalError());\n\n spline = gsl_spline_alloc(gsl_interp_cspline, x_.size());\n gsl_spline_init(spline, x_.data(), y_.data(), x_.size());\n\n accel = gsl_interp_accel_alloc();\n }\n\n /**\n * Copy constructor.\n */\n CubicSpline(const CubicSpline ©)\n : CubicSpline(copy.x_, copy.y_)\n {\n }\n\n /**\n * The copy assignment operator is deleted.\n */\n CubicSpline &operator=(const CubicSpline &) = delete;\n\n /**\n * Destructor.\n */\n ~CubicSpline()\n {\n gsl_interp_accel_free(accel);\n gsl_spline_free(spline);\n }\n\n /**\n * Evaluate the cubic spline at a given point @p x.\n *\n * @pre The point @p x must lie within the interval described by the\n * largest and smallest support point supplied to the constructor.\n */\n inline double eval(double x) const\n {\n return gsl_spline_eval(spline, x, accel);\n }\n\n private:\n const std::vector x_;\n const std::vector y_;\n gsl_spline *spline;\n mutable gsl_interp_accel *accel;\n };\n} // namespace ryujin\n\n#endif\n", "meta": {"hexsha": "dbe31601d32367fe22dcafb6af20afc923ee2d1a", "size": 2213, "ext": "h", "lang": "C", "max_stars_repo_path": "source/cubic_spline.h", "max_stars_repo_name": "Fanxiaotsing/ryujin", "max_stars_repo_head_hexsha": "8752fff625300d1e7e2ea22bf3e816e2f5725afa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-06-30T20:52:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T00:30:21.000Z", "max_issues_repo_path": "source/cubic_spline.h", "max_issues_repo_name": "Fanxiaotsing/ryujin", "max_issues_repo_head_hexsha": "8752fff625300d1e7e2ea22bf3e816e2f5725afa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-08-28T17:11:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:40:41.000Z", "max_forks_repo_path": "source/cubic_spline.h", "max_forks_repo_name": "Fanxiaotsing/ryujin", "max_forks_repo_head_hexsha": "8752fff625300d1e7e2ea22bf3e816e2f5725afa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2020-07-11T16:30:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T18:09:54.000Z", "avg_line_length": 23.2947368421, "max_line_length": 74, "alphanum_fraction": 0.5937641211, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5953874452057468}} {"text": "/*\n** conversions: p->z, z->p, t->z\n**\n** G.Lohmann, April 2007\n*/\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\n\n\n/* \n** convert t to p values \n*/\ndouble t2p(double t,double df)\n{\n double a,b,x;\n extern double gsl_sf_beta_inc(double,double,double);\n\n x = df/(df+(t*t));\n if (x < 0 || x > 1) return 1;\n a = 0.5*df;\n b = 0.5;\n\n return 0.5 * gsl_sf_beta_inc(a,b,x);\n}\n\n\n/* \n** convert t to z values \n*/\ndouble t2z(double t,double df)\n{\n double p=0,z=0;\n double a,b,x;\n extern double gsl_sf_beta_inc(double,double,double);\n\n\n /* t to p */\n x = df/(df+(t*t));\n if (x <= 0 || x > 1) return 0;\n\n a = 0.5*df;\n b = 0.5;\n p = 0.5 * gsl_sf_beta_inc(a,b,x);\n\n\n /* p to z */\n z = gsl_cdf_ugaussian_Qinv(p);\n return z;\n}\n\n\n/* \n** approximation: convert t to p values \n*/\nfloat\nt2z_approx(float t,float df)\n{\n float z=0,u;\n\n u = df*log(1.0+t*t/df)*(1.0-0.5/df);\n if (u <= 0) return 0;\n z = sqrt(u);\n return z;\n}\n\n\n/* \n** convert p to t values \n*/\ndouble \np2t(double px,double df)\n{\n double p,t0,t1,t,step=0.00001;\n\n t = 0;\n t0 = 0;\n t1 = 20;\n while (ABS(t0-t1) > step) {\n t = (t0 + t1)*0.5;\n p = t2p(t,df);\n if (p < px) t1 = t;\n else t0 = t;\n }\n p = t2p(t,df);\n\n return t;\n}\n\n\n/* \n** convert z to p values \n*/\ndouble z2p(double z)\n{\n if (z < 0) \n return gsl_cdf_ugaussian_Q(-z);\n else \n return gsl_cdf_ugaussian_Q(z);\n}\n\n\n/* \n** convert p to z values \n*/\ndouble p2z(double p)\n{\n return gsl_cdf_ugaussian_Qinv(p);\n}\n\n\n", "meta": {"hexsha": "28bd7a1062073adfbbb5604cd49e6b11f5c1b7f0", "size": 1637, "ext": "c", "lang": "C", "max_stars_repo_path": "src/lib_via/StatsConversions.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/lib_via/StatsConversions.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/lib_via/StatsConversions.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": 13.5289256198, "max_line_length": 54, "alphanum_fraction": 0.5601710446, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.5951741479676536}} {"text": "/* histogram/stat2d.c\n * Copyright (C) 2002 Achim Gaedke\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this library; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/***************************************************************\n *\n * File histogram/stat2d.c:\n * Routine to return statistical values of the content of a 2D hisogram. \n *\n * Contains the routines:\n * gsl_histogram2d_sum sum up all bin values\n * gsl_histogram2d_xmean determine mean of x values\n * gsl_histogram2d_ymean determine mean of y values\n *\n * Author: Achim Gaedke Achim.Gaedke@zpr.uni-koeln.de\n * Jan. 2002\n *\n ***************************************************************/\n\n#include \n#include \n#include \n#include \n\n/*\n sum up all bins of histogram2d\n */\n\ndouble\ngsl_histogram2d_sum (const gsl_histogram2d * h)\n{\n const size_t n = h->nx * h->ny;\n double sum = 0;\n size_t i = 0;\n\n while (i < n)\n sum += h->bin[i++];\n\n return sum;\n}\n\ndouble\ngsl_histogram2d_xmean (const gsl_histogram2d * h)\n{\n const size_t nx = h->nx;\n const size_t ny = h->ny;\n size_t i;\n size_t j;\n\n /* Compute the bin-weighted arithmetic mean M of a histogram using the\n recurrence relation\n\n M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n))) \n W(n) = W(n-1) + w(n)\n\n */\n\n long double wmean = 0;\n long double W = 0;\n\n for (i = 0; i < nx; i++)\n {\n double xi = (h->xrange[i + 1] + h->xrange[i]) / 2.0;\n double wi = 0;\n\n for (j = 0; j < ny; j++)\n {\n double wij = h->bin[i * ny + j];\n if (wij > 0)\n wi += wij;\n }\n if (wi > 0)\n {\n W += wi;\n wmean += (xi - wmean) * (wi / W);\n }\n }\n\n return wmean;\n}\n\ndouble\ngsl_histogram2d_ymean (const gsl_histogram2d * h)\n{\n const size_t nx = h->nx;\n const size_t ny = h->ny;\n size_t i;\n size_t j;\n\n /* Compute the bin-weighted arithmetic mean M of a histogram using the\n recurrence relation\n\n M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n))) \n W(n) = W(n-1) + w(n)\n\n */\n\n long double wmean = 0;\n long double W = 0;\n\n for (j = 0; j < ny; j++)\n {\n double yj = (h->yrange[j + 1] + h->yrange[j]) / 2.0;\n double wj = 0;\n\n for (i = 0; i < nx; i++)\n {\n double wij = h->bin[i * ny + j];\n if (wij > 0)\n wj += wij;\n }\n\n if (wj > 0)\n {\n W += wj;\n wmean += (yj - wmean) * (wj / W);\n }\n }\n\n return wmean;\n}\n\ndouble\ngsl_histogram2d_xsigma (const gsl_histogram2d * h)\n{\n const double xmean = gsl_histogram2d_xmean (h);\n const size_t nx = h->nx;\n const size_t ny = h->ny;\n size_t i;\n size_t j;\n\n /* Compute the bin-weighted arithmetic mean M of a histogram using the\n recurrence relation\n\n M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n))) \n W(n) = W(n-1) + w(n)\n\n */\n\n long double wvariance = 0;\n long double W = 0;\n\n for (i = 0; i < nx; i++)\n {\n double xi = (h->xrange[i + 1] + h->xrange[i]) / 2 - xmean;\n double wi = 0;\n\n for (j = 0; j < ny; j++)\n {\n double wij = h->bin[i * ny + j];\n if (wij > 0)\n wi += wij;\n }\n\n if (wi > 0)\n {\n W += wi;\n wvariance += ((xi * xi) - wvariance) * (wi / W);\n }\n }\n\n {\n double xsigma = sqrt (wvariance);\n return xsigma;\n }\n}\n\ndouble\ngsl_histogram2d_ysigma (const gsl_histogram2d * h)\n{\n const double ymean = gsl_histogram2d_ymean (h);\n const size_t nx = h->nx;\n const size_t ny = h->ny;\n size_t i;\n size_t j;\n\n /* Compute the bin-weighted arithmetic mean M of a histogram using the\n recurrence relation\n\n M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n))) \n W(n) = W(n-1) + w(n)\n\n */\n\n long double wvariance = 0;\n long double W = 0;\n\n for (j = 0; j < ny; j++)\n {\n double yj = (h->yrange[j + 1] + h->yrange[j]) / 2.0 - ymean;\n double wj = 0;\n\n for (i = 0; i < nx; i++)\n {\n double wij = h->bin[i * ny + j];\n if (wij > 0)\n wj += wij;\n }\n if (wj > 0)\n {\n W += wj;\n wvariance += ((yj * yj) - wvariance) * (wj / W);\n }\n }\n\n {\n double ysigma = sqrt (wvariance);\n return ysigma;\n }\n}\n\ndouble\ngsl_histogram2d_cov (const gsl_histogram2d * h)\n{\n const double xmean = gsl_histogram2d_xmean (h);\n const double ymean = gsl_histogram2d_ymean (h);\n const size_t nx = h->nx;\n const size_t ny = h->ny;\n size_t i;\n size_t j;\n\n /* Compute the bin-weighted arithmetic mean M of a histogram using the\n recurrence relation\n\n M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n))) \n W(n) = W(n-1) + w(n)\n\n */\n\n long double wcovariance = 0;\n long double W = 0;\n\n for (j = 0; j < ny; j++)\n {\n for (i = 0; i < nx; i++)\n {\n double xi = (h->xrange[i + 1] + h->xrange[i]) / 2.0 - xmean;\n double yj = (h->yrange[j + 1] + h->yrange[j]) / 2.0 - ymean;\n double wij = h->bin[i * ny + j];\n\n if (wij > 0)\n {\n W += wij;\n wcovariance += ((xi * yj) - wcovariance) * (wij / W);\n }\n }\n }\n\n return wcovariance;\n\n}\n", "meta": {"hexsha": "5982817838e0d37929b32855be6b10ddb8c4687b", "size": 5818, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/histogram/stat2d.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/stat2d.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/stat2d.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 21.8721804511, "max_line_length": 74, "alphanum_fraction": 0.5190787212, "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5948210757300586}} {"text": "/* =======================================\n * SUSY\n *\n * TODO:\n * - still giving qualitatively wrong answer\n * =======================================\n */\n#include \n#include \n#include \n#define sq(x) pow((x),2.0)\n#define cb(x) pow((x),3.0)\n#define qd(x) pow((x),4.0)\n\n// GSL Random Number Generator (https://www.gnu.org/software/gsl/)\n#include \nconst gsl_rng_type * T; gsl_rng * r;\n\n// GSL Spline (for smoothing)\n#include \n#include \ngsl_interp_accel *spline_accel;\ngsl_spline *spline;\n#define N_spl 5 // Factor of N_bin +1 (end points inclusive)\n\n// Parameters\n#define N_lat 2000 // Lattice size\n#define a 0.1 // Lattice spacing\n#define N_therm 500 // Thermalization\n#define N_meas 1000 // Number of configuration to measure\n#define N_skip 50 // Decorrelation\n#define alpha 0 // Strength of potential (harmonic)\n#define lambda 1 // Strength of potential (anharmonic)\n#define epsilon 0.2 // Size of fluctuation\n\n// SUSY Parameters\n#define epsilon_susy 0.4 // Size of fluctuation\n\n\n#define N_bin 100\n#define dx 0.04 // x_range*2 / bin\n#define x_range 2 // x in [-range, range]\n\n// Globals\ndouble x[N_lat]; // Lattice\nint N_acc,N_tot; // Acceptance rate = acc/tot\ndouble E0; // Ground state energy\ndouble C[N_lat]; // Correlator\ndouble psi[N_bin]; // Wavefunction\ndouble psip[N_bin]; // 1st derivative of wavefunction\ndouble psipp[N_bin]; // 2nd derivative of wavefunction\ndouble H_susy[N_bin]; // SUSY action\n\n\n// Output Files\nFILE *fE0, *fpsi0, *fpsi;\n\n// Prototypes\nvoid setup();\nvoid cleanup();\nvoid update();\nvoid update_susy();\nint xtoi(double x);\ndouble itox(int i);\n\nint main(void){\n setup();\n\n // Thermalize\n for(int n=0;n0){\n H_susy[i] = - (psipp[i]/psi[i]-sq(psip[i]/psi[i]))/sqrt(2); // TODO: This is technically wrong...\n }else{\n H_susy[i]=9999999;\n }\n }\n\n // Plot wavefunction and derivatives\n for(int i=0;i0){\n if(exp(-d)0){\n if(exp(-d)\n#include \n#include \n\nvoid inverse(double* A, lapack_int N)\n{\n lapack_int *IPIV = (lapack_int *) malloc(N * sizeof(lapack_int));\n int INFO;\n\n /*\n DGETRF computes an LU factorization of a general M-by-N matrix A\n using partial pivoting with row interchanges.\n\n The factorization has the form\n A = P * L * U\n where P is a permutation matrix, L is lower triangular with unit\n diagonal elements (lower trapezoidal if m > n), and U is upper\n triangular (upper trapezoidal if m < n).\n\n This is the right-looking Level 3 BLAS version of the algorithm.\n \n lapack_int LAPACKE_dgetrf( int matrix_layout, lapack_int m, lapack_int n,\n double* a, lapack_int lda, lapack_int* ipiv );\n \n INFO is INTEGER\n = 0: successful exit\n < 0: if INFO = -i, the i-th argument had an illegal value\n > 0: if INFO = i, U(i,i) is exactly zero. The factorization\n has been completed, but the factor U is exactly\n singular, and division by zero will occur if it is used\n to solve a system of equations.\n */\n \n INFO = LAPACKE_dgetrf(LAPACK_ROW_MAJOR,N,N,A,N,IPIV);\n printf(\"%d \", INFO);\n\n //DGETRI computes the inverse of a matrix using the LU factorization\n //computed by DGETRF.\n\n //This method inverts U and then computes inv(A) by solving the system\n //inv(A)*L = inv(U) for inv(A).\n //lapack_int LAPACKE_dgetri( int matrix_layout, lapack_int n, double* a,\n // lapack_int lda, const lapack_int* ipiv );\n INFO = LAPACKE_dgetri(LAPACK_ROW_MAJOR,N,A,N,IPIV);\n printf(\"%d \\n\", INFO);\n\n free(IPIV);\n}\n\nint main(){\n\n double A [2*2] = {\n 1,2,\n 3,4\n };\n\n inverse(A, 2);\n\n printf(\"%f %f\\n\", A[0], A[1]);\n printf(\"%f %f\\n\", A[2], A[3]);\n\n return 0;\n}\n", "meta": {"hexsha": "a6b4fe7840a17cf8733700b933a8d3df72f7769b", "size": 1917, "ext": "c", "lang": "C", "max_stars_repo_path": "main.c", "max_stars_repo_name": "agnusfeec/lc", "max_stars_repo_head_hexsha": "84a3b4446b825735618f541a7ce9adcf3753fe22", "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": "main.c", "max_issues_repo_name": "agnusfeec/lc", "max_issues_repo_head_hexsha": "84a3b4446b825735618f541a7ce9adcf3753fe22", "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": "main.c", "max_forks_repo_name": "agnusfeec/lc", "max_forks_repo_head_hexsha": "84a3b4446b825735618f541a7ce9adcf3753fe22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.953125, "max_line_length": 81, "alphanum_fraction": 0.5978090767, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5942877078009505}} {"text": "/*\n * knnring_sequential.c\n *\n * Created on: Nov 21, 2019\n * Author: Lambis\n */\n\n\n#include \n#include \n#include \n#include \n#include \n#include \"knnring.h\"\n\nknnresult kNN(double * X, double * Y, int n, int m, int d, int k) {\n\n\tknnresult knn;\n\n // Allocating memory for the knnresult.\n\tknn.nidx = (int *)malloc(m*k*sizeof(int));\n\tknn.ndist = (double *)malloc(m*k*sizeof(double));\n\n\t// Passing m and k values to knnresult.\n\tknn.m = m;\n\tknn.k = k;\n\n // Allocating memory for the distances array.\n\tdouble *D = (double *)malloc(m*n*sizeof(double));\n\n\t// Calculation of sum(X.^2,2).\n\tdouble *a = (double *)malloc(n*sizeof(double));\n\tfor (int i=0; i Array to be sorted, low --> Starting index, high --> Ending index\nvoid quickSort(double *arr, int low, int high, int *idx) {\n if (low < high) {\n // pi is partitioning index, arr[pi] is now at right place\n int pi = partition(arr, low, high, idx);\n\n // Separately sort elements before partition and after partition\n quickSort(arr, low, pi - 1, idx);\n quickSort(arr, pi + 1, high, idx);\n }\n}\n", "meta": {"hexsha": "19dc26f3d62f733355dc4357da647be1f0684a23", "size": 3925, "ext": "c", "lang": "C", "max_stars_repo_path": "knnring_sequential.c", "max_stars_repo_name": "LambisElef/kNN_MPI", "max_stars_repo_head_hexsha": "6977dca83c165fc41466e2a28bd7d460cbda29de", "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": "knnring_sequential.c", "max_issues_repo_name": "LambisElef/kNN_MPI", "max_issues_repo_head_hexsha": "6977dca83c165fc41466e2a28bd7d460cbda29de", "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": "knnring_sequential.c", "max_forks_repo_name": "LambisElef/kNN_MPI", "max_forks_repo_head_hexsha": "6977dca83c165fc41466e2a28bd7d460cbda29de", "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.2374100719, "max_line_length": 124, "alphanum_fraction": 0.5763057325, "num_tokens": 1262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.594287678499115}} {"text": "/* randist/poisson.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 poisson distribution has the form\n\n p(n) = (mu^n / n!) exp(-mu) \n\n for n = 0, 1, 2, ... . The method used here is the one from Knuth. */\n\nunsigned int\ngsl_ran_poisson (const gsl_rng * r, double mu)\n{\n double emu;\n double prod = 1.0;\n unsigned int k = 0;\n\n while (mu > 10)\n {\n unsigned int m = mu * (7.0 / 8.0);\n\n double X = gsl_ran_gamma_int (r, m);\n\n if (X >= mu)\n {\n return k + gsl_ran_binomial (r, mu / X, m - 1);\n }\n else\n {\n k += m;\n mu -= X; \n }\n }\n\n /* This following method works well when mu is small */\n\n emu = exp (-mu);\n\n do\n {\n prod *= gsl_rng_uniform (r);\n k++;\n }\n while (prod > emu);\n\n return k - 1;\n\n}\n\nvoid\ngsl_ran_poisson_array (const gsl_rng * r, size_t n, unsigned int array[],\n double mu)\n{\n size_t i;\n\n for (i = 0; i < n; i++)\n {\n array[i] = gsl_ran_poisson (r, mu);\n }\n\n return;\n}\n\ndouble\ngsl_ran_poisson_pdf (const unsigned int k, const double mu)\n{\n double p;\n double lf = gsl_sf_lnfact (k); \n\n p = exp (log (mu) * k - lf - mu);\n return p;\n}\n", "meta": {"hexsha": "34501f844d7b43ddfd52bddace0f132c8829233b", "size": 2075, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/poisson.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/poisson.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/poisson.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.0744680851, "max_line_length": 81, "alphanum_fraction": 0.6125301205, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5934692373987598}} {"text": "/* specfunc/gsl_sf_gamma.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#ifndef __GSL_SF_GAMMA_H__\n#define __GSL_SF_GAMMA_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/* Log[Gamma(x)], x not a negative integer\n * Uses real Lanczos method.\n * Returns the real part of Log[Gamma[x]] when x < 0,\n * i.e. Log[|Gamma[x]|].\n *\n * exceptions: GSL_EDOM, GSL_EROUND\n */\nint gsl_sf_lngamma_e(double x, gsl_sf_result * result);\ndouble gsl_sf_lngamma(const double x);\n\n\n/* Log[Gamma(x)], x not a negative integer\n * Uses real Lanczos method. Determines\n * the sign of Gamma[x] as well as Log[|Gamma[x]|] for x < 0.\n * So Gamma[x] = sgn * Exp[result_lg].\n *\n * exceptions: GSL_EDOM, GSL_EROUND\n */\nint gsl_sf_lngamma_sgn_e(double x, gsl_sf_result * result_lg, double *sgn);\n\n\n/* Gamma(x), x not a negative integer\n * Uses real Lanczos method.\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EROUND\n */\nint gsl_sf_gamma_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_gamma(const double x);\n\n\n/* Regulated Gamma Function, x > 0\n * Gamma^*(x) = Gamma(x)/(Sqrt[2Pi] x^(x-1/2) exp(-x))\n * = (1 + 1/(12x) + ...), x->Inf\n * A useful suggestion of Temme.\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_gammastar_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_gammastar(const double x);\n\n\n/* 1/Gamma(x)\n * Uses real Lanczos method.\n *\n * exceptions: GSL_EUNDRFLW, GSL_EROUND\n */\nint gsl_sf_gammainv_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_gammainv(const double x);\n\n\n/* Log[Gamma(z)] for z complex, z not a negative integer\n * Uses complex Lanczos method. Note that the phase part (arg)\n * is not well-determined when |z| is very large, due\n * to inevitable roundoff in restricting to (-Pi,Pi].\n * This will raise the GSL_ELOSS exception when it occurs.\n * The absolute value part (lnr), however, never suffers.\n *\n * Calculates:\n * lnr = log|Gamma(z)|\n * arg = arg(Gamma(z)) in (-Pi, Pi]\n *\n * exceptions: GSL_EDOM, GSL_ELOSS\n */\nint gsl_sf_lngamma_complex_e(double zr, double zi, gsl_sf_result * lnr, gsl_sf_result * arg);\n\n\n/* x^n / n!\n *\n * x >= 0.0, n >= 0\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_taylorcoeff_e(const int n, const double x, gsl_sf_result * result);\ndouble gsl_sf_taylorcoeff(const int n, const double x);\n\n\n/* n!\n *\n * exceptions: GSL_EDOM, GSL_OVRFLW\n */\nint gsl_sf_fact_e(const unsigned int n, gsl_sf_result * result);\ndouble gsl_sf_fact(const unsigned int n);\n\n\n/* n!! = n(n-2)(n-4) ... \n *\n * exceptions: GSL_EDOM, GSL_OVRFLW\n */\nint gsl_sf_doublefact_e(const unsigned int n, gsl_sf_result * result);\ndouble gsl_sf_doublefact(const unsigned int n);\n\n\n/* log(n!) \n * Faster than ln(Gamma(n+1)) for n < 170; defers for larger n.\n *\n * exceptions: none\n */\nint gsl_sf_lnfact_e(const unsigned int n, gsl_sf_result * result);\ndouble gsl_sf_lnfact(const unsigned int n);\n\n\n/* log(n!!) \n *\n * exceptions: none\n */\nint gsl_sf_lndoublefact_e(const unsigned int n, gsl_sf_result * result);\ndouble gsl_sf_lndoublefact(const unsigned int n);\n\n\n/* log(n choose m)\n *\n * exceptions: GSL_EDOM \n */\nint gsl_sf_lnchoose_e(unsigned int n, unsigned int m, gsl_sf_result * result);\ndouble gsl_sf_lnchoose(unsigned int n, unsigned int m);\n\n\n/* n choose m\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_choose_e(unsigned int n, unsigned int m, gsl_sf_result * result);\ndouble gsl_sf_choose(unsigned int n, unsigned int m);\n\n\n/* Logarithm of Pochhammer (Apell) symbol\n * log( (a)_x )\n * where (a)_x := Gamma[a + x]/Gamma[a]\n *\n * a > 0, a+x > 0\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_lnpoch_e(const double a, const double x, gsl_sf_result * result);\ndouble gsl_sf_lnpoch(const double a, const double x);\n\n\n/* Logarithm of Pochhammer (Apell) symbol, with sign information.\n * result = log( |(a)_x| )\n * sgn = sgn( (a)_x )\n * where (a)_x := Gamma[a + x]/Gamma[a]\n *\n * a != neg integer, a+x != neg integer\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_lnpoch_sgn_e(const double a, const double x, gsl_sf_result * result, double * sgn);\n\n\n/* Pochhammer (Apell) symbol\n * (a)_x := Gamma[a + x]/Gamma[x]\n *\n * a != neg integer, a+x != neg integer\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_poch_e(const double a, const double x, gsl_sf_result * result);\ndouble gsl_sf_poch(const double a, const double x);\n\n\n/* Relative Pochhammer (Apell) symbol\n * ((a,x) - 1)/x\n * where (a,x) = (a)_x := Gamma[a + x]/Gamma[a]\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_pochrel_e(const double a, const double x, gsl_sf_result * result);\ndouble gsl_sf_pochrel(const double a, const double x);\n\n\n/* Normalized Incomplete Gamma Function\n *\n * Q(a,x) = 1/Gamma(a) Integral[ t^(a-1) e^(-t), {t,x,Infinity} ]\n *\n * a >= 0, x >= 0\n * Q(a,0) := 1\n * Q(0,x) := 0, x != 0\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_gamma_inc_Q_e(const double a, const double x, gsl_sf_result * result);\ndouble gsl_sf_gamma_inc_Q(const double a, const double x);\n\n\n/* Complementary Normalized Incomplete Gamma Function\n *\n * P(a,x) = 1/Gamma(a) Integral[ t^(a-1) e^(-t), {t,0,x} ]\n *\n * a > 0, x >= 0\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_gamma_inc_P_e(const double a, const double x, gsl_sf_result * result);\ndouble gsl_sf_gamma_inc_P(const double a, const double x);\n\n\n/* Non-normalized Incomplete Gamma Function\n *\n * Gamma(a,x) := Integral[ t^(a-1) e^(-t), {t,x,Infinity} ]\n *\n * x >= 0.0\n * Gamma(a, 0) := Gamma(a)\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_gamma_inc_e(const double a, const double x, gsl_sf_result * result);\ndouble gsl_sf_gamma_inc(const double a, const double x);\n\n\n/* Logarithm of Beta Function\n * Log[B(a,b)]\n *\n * a > 0, b > 0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_lnbeta_e(const double a, const double b, gsl_sf_result * result);\ndouble gsl_sf_lnbeta(const double a, const double b);\n\nint gsl_sf_lnbeta_sgn_e(const double x, const double y, gsl_sf_result * result, double * sgn);\n\n\n/* Beta Function\n * B(a,b)\n *\n * a > 0, b > 0\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_beta_e(const double a, const double b, gsl_sf_result * result);\ndouble gsl_sf_beta(const double a, const double b);\n\n\n/* Normalized Incomplete Beta Function\n * B_x(a,b)/B(a,b)\n *\n * a > 0, b > 0, 0 <= x <= 1\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_beta_inc_e(const double a, const double b, const double x, gsl_sf_result * result);\ndouble gsl_sf_beta_inc(const double a, const double b, const double x);\n\n\n/* The maximum x such that gamma(x) is not\n * considered an overflow.\n */\n#define GSL_SF_GAMMA_XMAX 171.0\n\n/* The maximum n such that gsl_sf_fact(n) does not give an overflow. */\n#define GSL_SF_FACT_NMAX 170\n\n/* The maximum n such that gsl_sf_doublefact(n) does not give an overflow. */\n#define GSL_SF_DOUBLEFACT_NMAX 297\n\n__END_DECLS\n\n#endif /* __GSL_SF_GAMMA_H__ */\n", "meta": {"hexsha": "a06b74edd456d2220d8614fd20fdacb58890a997", "size": 7748, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_sf_gamma.h", "max_stars_repo_name": "iti-luebeck/HANSE2011", "max_stars_repo_head_hexsha": "0bd5b3f1e0bc5a02516e7514b2241897337334c2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/specfunc/gsl_sf_gamma.h", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-01-29T22:11:01.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-09T10:24:03.000Z", "max_forks_repo_path": "gsl/include/gsl/gsl_sf_gamma.h", "max_forks_repo_name": "gersteinlab/LESSeq", "max_forks_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-02-01T15:12:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T23:53:15.000Z", "avg_line_length": 26.3537414966, "max_line_length": 94, "alphanum_fraction": 0.693598348, "num_tokens": 2321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5934094115885857}} {"text": "#include \"scf.h\"\n#include \"scf_decompose.h\"\n#include \n#include \n\n/* computes a!/b! = a(a-1)(a-2)...(b+1) */\ndouble factorial_frac(int a, int b) \n{\n if(a<0 || b<0)\n {\n perror(\"factorial_frac: either a or b is negative!!\\n\");\n exit(1);\n }\n\n int recip = 0;\n if(a==b)\n return 1.0;\n else if(a b)\n {\n val = val * a;\n a--;\n }\n \n if(recip)\n val = 1.0/val;\n \n return val;\n \n}\n\nvoid scf_integral(double* mat_cos, double* mat_sin)\n{\t\n long long k;\n double* rr = (double*)malloc(NumPart*sizeof(double));\n double* cos_tt = (double*)malloc(NumPart*sizeof(double));\n double* pp = (double*)malloc(NumPart*sizeof(double));\n\n#ifdef USE_GSL_GEGENBAUER_HOST\n double* xxi = (double*)malloc(NumPart*sizeof(double));\n double this_Cna;\n#endif\n\n /* cos_tt is calculated directly by cos(theta)=z/r because\n we never need theta by itself, but only cos(theta) in the \n legendre polynomials. Also, notice that cos_tt must be\n calculated in double precision because with single precision\n zz[k] can be greater than rr[k] by a tiny bit, which \n the plgndr routine will complain later on */\n\n for(k=0; k\n#include \n#include \n#include \n#include \n#include \n#include \"magneticTrap.h\"\n//#include \n#define SIZE 3\n\n//Function to calculate beta. The speed is then v=beta*c\ndouble calculateBeta(double T) {\n double eMass = 9.10938356e-31;\n double c = 299792458.0;\n double factor = pow(T,2.0)/(pow(eMass,2.0)*pow(c,4.0)) + (2.0*T)/(eMass*pow(c,2.0)) + 1;\n double beta = sqrt(1.0 - 1.0/factor);\n return beta;\n}\n\nint main (int argc, const char * argv[]) {\n int i, j;\n //FILE *inputFile = fopen(\"simParms.dat\",\"r\");\n //for(int kk=0; kk<10; kk++){\n //}\n //\n double lambda,lambda0,Bx,By,Bz,q,dt,posX,posY,posZ;\n double kinE, mass,gamma,c,Ux,Uy,Uz,magV,magVComputed;\n double dirCosX, dirCosY, dirCosZ, rotationR, solenoidWidth;\n double coilRadius, current, mu, coilPosZMin1, coilPosZMax1, coilPosZMin2, coilPosZMax2;\n double Z_coil1_, Z_coil2_ ; \n int nTsteps, nCoils;\n\n //double vecRHS[SIZE] = {0.0, 0.0, 0.0};\n //double Bfield[SIZE] = {0.0, 0.0, 0.0 };\n //double Bcgrnd[SIZE] = {0.0, 0.0, 1.0 };\n double *vecRHS, *Bfield, *background;\n vecRHS = (double*)malloc(SIZE*sizeof(double));\n Bfield = (double*)malloc(SIZE*sizeof(double));\n background = (double*)malloc(SIZE*sizeof(double));\n background[0] = 0.0; background[1] = 0.0; background[2] = 1.0;\n lapack_int info,nRowsA,nColsB,nColsARowsB,ldA,ldB,ipvt[SIZE*SIZE];\n\n dt= 5.0e-12;\n nTsteps = 2.5e6;\n q = 1.602176634e-19;\n c = 299792458.0;\n mass = 9.10938356e-31;\n kinE = 18575.0*q;\n rotationR = 4.6375e-4;\n solenoidWidth = 0.2;\n coilRadius = 0.05; \n current = 20.0;\n nCoils = 11;\n mu = 1.25663706e-6;\n Z_coil1_ = -0.5;\n Z_coil2_ = 0.5;\n coilPosZMin1 = Z_coil1_ - solenoidWidth/2.0;\n coilPosZMax1 = Z_coil1_ + solenoidWidth/2.0;\n coilPosZMin2 = Z_coil2_ - solenoidWidth/2.0;\n coilPosZMax2 = Z_coil2_ + solenoidWidth/2.0;\n\n posX=rotationR;posY=0.0;posZ=0.0;\n bathTubFieldSolenoids(coilRadius, current, coilPosZMin1, coilPosZMax1, coilPosZMin2, coilPosZMax2, nCoils,\n mu, posX, posY, posZ, background, Bfield);\n Bx = Bfield[0]; By = Bfield[1]; Bz = Bfield[2]; \n //-----------\n magV = calculateBeta(kinE)*c;\n double pitchAngle = 85.0 * M_PI/180.0;\n dirCosX = 0.0; dirCosZ=cos(pitchAngle); dirCosY=1.0-dirCosZ;\n Ux = magV*dirCosX; Uy=magV*dirCosY; Uz=magV*dirCosZ;\n //double ufuture[SIZE] = {0.0, 0.0, 0.0};\n\t//double upast[SIZE] = {Ux, Uy, Uz};\n double *ufuture, *upast;\n ufuture = (double*)malloc(SIZE*sizeof(double));\n upast = (double*)malloc(SIZE*sizeof(double));\n upast[0] = Ux; upast[1] = Uy; upast[2] = Uz;\n printf(\"# Starting simulation with U(x), U(y), U(z) = %8.5e , %8.5e , %8.5e \\n\", Ux, Uy, Uz);\n gamma = 1.0/(sqrt(1.0-(pow(magV,2.0))/(pow(c,2.0))));\n lambda0= (0.5*q*dt)/(2.0*mass*gamma); // Careful: this definition is only for the first time step\n lambda = (1.0*q*dt)/(2.0*mass*gamma); // Careful: this definition is only for the first time step\n\n //writing a and b as vectors, but they are in concept the matrices of the system of linear equations\n //double a[SIZE*SIZE] = { 1.0, lambda0*Bz,-lambda0*By , -lambda0*Bz,1.0, lambda0*Bx , lambda0*By,-lambda0*Bx,1.0 };\n //double b[SIZE*SIZE] = { 1.0,-lambda0*Bz, lambda0*By , lambda0*Bz,1.0,-lambda0*Bx , -lambda0*By, lambda0*Bx,1.0 };\n double *a, *b;\n a = (double*)malloc(SIZE*SIZE*sizeof(double));\n b = (double*)malloc(SIZE*SIZE*sizeof(double));\n\n a[0] = 1.0; a[1] = lambda0*Bz; a[2] = -lambda0*By;\n a[3] = -lambda0*Bz; a[4] = 1.0; a[5] = lambda0*Bx;\n a[6] = lambda0*By; a[7] = -lambda0*Bx; a[8] = 1.0; \n\n b[0] = 1.0; b[1] = -lambda0*Bz; b[2] = lambda0*By;\n b[3] = lambda0*Bz; b[4] = 1.0; b[5] = -lambda0*Bx;\n b[6] = -lambda0*By; b[7] = lambda0*Bx; b[8] = 1.0;\n\n\n nRowsA = SIZE;\n nColsB = 1;\n nColsARowsB = SIZE;\n ldA = nRowsA;\n ldB = nColsARowsB;\n\n // Printing LHS matrix\n /*printf(\"#LHS Matrix (Traspose -> Column major order -----------\\t | \\n\");\n for(i=0;i Column major order -----------\\t | \\n\");\n for(i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef genann_act\n#define genann_act_hidden genann_act_hidden_indirect\n#define genann_act_output genann_act_output_indirect\n#else\n#define genann_act_hidden genann_act\n#define genann_act_output genann_act\n#endif\n\n#define LOOKUP_SIZE 4096\n\ndouble genann_act_hidden_indirect(const struct genann *ann, double a) {\n return ann->activation_hidden(ann, a);\n}\n\ndouble genann_act_output_indirect(const struct genann *ann, double a) {\n return ann->activation_output(ann, a);\n}\n\nconst double sigmoid_dom_min = -15.0;\nconst double sigmoid_dom_max = 15.0;\ndouble interval;\ndouble lookup[LOOKUP_SIZE];\n\n#ifdef __GNUC__\n#define likely(x) __builtin_expect(!!(x), 1)\n#define unlikely(x) __builtin_expect(!!(x), 0)\n#define unused __attribute__((unused))\n#else\n#define likely(x) x\n#define unlikely(x) x\n#define unused\n#pragma warning(disable : 4996) /* For fscanf */\n#endif\n\n\ndouble genann_act_sigmoid(const genann *ann unused, double a) {\n if (a < -45.0) return 0;\n if (a > 45.0) return 1;\n return 1.0 / (1 + exp(-a));\n}\n\nvoid genann_init_sigmoid_lookup(const genann *ann) {\n const double f = (sigmoid_dom_max - sigmoid_dom_min) / LOOKUP_SIZE;\n int i;\n\n interval = LOOKUP_SIZE / (sigmoid_dom_max - sigmoid_dom_min);\n for (i = 0; i < LOOKUP_SIZE; ++i) {\n lookup[i] = genann_act_sigmoid(ann, sigmoid_dom_min + f * i);\n }\n}\n\ndouble genann_act_sigmoid_cached(const genann *ann unused, double a) {\n assert(!isnan(a));\n\n if (a < sigmoid_dom_min) return lookup[0];\n if (a >= sigmoid_dom_max) return lookup[LOOKUP_SIZE - 1];\n\n size_t j = (size_t)((a-sigmoid_dom_min)*interval+0.5);\n\n /* Because doubleing point... */\n if (unlikely(j >= LOOKUP_SIZE)) return lookup[LOOKUP_SIZE - 1];\n\n return lookup[j];\n}\n\ndouble genann_act_linear(const struct genann *ann unused, double a) {\n return a;\n}\n\ndouble genann_act_threshold(const struct genann *ann unused, double a) {\n return a > 0;\n}\n\ngenann *genann_init(int inputs, int hidden_layers, int hidden, int outputs) {\n if (hidden_layers < 0) return 0;\n if (inputs < 1) return 0;\n if (outputs < 1) return 0;\n if (hidden_layers > 0 && hidden < 1) return 0;\n\n\n const int hidden_weights = hidden_layers ? (inputs+1) * hidden + (hidden_layers-1) * (hidden+1) * hidden : 0;\n const int output_weights = (hidden_layers ? (hidden+1) : (inputs+1)) * outputs;\n const int total_weights = (hidden_weights + output_weights);\n\n const int total_neurons = (inputs + hidden * hidden_layers + outputs);\n\n /* Allocate extra size for weights, outputs, and deltas. */\n const int size = sizeof(genann) + sizeof(double) * (total_weights + total_neurons + (total_neurons - inputs));\n genann *ret = malloc(size);\n if (!ret) return 0;\n\n ret->inputs = inputs;\n ret->hidden_layers = hidden_layers;\n ret->hidden = hidden;\n ret->outputs = outputs;\n\n ret->total_weights = total_weights;\n ret->total_neurons = total_neurons;\n\n /* Set pointers. */\n ret->weight = (double*)((char*)ret + sizeof(genann));\n ret->output = ret->weight + ret->total_weights;\n ret->delta = ret->output + ret->total_neurons;\n\n genann_randomize(ret);\n\n ret->activation_hidden = genann_act_sigmoid_cached;\n ret->activation_output = genann_act_sigmoid_cached;\n\n genann_init_sigmoid_lookup(ret);\n\n return ret;\n}\n\n\ngenann *genann_read(FILE *in) {\n int inputs, hidden_layers, hidden, outputs;\n int rc;\n\n errno = 0;\n rc = fscanf(in, \"%d %d %d %d\", &inputs, &hidden_layers, &hidden, &outputs);\n if (rc < 4 || errno != 0) {\n perror(\"fscanf\");\n return NULL;\n }\n\n genann *ann = genann_init(inputs, hidden_layers, hidden, outputs);\n\n int i;\n for (i = 0; i < ann->total_weights; ++i) {\n errno = 0;\n rc = fscanf(in, \" %le\", ann->weight + i);\n if (rc < 1 || errno != 0) {\n perror(\"fscanf\");\n genann_free(ann);\n\n return NULL;\n }\n }\n\n return ann;\n}\n\n\ngenann *genann_copy(genann const *ann) {\n const int size = sizeof(genann) + sizeof(double) * (ann->total_weights + ann->total_neurons + (ann->total_neurons - ann->inputs));\n genann *ret = malloc(size);\n if (!ret) return 0;\n\n memcpy(ret, ann, size);\n\n /* Set pointers. */\n ret->weight = (double*)((char*)ret + sizeof(genann));\n ret->output = ret->weight + ret->total_weights;\n ret->delta = ret->output + ret->total_neurons;\n\n return ret;\n}\n\n\nvoid genann_randomize(genann *ann) {\n int i;\n for (i = 0; i < ann->total_weights; ++i) {\n double r = GENANN_RANDOM();\n /* Sets weights from -0.5 to 0.5. */\n ann->weight[i] = r - 0.5;\n }\n}\n\n\nvoid genann_free(genann *ann) {\n /* The weight, output, and delta pointers go to the same buffer. */\n free(ann);\n}\n\ndouble const *genann_run(genann const *ann, double const *inputs) {\n //Copy the weights into a more convenient variable\n double const *w = ann->weight;\n //Initialize the output vector to point at the second layer of neurons\n double *o = ann->output + ann->inputs;\n //Initialize the input vector to point at the first layer of neurons\n double const *i = ann->output;\n\n /* Copy the inputs to the scratch area, where we also store each neuron's\n * output, for consistency. This way the first layer isn't a special case. */\n memcpy(ann->output, inputs, sizeof(double) * ann->inputs);\n\n int h, j, k;\n\n if (!ann->hidden_layers) {\n double *ret = o;\n for (j = 0; j < ann->outputs; ++j) {\n double sum = *w++ * -1.0;\n for (k = 0; k < ann->inputs; ++k) {\n sum += *w++ * i[k];\n }\n *o++ = genann_act_output(ann, sum);\n }\n\n return ret;\n }\n\n /* Figure input layer */\n for (j = 0; j < ann->hidden; ++j) {\n double sum = *w++ * -1.0;\n for (k = 0; k < ann->inputs; ++k) {\n sum += *w++ * i[k];\n }\n *o++ = genann_act_hidden(ann, sum);\n }\n\n i += ann->inputs;\n\n /////////////////////////////////\n // TODO: 1 GEMV using BLAS //\n /////////////////////////////////\n\n\n /*\n Function description:\n\n Activates each neuron in the input layer based on an input vector.\n Propagates these activations through the network.\n\n Variables:\n ann: The neural network\n ann->weights: The edge and neuron weights for all layers\n ann->inputs: The number of neurons in the input layer\n ann->hidden: The number of neurons in the hidden layers\n ann->hidden_layers: The number of hidden layers in the network\n ann->output: The neuron activations for the whole network, incluing input, hidden and final layer.\n inputs: The input vector\n w: Points at ann->weights\n o: Points at the layer of ann->output we are currently writing to\n i: Points to the layer of ann->output we are currently using as input.\n i.e. the previous layer.\n\n When the function returns, ann->output contains the final result.\n */\n\n\n /* Comment from original source: Figure hidden layers, if any. */\n\n //These are the dimensions of the square weight matrix\n int m = ann->hidden;\n int n = ann->hidden;\n\n //In addition to n edge weights, each neuron has one value (bias) associated with it.\n //This value is *also* saved in w, meaning the complete matrix has (n+1)*m elements.\n //This value is always multiplied by -1, which we make room for in a copy of the input vector.\n double* temp_i = malloc( (ann->hidden+1) * sizeof(double) );\n double* sums = calloc((ann->hidden+1), sizeof(double));\n\n for (h = 1; h < ann->hidden_layers; ++h) {\n //Copyyng the input vector and setting the first value to -1 as described above.\n temp_i[0] = -1.0;\n memcpy(temp_i+1, i, n*sizeof(double));\n\n ////////////////////////////////////////////////////////////\n // Decompose and replace this double for loop with GEMV call\n for (j = 0; j < ann->hidden; ++j) {\n for (k = 0; k < ann->hidden+1; ++k) {\n sums[j] += w[k + j*(ann->hidden+1)] * temp_i[k];\n }\n o[j] = genann_act_hidden(ann, sums[j]);\n }\n ////////////////////////////////////////////////////////////\n\n w += (n + 1) * m;\n o += m;\n i += m;\n }\n free(temp_i);\n free(sums);\n\n /////////////////////////////////\n // TODO 1 END //\n /////////////////////////////////\n\n double const *ret = o;\n /* Figure output layer. */\n for (j = 0; j < ann->outputs; ++j) {\n double sum = *w++ * -1.0;\n for (k = 0; k < ann->hidden; ++k) {\n sum += *w++ * i[k];\n }\n *o++ = genann_act_output(ann, sum);\n }\n\n /* Sanity check that we used all weights and wrote all outputs. */\n assert(w - ann->weight == ann->total_weights);\n assert(o - ann->output == ann->total_neurons);\n\n return ret;\n}\n\n\nvoid genann_train(genann const *ann, double const *inputs, double const *desired_outputs, double learning_rate) {\n /* To begin with, we must run the network forward. */\n genann_run(ann, inputs);\n\n int h, j, k;\n\n\n /*\n TDT4200 comment: This lonesome curly bracket starts a new scope.\n That means no variables declared within will be\n visible outside outside it (that is, o, d and t).\n That also means the names can safely be re-used later.\n */\n { /* First set the output layer deltas. */\n double const *o = ann->output + ann->inputs + ann->hidden * ann->hidden_layers; /* First output. */\n double *d = ann->delta + ann->hidden * ann->hidden_layers; /* First delta. */\n double const *t = desired_outputs; /* First desired output. */\n\n\n /* Set output layer deltas. */\n if (genann_act_output == genann_act_linear ||\n ann->activation_output == genann_act_linear) {\n for (j = 0; j < ann->outputs; ++j) {\n *d++ = *t++ - *o++;\n }\n } else {\n for (j = 0; j < ann->outputs; ++j) {\n *d++ = (*t - *o) * *o * (1.0 - *o);\n ++o; ++t;\n }\n }\n }\n\n\n /* Set hidden layer deltas, start on last layer and work backwards. */\n /* Note that loop is skipped in the case of hidden_layers == 0. */\n for (h = ann->hidden_layers - 1; h >= 0; --h) {\n\n /* Find first output and delta in this layer. */\n double const *o = ann->output + ann->inputs + (h * ann->hidden);\n double *d = ann->delta + (h * ann->hidden);\n\n /* Find first delta in following layer (which may be hidden or output). */\n double const * const dd = ann->delta + ((h+1) * ann->hidden);\n\n /* Find first weight in following layer (which may be hidden or output). */\n double const * const ww = ann->weight + ((ann->inputs+1) * ann->hidden) + ((ann->hidden+1) * ann->hidden * (h));\n\n\n /////////////////////////////////\n // TODO: 2 GEMV using BLAS //\n /////////////////////////////////\n\n /*\n Function description:\n First, run an input through the network (see TODO 1).\n Then, starting at the output layer and running backwards, determine the\n deltas, the differences between the desired activation and actual\n activation of each neuron.\n\n Variables:\n ann: The artificial neural network, same as in TODO 1. \\\n ann->delta: An area of memory as big as ann->output.\n When function returns, stores difference between desired\n output and actual output.\n h: The index of the current layer. Starting at the output layer and\n going backwards.\n o: The actual output of the current layer, produced by TODO 1 function.\n d: The delta vector of the current layer, this is what we're calculating\n dd: The delta vector of the *previous* layer, at index (h+1).\n ww: The edge weights going from the previous layer and the current one.\n\n Note 1: We're playing fast and loose with the term \"difference\" here.\n It is not strictly a [desired]-[actual] calculation, but can be\n conceptually thought of as a difference.\n Note 2: We say \"previous\" layer meaning the layer involved in the\n previous calculation. Because we are going backwards, this is,\n strictly speaking, the \"following\" layer, which is what it is\n called in the source code comments.\n */\n\n // TODO 2.a: Define the m and n dimension of the delta matrix\n // Hint: Look at the double for loop\n int m = 0;\n int n = 0;\n\n //A temporary vector to store the propagated delta from the previuos layer.\n double* delta = calloc(ann->hidden, sizeof(double));\n\n // TODO 2.b: Decompose and implement GEMV BLAS call for the code\n // Hint: Think about how ww is offset from its original address.\n // You will need pointer arithmetic for the BLAS call\n for (j = 0; j < ann->hidden; ++j) {\n //We iterate up to the value ann->outputs if we are on the output layer,\n //h == ann->hidden_layers-1, and to ann->hidden otherwise.\n for (k = 0; k < (h == ann->hidden_layers-1 ? ann->outputs : ann->hidden); ++k) {\n //Similarly to TODO 1, we add 1 to ann->hidden and j here as a\n //consequence of how bias for each neuron is stored.\n const int windex = k * (ann->hidden + 1) + (j + 1);\n //Propagate the deltas from the previous layer backwards\n //Using the weights between the layers and storing the result in \"delta\"\n delta[j] += dd[k] * ww[windex];\n }\n //Calculate the actual new deltas for this layer\n d[j] = o[j] * (1.0-o[j]) * delta[j];\n }\n\n free(delta);\n\n /////////////////////////////////\n // TODO 2 END //\n /////////////////////////////////\n }\n\n\n /* Train the outputs. */\n {\n /* Find first output delta. */\n double const *d = ann->delta + ann->hidden * ann->hidden_layers; /* First output delta. */\n\n /* Find first weight to first output delta. */\n double *w = ann->weight + (ann->hidden_layers\n ? ((ann->inputs+1) * ann->hidden + (ann->hidden+1) * ann->hidden * (ann->hidden_layers-1))\n : (0));\n\n /* Find first output in previous layer. */\n double const * const i = ann->output + (ann->hidden_layers\n ? (ann->inputs + (ann->hidden) * (ann->hidden_layers-1))\n : 0);\n\n /* Set output layer weights. */\n for (j = 0; j < ann->outputs; ++j) {\n *w++ += *d * learning_rate * -1.0;\n for (k = 1; k < (ann->hidden_layers ? ann->hidden : ann->inputs) + 1; ++k) {\n *w++ += *d * learning_rate * i[k-1];\n }\n\n ++d;\n }\n\n assert(w - ann->weight == ann->total_weights);\n }\n\n\n /* Train the hidden layers. */\n for (h = ann->hidden_layers - 1; h >= 0; --h) {\n\n /* Find first delta in this layer. */\n double const *d = ann->delta + (h * ann->hidden);\n\n /* Find first input to this layer. */\n double const *i = ann->output + (h\n ? (ann->inputs + ann->hidden * (h-1))\n : 0);\n\n /* Find first weight to this layer. */\n double *w = ann->weight + (h\n ? ((ann->inputs+1) * ann->hidden + (ann->hidden+1) * (ann->hidden) * (h-1))\n : 0);\n\n\n /////////////////////////////////\n // TODO: 3 (Optional) Optimize //\n /////////////////////////////////\n for (j = 0; j < ann->hidden; ++j) {\n *w++ += *d * learning_rate * -1.0;\n for (k = 1; k < (h == 0 ? ann->inputs : ann->hidden) + 1; ++k) {\n *w++ += *d * learning_rate * i[k-1];\n }\n ++d;\n }\n /////////////////////////////////\n // TODO 3 END //\n /////////////////////////////////\n }\n\n}\n\n\nvoid genann_write(genann const *ann, FILE *out) {\n fprintf(out, \"%d %d %d %d\", ann->inputs, ann->hidden_layers, ann->hidden, ann->outputs);\n\n int i;\n for (i = 0; i < ann->total_weights; ++i) {\n fprintf(out, \" %.20e\", ann->weight[i]);\n }\n}\n", "meta": {"hexsha": "3d3b31083b764800ca9cf0466cecef3e85fb71ec", "size": 17678, "ext": "c", "lang": "C", "max_stars_repo_path": "TDT4200/A3/genann.c", "max_stars_repo_name": "jorgstei/Datateknologi", "max_stars_repo_head_hexsha": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e", "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": "TDT4200/A3/genann.c", "max_issues_repo_name": "jorgstei/Datateknologi", "max_issues_repo_head_hexsha": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e", "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": "TDT4200/A3/genann.c", "max_forks_repo_name": "jorgstei/Datateknologi", "max_forks_repo_head_hexsha": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e", "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.9961538462, "max_line_length": 134, "alphanum_fraction": 0.5623373685, "num_tokens": 4526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.5927984302735176}} {"text": "/* Implementation of the interface in orbital_state_vector.h. */\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"basic_types.h\"\n#include \"earth_constants.h\"\n#include \"orbital_state_vector.h\"\n\nOrbitalStateVector *\norbital_state_vector_new (double x, double y, double z, double vx, double vy,\n\t\t\t double vz)\n{\n OrbitalStateVector *self = malloc (sizeof (OrbitalStateVector));\n\n self->position = vector_new (x, y, z);\n self->velocity = vector_new (vx, vy, vz);\n\n return self;\n}\n\nOrbitalStateVector *\norbital_state_vector_copy (OrbitalStateVector *a)\n{\n OrbitalStateVector *new = malloc (sizeof (OrbitalStateVector));\n\n new->position = vector_copy (a->position);\n new->velocity = vector_copy (a->velocity);\n\n return new;\n}\n\nvoid\norbital_state_vector_get_keplerian_elements \n(OrbitalStateVector *self, double *a, double *e, double *i, \n double *capital_omega, double *lower_case_omega, double *nu, double *E, \n double *M)\n{\n /* Shorthand. */\n static const double gm = EARTH_GRAVITATIONAL_CONSTANT;\n\n /* Fundamental vectors as described in \"Satellite Geodesy\". */\n Vector *h = vector_cross (self->position, self->velocity);\n Vector *X = vector_new (1.0, 0.0, 0.0);\n Vector *Z = vector_new (0.0, 0.0, 1.0);\n Vector *n = vector_cross (Z, h);\n double r_dot_v = vector_dot (self->position, self->velocity);\n double r_mag = vector_magnitude (self->position);\n double v_mag = vector_magnitude (self->velocity);\n Vector *tmp1 = vector_copy (self->position);\n Vector *tmp2 = vector_copy (self->velocity);\n /* Fundamental vector 'e' ('_fv' is appended to dodge name clash). */\n Vector *e_fv;\n double h_mag;\n double n_mag;\n\n vector_multiply (tmp1, pow (v_mag, 2) - gm / r_mag);\n vector_multiply (tmp2, r_dot_v);\n vector_subtract (tmp1, tmp2);\n vector_multiply (tmp1, (1.0 / gm));\n e_fv = vector_copy (tmp1);\n\n /* Compute keplerian elements. */\n *e = vector_magnitude (e_fv);\n h_mag = vector_magnitude (h);\n *a = (pow (h_mag, 2) / gm) / (1 - pow (*e, 2));\n *i = acos (vector_dot (h, Z) / h_mag);\n n_mag = vector_magnitude (n);\n *capital_omega = acos (vector_dot (n, X) / n_mag);\n *lower_case_omega = acos (vector_dot (n, e_fv) / (n_mag * (*e)));\n *nu = acos (vector_dot (e_fv, self->position) \n\t / ((*e) * vector_magnitude (self->position)));\n *E = acos ((*e + cos (*nu)) / (1.0 + (*e) * cos (*nu)));\n *M = *E - (*e) * sin (*E);\n\n /* Free fundamental and temporary vectors used in computation. */\n free (h);\n free (Z);\n free (X);\n free (n);\n free (tmp1);\n free (tmp2);\n free (e_fv);\n}\n\ndouble\norbital_state_vector_height_above_ellipsoid (OrbitalStateVector *self)\n{\n double r = vector_magnitude (self->position);\n\n /* Compute height of satellite above the WGS84 ellipsoid. */\n static Vector z_unit = {0.0, 0.0, 1.0};\n /* Angle between position vector and equatorial plane. */\n double eq_angle = M_PI / 2 - vector_angle (self->position, &z_unit);\n double ae = EARTH_SEMIMAJOR_AXIS;\n /* Earth semiminor axis. */\n double be = sqrt (pow (ae, 2) * (1 - pow (EARTH_ECCENTRICITY, 2)));\n /* Radius of ellipsoid at point under satellite. */\n double ellipsoid_radius = sqrt (pow (ae * cos (eq_angle), 2)\n\t\t\t\t + pow (be * sin (eq_angle), 2));\n\n return r - ellipsoid_radius;\n}\n\n/* Compute derivatives f from functions y(t), t, and other\n miscellaneous parameters. Return GSL_SUCCESS after successful\n computation. This code mostly follows the example in the GNU\n Scientific Library documentation, which uses a y array for the\n function values. The y[1] value is the only one that corresponds\n to the y coordinate, and the y[4] vale the only one that\n corresponds to the y velocity. */\nstatic int\nfunc (double t, const double y[], double f[], void *params)\n{\n /* Shorthand for some earth constants. */\n static const double gm = EARTH_GRAVITATIONAL_CONSTANT;\n static const double ae = EARTH_SEMIMAJOR_AXIS;\n\n /* Create position and velocity vectors. We use static vectors to\n avoid allocation overhead. */\n static Vector p_st;\n static Vector v_st;\n static Vector *p = &p_st;\n static Vector *v = &v_st;\n\n double r;\n double j2;\n double a_j2_x, a_j2_y, a_j2_z;\n double ksx, ksy, ksz;\n\n vector_set (p, y[0], y[1], y[2]);\n vector_set (v, y[3], y[4], y[5]);\n\n /* Current range to satellife from center of earth. */\n r = vector_magnitude (p);\n double r3 = r*r*r;\n\n /* The so-called first zonal harmonic is used to account for the\n effects of earth oblatedness (see below for references). */\n j2 = 1082.63e-6;\t/* First zonal harmonic coefficient. */\n a_j2_x = (gm * p->x / r3) * j2 * (3.0 / 2) * (ae*ae / (r*r))\n * (5.0 * (p->z * p->z) / (r*r) - 1.0);\n a_j2_y = (p->y / p->x) * a_j2_x;\n a_j2_z = (-gm * p->z / r3) * j2 * (3.0 / 2) \n * (ae*ae / (r*r)) * (3.0 - 5.0 * (p->z * p->z) / (r*r));\n\n /* Total perturbations. */\n ksx = a_j2_x;\n ksy = a_j2_y;\n ksz = a_j2_z;\n\n f[0] = v->x;\n f[1] = v->y;\n f[2] = v->z;\n f[3] = ksx - gm * (p->x / r3);\n f[4] = ksy - gm * (p->y / r3);\n f[5] = ksz - gm * (p->z / r3);\n\n return GSL_SUCCESS;\n}\n\nvoid\norbital_state_vector_propagate (OrbitalStateVector *self, double time)\n{\n /* We need to solve the following six dimensional system of ordinary\n differential equations:\n\n dx/dt = vx\n\t dy/dt = vy\n\t dz/dt = vz\n\n\t dvx/dt = ksx - (GM / r^3) * x\n\t dvy/dt = ksy - (GM / r^3) * y\n\t dvz/dt = ksz - (GM / r^3) * z\n\n where\n\n r = sqrt (x^2 + y^2 + z^2)\n\n with initial conditions given by the current state. The values\n ksx, ksy, and ksz represent the perturbations due to earth\n oblatedness as described in section 3.2.2.3 respectively of\n \"Satellite Geodesy\", 2nd edition, by Gunter Seeber. An ordinary\n differential equation solver from the GNU Scientific Library\n (GSL) is used to solve the system. It is well described in the\n GSL documentation section \"Ordinary Differential Equations\". */\n\n const int dimension = 6;\n /* Create some things the ODE solver uses. */\n const gsl_odeiv_step_type *step_type = gsl_odeiv_step_rkf45; \n gsl_odeiv_step *ode_step = gsl_odeiv_step_alloc (step_type, dimension);\n /* Hold the absolute integration error for each coordinate for each\n step to within this value. This value was chosen using the\n following sophisticated methodology: Keep tightening the\n tolerance until the answer no longer changes with further\n tightenings, for an short (~2.5 minute) propagation. */\n double mae = 0.000001;\n gsl_odeiv_control *ode_control = gsl_odeiv_control_y_new (mae, 0.0);\n gsl_odeiv_evolve *ode_evolve = gsl_odeiv_evolve_alloc (dimension);\n gsl_odeiv_system ode_system;\n double t0 = 0.0, t1 = time;\t/* Start and end times. */\n /* Initial guess for step size. */\n const double initial_step_size = GSL_SIGN (t1) * 1.0;\n double step_size = initial_step_size;\n double *y = malloc (dimension * sizeof (double));\n double t = t0;\t\t/* Current time. */\n\n ode_system.function = func;\n ode_system.jacobian = NULL;\n ode_system.dimension = dimension;\n ode_system.params = NULL;\n\n y[0] = self->position->x;\n y[1] = self->position->y;\n y[2] = self->position->z;\n y[3] = self->velocity->x;\n y[4] = self->velocity->y;\n y[5] = self->velocity->z;\n /* Here is the actual propagation. */\n while ( fabs (t) < fabs (t1) ) {\n int status = gsl_odeiv_evolve_apply (ode_evolve, ode_control, ode_step, \n\t\t\t\t\t &ode_system, &t, t1, &step_size, y);\n assert (status == GSL_SUCCESS);\n }\n self->position->x = y[0];\n self->position->y = y[1];\n self->position->z = y[2];\n self->velocity->x = y[3];\n self->velocity->y = y[4];\n self->velocity->z = y[5]; \n\n free (y);\n gsl_odeiv_evolve_free (ode_evolve);\n gsl_odeiv_control_free (ode_control);\n gsl_odeiv_step_free (ode_step);\n}\n\nvoid\norbital_state_vector_propagate_interpolate (OrbitalStateVector *self, \n\t\t\t\t\t double time, \n\t\t\t\t\t OrbitalStateVector *other)\n{\n /* Not implemented. */\n assert (FALSE);\n}\n", "meta": {"hexsha": "a7182289b4c16c0f2d82c600f74d0a64a06f630d", "size": 8010, "ext": "c", "lang": "C", "max_stars_repo_path": "src/asf_meta/orbital_state_vector.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/asf_meta/orbital_state_vector.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "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/asf_meta/orbital_state_vector.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 31.9123505976, "max_line_length": 77, "alphanum_fraction": 0.6595505618, "num_tokens": 2565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5924537333184187}} {"text": "#include \n#include \n#define COMPEARTH_PRIVATE_GEM3 1\n#define COMPEARTH_PRIVATE_GEMT3 1\n#include \"compearth.h\"\n#ifdef DEBUG\n#ifdef COMPEARTH_USE_MKL\n#include \n#else\n#include \n#endif\n#endif\n\n/*!\n * @brief Transforms a set of 3 x 3 tensors using transformation matrix T.\n *\n * @param[in] nmt Number of moment tensors.\n * @param[in] T 3 x 3 transformation matrix in column major order.\n * @param[in] Min [3 x 3 x n] input matrices. Each [3 x 3] matrix is in\n * column major order.\n * @param[out] Mout [3 x 3 x n] output matrices. Each [3 x 3] matrix is\n * in column major order.\n * @result 0 indicates success.\n *\n * @author Carl Tape and translated to C by Ben Baker.\n *\n */\nint compearth_transform_mat(const int nmt,\n const double *__restrict__ T,\n const double *__restrict__ Min,\n double *__restrict__ Mout)\n{\n double TM[9];\n int imt; //i, j\n // Compute T*Min*T'\n for (imt=0; imt\n#include \n\n#include \n#include \n#include \n\nint main() {\n\tint ret;\n\tgsl_matrix A;\n\tdouble data[9];\n\tint i, j;\n\n\tmemset(&A, 0, sizeof(gsl_matrix));\n\n\tA.size1 = 3;\n\tA.size2 = 3;\n\tA.tda = 3;\n\tA.data = data;\n\n\tgsl_matrix_set(&A, 0, 0, 34.0);\n\tgsl_matrix_set(&A, 0, 1, 4.0);\n\tgsl_matrix_set(&A, 0, 2, 14.0);\n\tgsl_matrix_set(&A, 1, 0, 1.0);\n\tgsl_matrix_set(&A, 1, 1, 8.0);\n\tgsl_matrix_set(&A, 1, 2, 3.0);\n\tgsl_matrix_set(&A, 2, 0, 7.0);\n\tgsl_matrix_set(&A, 2, 1, 1.0);\n\tgsl_matrix_set(&A, 2, 2, 8.0);\n\n\tfor (i=0; i\n#include \n#include \n#include \n#include \n\n#ifndef M_PIf\n #define M_PIf 3.141592653589793238462643383279502884f\n#endif\n\n#ifndef M_PI\n #define M_PI 3.141592653589793238462643383279502884\n#endif\n\n#ifdef __cplusplus\nnamespace ov {\nextern \"C\" {\n#endif\n\nint get_ccs_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int ndct, const float Q, const int K);\nint get_ccs_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim, const int ndct, const double Q, const int K);\n\n\nint get_ccs_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int ndct, const float Q, const int K)\n{\n const float z = 0.0f;\n const float Q2 = 0.5f*Q, PQ = M_PIf/Q;\n int r, c, k;\n float *X1, *Y1; //*lift;\n fftwf_plan plan;\n //struct timespec tic, toc;\n\n //Checks\n if (R<1) { fprintf(stderr,\"error in get_ccs_s: R (nrows X) must be positive\\n\"); return 1; }\n if (C<1) { fprintf(stderr,\"error in get_ccs_s: C (ncols X) must be positive\\n\"); return 1; }\n if (ndct= R for dim==0\\n\"); return 1; }\n if (ndct= C for dim==1\\n\"); return 1; }\n if (Q<0.0f) { fprintf(stderr,\"error in get_ccs_s: Q must be positive (or 0 to skip lifter)\\n\"); return 1; }\n if (K<1) { fprintf(stderr,\"error in get_ccs_s: K must be positive\\n\"); return 1; }\n if (K>ndct) { fprintf(stderr,\"error in get_ccs_s: K must be <= ndct>\\n\"); return 1; }\n\n //Initialize fftwf\n X1 = fftwf_alloc_real((size_t)ndct);\n Y1 = fftwf_alloc_real((size_t)ndct);\n plan = fftwf_plan_r2r_1d(ndct,X1,Y1,FFTW_REDFT10,FFTW_ESTIMATE);\n if (!plan) { fprintf(stderr,\"error in get_ccs_s: problem creating fftw plan\\n\"); return 1; }\n cblas_scopy(ndct,&z,0,&X1[0],1); //zero-pad\n\n //clock_gettime(CLOCK_REALTIME,&tic);\n\n //Initialize lifter\n //if (!(lift=(float *)malloc((size_t)K*sizeof(float)))) { fprintf(stderr,\"error in get_ccs_s: problem with malloc for lifter. \"); perror(\"malloc\"); return 1; }\n //for (k=0; kFLT_EPSILON)\n {\n for (k=0; kFLT_EPSILON)\n {\n for (k=0; kFLT_EPSILON)\n {\n for (k=0; kFLT_EPSILON)\n {\n for (k=0; k= R for dim==0\\n\"); return 1; }\n if (ndct= C for dim==1\\n\"); return 1; }\n if (Q<0.0) { fprintf(stderr,\"error in get_ccs_d: Q must be positive (or 0 to skip lifter)\\n\"); return 1; }\n if (K<1) { fprintf(stderr,\"error in get_ccs_d: K must be positive\\n\"); return 1; }\n if (K>ndct) { fprintf(stderr,\"error in get_ccs_d: K must be <= ndct>\\n\"); return 1; }\n\n //Initialize fftw\n X1 = fftw_alloc_real((size_t)ndct);\n Y1 = fftw_alloc_real((size_t)ndct);\n plan = fftw_plan_r2r_1d(ndct,X1,Y1,FFTW_REDFT10,FFTW_ESTIMATE);\n if (!plan) { fprintf(stderr,\"error in get_ccs_s: problem creating fftw plan\\n\"); return 1; }\n cblas_dcopy(ndct,&z,0,&X1[0],1); //zero-pad\n\n if (dim==0)\n {\n if (iscolmajor)\n {\n for (c=0; cDBL_EPSILON)\n {\n for (k=0; kDBL_EPSILON)\n {\n for (k=0; kDBL_EPSILON)\n {\n for (k=0; kDBL_EPSILON)\n {\n for (k=0; k\n#include \"compressibleFlow.h\"\n#include \"mesh.h\"\n\n#define DIM 2 /* Geometric dimension */\n\ntypedef struct {\n PetscReal gamma;\n PetscReal rhoL;\n PetscReal rhoR;\n PetscReal uL;\n PetscReal uR;\n PetscReal pL;\n PetscReal pR;\n PetscReal maxTime;\n PetscReal length;\n} InitialConditions;\n\ntypedef struct {\n PetscReal rho;\n PetscReal rhoU[2];//Hardcode for 2 for now\n PetscReal rhoE;\n} EulerNode;\n\ntypedef struct {\n PetscReal pstar,ustar,rhostarL,astarL,SL,SHL,STL,rhostarR,astarR,SR,SHR,STR,gamm1,gamp1;\n} StarState;\n\ntypedef struct {\n InitialConditions initialConditions;\n StarState starState;\n} ProblemSetup;\n\ntypedef struct{\n PetscReal f;\n PetscReal fprm;\n} PressureFunction;\n\nstatic PressureFunction f_and_fprm_rarefaction(PetscReal pstar, PetscReal pLR, PetscReal aLR, PetscReal gam, PetscReal gamm1,PetscReal gamp1) {\n // compute value of pressure function for rarefaction\n PressureFunction function;\n function.f = ((2. * aLR) / gamm1) * (pow(pstar / pLR, 0.5 * gamm1 / gam) - 1.);\n function.fprm = (aLR / pLR / gam) * pow(pstar / pLR, -0.5 * gamp1 / gam);\n return function;\n}\n\nstatic PressureFunction f_and_fprm_shock(PetscReal pstar, PetscReal pLR, PetscReal rhoLR, PetscReal gam, PetscReal gamm1, PetscReal gamp1){\n // compute value of pressure function for shock\n PetscReal A = 2./gamp1/rhoLR;\n PetscReal B = gamm1*pLR/gamp1;\n PetscReal sqrtterm = PetscSqrtReal(A/(pstar+B));\n PressureFunction function;\n function.f = (pstar-pLR)*sqrtterm;\n function.fprm = sqrtterm*(1.-0.5*(pstar-pLR)/(B+pstar));\n return function;\n}\n\n#define EPS 1.e-6\n#define MAXIT 100\nPetscErrorCode DetermineStarState(const InitialConditions* setup, StarState* starState){\n // compute the speed of sound\n PetscReal aL = PetscSqrtReal(setup->gamma*setup->pL/setup->rhoL);\n PetscReal aR = PetscSqrtReal(setup->gamma*setup->pR/setup->rhoR);\n\n //first guess pstar based on two-rarefacation approximation\n starState->pstar = aL+aR - 0.5*(setup->gamma-1.)*(setup->uR-setup->uL);\n starState->pstar = starState->pstar / (aL/pow(setup->pL,0.5*(setup->gamma-1.)/setup->gamma) + aR/pow(setup->pR,0.5*(setup->gamma-1.)/setup->gamma) );\n starState->pstar = pow(starState->pstar,2.*setup->gamma/(setup->gamma-1.));\n starState->gamm1 = setup->gamma-1.;\n starState->gamp1 = setup->gamma+1.;\n\n PressureFunction fL;\n if (starState->pstar <= setup->pL){\n fL = f_and_fprm_rarefaction(starState->pstar, setup->pL,aL,setup->gamma,starState->gamm1,starState->gamp1);\n }else{\n fL = f_and_fprm_shock(starState->pstar,setup->pL,setup->rhoL,setup->gamma,starState->gamm1,starState->gamp1);\n }\n\n PressureFunction fR;\n if (starState->pstar <= setup->pR) {\n fR = f_and_fprm_rarefaction(starState->pstar, setup->pR, aR, setup->gamma, starState->gamm1, starState->gamp1);\n }else {\n fR = f_and_fprm_shock(starState->pstar, setup->pR, setup->rhoR, setup->gamma, starState->gamm1, starState->gamp1);\n }\n PetscReal delu = setup->uR-setup->uL;\n\n // iterate using Newton-Rapson\n if ((fL.f+fR.f+delu)> EPS) {\n // iterate using Newton-Rapson\n for(PetscInt it =0; it < MAXIT+4; it++){\n PetscReal pold = starState->pstar;\n starState->pstar = pold - (fL.f+fR.f+delu)/(fL.fprm+fR.fprm);\n\n if(starState->pstar < 0){\n starState->pstar = EPS;\n }\n\n if(2.0*PetscAbsReal(starState->pstar - pold)/(starState->pstar + pold) < EPS){\n break;\n }else{\n if(starState->pstar < setup->pL){\n fL = f_and_fprm_rarefaction(starState->pstar, setup->pL,aL,setup->gamma,starState->gamm1,starState->gamp1);\n }else{\n fL = f_and_fprm_shock(starState->pstar,setup->pL,setup->rhoL,setup->gamma,starState->gamm1,starState->gamp1);\n }\n if (starState->pstar<=setup->pR) {\n fR = f_and_fprm_rarefaction(starState->pstar, setup->pR, aR, setup->gamma, starState->gamm1, starState->gamp1);\n }else {\n fR = f_and_fprm_shock(starState->pstar, setup->pR, setup->rhoR, setup->gamma, starState->gamm1, starState->gamp1);\n }\n }\n\n if (it>MAXIT){\n SETERRQ(PETSC_COMM_WORLD,1,\"error in Riemann.find_pstar - did not converage for pstar\" );\n }\n }\n }\n\n // determine rest of star state\n starState->ustar = 0.5*(setup->uL+setup->uR+fR.f-fL.f);\n\n // left star state\n PetscReal pratio = starState->pstar/setup->pL;\n if (starState->pstar<=setup->pL) { // rarefaction\n starState->rhostarL = setup->rhoL * PetscPowReal(pratio, 1. / setup->gamma);\n starState->astarL = aL * PetscPowReal(pratio, 0.5 * starState->gamm1 / setup->gamma);\n starState->SHL = setup->uL - aL;\n starState->STL = starState->ustar - starState->astarL;\n }else { // #shock\n starState->rhostarL = setup->rhoL * (pratio + starState->gamm1 / starState->gamp1) / (starState->gamm1 * pratio / starState->gamp1 + 1.);\n starState->SL = setup->uL - aL * PetscSqrtReal(0.5 * starState->gamp1 / setup->gamma * pratio + 0.5 * starState->gamm1 / setup->gamma);\n }\n\n // right star state\n pratio = starState->pstar/setup->pR;\n if (starState->pstar<=setup->pR) { // # rarefaction\n starState->rhostarR = setup->rhoR * PetscPowReal(pratio, 1. / setup->gamma);\n starState->astarR = aR * PetscPowReal(pratio, 0.5 * starState->gamm1 / setup->gamma);\n starState-> SHR = setup->uR + aR;\n starState->STR = starState->ustar + starState->astarR;\n }else { // shock\n starState->rhostarR = setup->rhoR * (pratio + starState->gamm1 / starState->gamp1) / (starState->gamm1 * pratio / starState->gamp1 + 1.);\n starState->SR = setup->uR + aR * PetscSqrtReal(0.5 * starState->gamp1 / setup->gamma * pratio + 0.5 * starState->gamm1 / setup->gamma);\n }\n return 0;\n}\n\nvoid SetExactSolutionAtPoint(PetscInt dim, PetscReal xDt, const InitialConditions* setup, const StarState* starState, EulerNode* uu){\n PetscReal p;\n // compute the speed of sound\n PetscReal aL = PetscSqrtReal(setup->gamma*setup->pL/setup->rhoL);\n PetscReal aR = PetscSqrtReal(setup->gamma*setup->pR/setup->rhoR);\n\n for(PetscInt i =0; i < dim; i++){\n uu->rhoU[i] = 0.0;\n }\n\n if (xDt <= starState->ustar) { //# left of contact surface\n if (starState->pstar <= setup->pL) { // # rarefaction\n if (xDt <= starState->SHL) {\n uu->rho = setup->rhoL;\n p = setup->pL;\n uu->rhoU[0] = setup->uL*uu->rho;\n }else if (xDt <=starState->STL) { //#SHL < x / t < STL\n PetscReal tmp = 2. / starState->gamp1 + (starState->gamm1 / starState->gamp1 / aL) * (setup->uL - xDt);\n uu->rho = setup->rhoL * pow(tmp, 2. / starState->gamm1);\n uu->rhoU[0] = uu->rho * (2. / starState->gamp1) * (aL + 0.5 * starState->gamm1 * setup->uL + xDt);\n p = setup->pL * pow(tmp, 2. * setup->gamma / starState->gamm1);\n }else { //# STL < x/t < u*\n uu->rho = starState->rhostarL;\n p = starState->pstar;\n uu->rhoU[0] = uu->rho * starState->ustar;\n }\n }else{ //# shock\n if (xDt<= starState->SL) { // # xDt < SL\n uu->rho = setup->rhoL;\n p = setup->pL;\n uu->rhoU[0] = uu->rho * setup->uL;\n }else { //# SL < xDt < ustar\n uu->rho = starState->rhostarL;\n p = starState->pstar;\n uu->rhoU[0] = uu->rho * starState->ustar;\n }\n }\n }else{//# right of contact surface\n if (starState->pstar<=setup->pR) { //# rarefaction\n if (xDt>= starState->SHR) {\n uu->rho = setup->rhoR;\n p = setup->pR;\n uu->rhoU[0] = uu->rho * setup->uR;\n }else if (xDt >= starState->STR) { // # SHR < x/t < SHR\n PetscReal tmp = 2./starState->gamp1 - (starState->gamm1/starState->gamp1/aR)*(setup->uR-xDt);\n uu->rho = setup->rhoR*PetscPowReal(tmp,2./starState->gamm1);\n uu->rhoU[0] = uu->rho * (2./starState->gamp1)*(-aR + 0.5*starState->gamm1*setup->uR+xDt);\n p = setup->pR*PetscPowReal(tmp,2.*setup->gamma/starState->gamm1);\n }else{ //# u* < x/t < STR\n uu->rho = starState->rhostarR;\n p = starState->pstar;\n uu->rhoU[0] = uu->rho * starState->ustar;\n }\n }else {//# shock\n if (xDt>= starState->SR) { // # xDt > SR\n uu->rho = setup->rhoR;\n p = setup->pR;\n uu->rhoU[0] = uu->rho * setup->uR;\n }else {//#ustar < xDt < SR\n uu->rho = starState->rhostarR;\n p = starState->pstar;\n uu->rhoU[0] = uu->rho * starState->ustar;\n }\n }\n }\n PetscReal e = p/starState->gamm1/uu->rho;\n PetscReal E = e + 0.5*(uu->rhoU[0]/uu->rho)*(uu->rhoU[0]/uu->rho);\n uu->rhoE = uu->rho*E;\n}\n\n\nstatic PetscErrorCode SetExactSolutionRho(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx){\n ProblemSetup* prob = (ProblemSetup*)ctx;\n\n PetscReal xDt = (x[0]-prob->initialConditions.length/2)/time;\n EulerNode uu;\n SetExactSolutionAtPoint(dim, xDt, &prob->initialConditions, &prob->starState, &uu);\n\n u[0] = uu.rho;\n return 0;\n}\n\nstatic PetscErrorCode SetExactSolutionRhoU(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx){\n ProblemSetup* prob = (ProblemSetup*)ctx;\n\n PetscReal xDt = (x[0]-prob->initialConditions.length/2)/time;\n EulerNode uu;\n SetExactSolutionAtPoint(dim, xDt, &prob->initialConditions, &prob->starState, &uu);\n u[0] = uu.rhoU[0];\n u[1] = uu.rhoU[1];\n return 0;\n}\n\nstatic PetscErrorCode SetExactSolutionRhoE(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx){\n ProblemSetup* prob = (ProblemSetup*)ctx;\n\n PetscReal xDt = (x[0]-prob->initialConditions.length/2)/time;\n EulerNode uu;\n SetExactSolutionAtPoint(dim, xDt, &prob->initialConditions, &prob->starState, &uu);\n u[0] = uu.rhoE;\n return 0;\n}\n\nstatic PetscErrorCode PrintVector(DM dm, Vec v, PetscInt step, const char * fileName){\n Vec cellgeom;\n PetscErrorCode ierr = DMPlexGetGeometryFVM(dm, NULL, &cellgeom, NULL);CHKERRQ(ierr);\n PetscInt cStart, cEnd;\n ierr = DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);\n DM dmCell;\n ierr = VecGetDM(cellgeom, &dmCell);CHKERRQ(ierr);\n const PetscScalar *cgeom;\n ierr = VecGetArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);\n const PetscScalar *x;\n ierr = VecGetArrayRead(v, &x);CHKERRQ(ierr);\n // print the header for each file\n char filename[100];\n ierr = PetscSNPrintf(filename,sizeof(filename),\"%s.%d.txt\",fileName, step);CHKERRQ(ierr);\n\n PetscInt rank = 0;\n PetscInt size;\n ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank);CHKERRMPI(ierr);\n ierr = MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size);CHKERRMPI(ierr);\n\n for(PetscInt r =0; r < size; r++ ) {\n if(r == rank) {\n FILE *fptr;\n if(r == 0){\n fptr = fopen(filename, \"w\");\n fprintf(fptr, \"x rho u e rhou rhoe\\n\");\n }else{\n fptr = fopen(filename, \"a\");\n }\n for (PetscInt c = cStart; c < cEnd; ++c) {\n PetscFVCellGeom *cg;\n const EulerNode *xc;\n\n ierr = DMPlexPointLocalRead(dmCell, c, cgeom, &cg);\n CHKERRQ(ierr);\n ierr = DMPlexPointGlobalFieldRead(dm, c, 0, x, &xc);\n CHKERRQ(ierr);\n if(xc) {// must be real cell and not ghost\n PetscReal u0 = xc->rhoU[0] / xc->rho;\n fprintf(fptr, \"%f %f %f %f %f %f\\n\", cg->centroid[0], xc->rho, u0, (xc->rhoE / xc->rho) - 0.5 * u0 * u0, xc->rhoU[0], xc->rhoE);\n }\n }\n\n fclose(fptr);\n }\n MPI_Barrier(PetscObjectComm((PetscObject)dm));\n }\n ierr = VecRestoreArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(v, &x);CHKERRQ(ierr);\n return 0;\n}\n\nstatic PetscErrorCode MonitorError(TS ts, PetscInt step, PetscReal time, Vec u, void *ctx) {\n PetscFunctionBeginUser;\n PetscErrorCode ierr;\n\n // Get the DM\n DM dm;\n ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);\n\n // Create a copy of the u vector\n Vec e;\n ierr = DMCreateGlobalVector(dm, &e);CHKERRQ(ierr);\n ierr = PetscObjectSetName((PetscObject)e, \"exact\");CHKERRQ(ierr);\n\n // Set the values\n PetscErrorCode (*func[3]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {SetExactSolutionRho, SetExactSolutionRhoU, SetExactSolutionRhoE};\n void* ctxs[3] ={ctx, ctx, ctx};\n ierr = DMProjectFunction(dm,time,func,ctxs,INSERT_ALL_VALUES,e);CHKERRQ(ierr);\n\n // just print to a file for now\n ierr = PrintVector(dm, e, step, \"exact\");CHKERRQ(ierr);\n ierr = PrintVector(dm, u, step, \"solution\");CHKERRQ(ierr);\n\n PetscPrintf(PETSC_COMM_WORLD, \"TS %d: %f\\n\", step, time);\n\n DMRestoreGlobalVector(dm, &e);\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PhysicsBoundary_Euler_Mirror(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx)\n{\n const EulerNode *xI = (const EulerNode*)a_xI;\n EulerNode *xG = (EulerNode*)a_xG;\n ProblemSetup* prob = (ProblemSetup*)ctx;\n PetscFunctionBeginUser;\n xG->rho = xI->rho;\n xG->rhoE = xI->rhoE;\n xG->rhoU[0] = xI->rhoU[0];\n xG->rhoU[1] = xI->rhoU[1];\n\n PetscFunctionReturn(0);\n}\n\n/* PetscReal* => EulerNode* conversion */\nstatic PetscErrorCode PhysicsBoundary_Euler_Left(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx)\n{\n const EulerNode *xI = (const EulerNode*)a_xI;\n EulerNode *xG = (EulerNode*)a_xG;\n ProblemSetup* prob = (ProblemSetup*)ctx;\n PetscFunctionBeginUser;\n xG->rho = prob->initialConditions.rhoL;\n PetscReal eT = prob->initialConditions.rhoL*((prob->initialConditions.pL /(prob->initialConditions.gamma -1) / prob->initialConditions.rhoL) + 0.5 * prob->initialConditions.uL * prob->initialConditions.uL);\n xG->rhoE = eT;\n xG->rhoU[0] = prob->initialConditions.rhoL * prob->initialConditions.uL;\n xG->rhoU[1] = 0.0;\n\n PetscFunctionReturn(0);\n}\n\n/* PetscReal* => EulerNode* conversion */\nstatic PetscErrorCode PhysicsBoundary_Euler_Right(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx)\n{\n const EulerNode *xI = (const EulerNode*)a_xI;\n EulerNode *xG = (EulerNode*)a_xG;\n ProblemSetup* prob = (ProblemSetup*)ctx;\n PetscFunctionBeginUser;\n xG->rho = prob->initialConditions.rhoR;\n PetscReal eT = prob->initialConditions.rhoR*((prob->initialConditions.pR /(prob->initialConditions.gamma -1)/ prob->initialConditions.rhoR) + 0.5 * prob->initialConditions.uR * prob->initialConditions.uR);\n xG->rhoE = eT;\n xG->rhoU[0] = prob->initialConditions.rhoR * prob->initialConditions.uR;\n xG->rhoU[1] = 0.0;\n\n PetscFunctionReturn(0);\n}\n\nint main(int argc, char **argv)\n{\n PetscErrorCode ierr;\n // create the mesh\n // setup the ts\n DM dm; /* problem definition */\n TS ts; /* timestepper */\n\n // initialize petsc and mpi\n PetscInitialize(&argc, &argv, NULL, \"HELP\");\n\n // Create a ts\n ierr = TSCreate(PETSC_COMM_WORLD, &ts);CHKERRQ(ierr);\n ierr = TSSetProblemType(ts, TS_NONLINEAR);CHKERRQ(ierr);\n ierr = TSSetType(ts, TSEULER);CHKERRQ(ierr);\n ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);CHKERRQ(ierr);\n\n // Create a mesh\n // hard code the problem setup\n PetscReal start[] = {0.0, 0.0};\n PetscReal end[] = {1.0, 1};\n PetscInt nx[] = {100, 1};\n DMBoundaryType bcType[] = {DM_BOUNDARY_NONE, DM_BOUNDARY_NONE};\n ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, DIM, PETSC_FALSE, nx, start, end, bcType, PETSC_TRUE, &dm);CHKERRQ(ierr);\n\n// Setup the problem\n ProblemSetup problem;\n\n // case 1 - Sod problem\n problem.initialConditions.rhoL=1.0;\n problem.initialConditions.uL=0.0;\n problem.initialConditions.pL=1.0;\n problem.initialConditions.rhoR=0.125;\n problem.initialConditions.uR=0.0;\n problem.initialConditions.pR=0.1;\n problem.initialConditions.maxTime = 0.25;\n problem.initialConditions.length = 1;\n problem.initialConditions.gamma = 1.4;\n\n // case 2\n// problem.initialConditions.rhoL=1.0;\n// problem.initialConditions.uL=-2.0;\n// problem.initialConditions.pL=0.4;\n// problem.initialConditions.rhoR=1.0;\n// problem.initialConditions.uR=2.0;\n// problem.initialConditions.pR=0.4;\n// problem.initialConditions.maxTime = 0.15;\n// problem.initialConditions.length = 1;\n// problem.initialConditions.gamma = 1.4;\n\n // case 5\n// problem.initialConditions.rhoL=5.99924;\n// problem.initialConditions.uL=19.5975;\n// problem.initialConditions.pL=460.894;\n// problem.initialConditions.rhoR=5.99242;\n// problem.initialConditions.uR=-6.19633;\n// problem.initialConditions.pR=46.0950;\n// problem.initialConditions.maxTime = 0.035;\n// problem.initialConditions.length = 1;\n// problem.initialConditions.gamma = 1.4;\n\n // Compute the star state\n ierr = DetermineStarState(&problem.initialConditions, &problem.starState);CHKERRQ(ierr);\n\n // Setup the flow data\n FlowData flowData; /* store some of the flow data*/\n ierr = FlowCreate(&flowData);CHKERRQ(ierr);\n\n //Setup\n CompressibleFlow_SetupDiscretization(flowData, dm);\n\n // Add in the flow parameters\n PetscScalar params[TOTAL_COMPRESSIBLE_FLOW_PARAMETERS];\n params[CFL] = 0.5;\n params[GAMMA] = problem.initialConditions.gamma;\n\n // set up the finite volume fluxes\n CompressibleFlow_StartProblemSetup(flowData, TOTAL_COMPRESSIBLE_FLOW_PARAMETERS, params);\n DMView(flowData->dm, PETSC_VIEWER_STDERR_SELF);\n // Add in any boundary conditions\n PetscDS prob;\n ierr = DMGetDS(flowData->dm, &prob);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n const PetscInt idsLeft[]= {4};\n ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, \"wall left\", \"Face Sets\", 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Euler_Left, NULL, 1, idsLeft, &problem);CHKERRQ(ierr);\n const PetscInt idsRight[]= {2};\n ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, \"wall right\", \"Face Sets\", 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Euler_Right, NULL, 1, idsRight, &problem);CHKERRQ(ierr);\n const PetscInt mirror[]= {1, 3};\n ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, \"mirrorWall\", \"Face Sets\", 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Euler_Mirror, NULL, 2, mirror, &problem);CHKERRQ(ierr);\n\n // Complete the problem setup\n ierr = CompressibleFlow_CompleteProblemSetup(flowData, ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Name the flow field\n ierr = PetscObjectSetName(((PetscObject)flowData->flowField), \"Numerical Solution\");\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Setup the TS\n ierr = TSSetFromOptions(ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = TSMonitorSet(ts, MonitorError, &problem, NULL);CHKERRQ(ierr);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = TSSetMaxTime(ts,problem.initialConditions.maxTime);CHKERRQ(ierr);\n\n // set the initial conditions\n PetscErrorCode (*func[3]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {SetExactSolutionRho, SetExactSolutionRhoU, SetExactSolutionRhoE};\n void* ctxs[3] ={&problem, &problem, &problem};\n ierr = DMProjectFunction(flowData->dm,0.0,func,ctxs,INSERT_ALL_VALUES,flowData->flowField);CHKERRQ(ierr);\n\n ierr = TSSolve(ts,flowData->flowField);CHKERRQ(ierr);\n\n return PetscFinalize();\n\n}", "meta": {"hexsha": "2208cb87c95ebbff3a409a626aba7054732cb0c9", "size": 20305, "ext": "c", "lang": "C", "max_stars_repo_path": "eulerFlow.c", "max_stars_repo_name": "mmcgurn/MattFlowCases", "max_stars_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eulerFlow.c", "max_issues_repo_name": "mmcgurn/MattFlowCases", "max_issues_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eulerFlow.c", "max_forks_repo_name": "mmcgurn/MattFlowCases", "max_forks_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3543788187, "max_line_length": 210, "alphanum_fraction": 0.6262004432, "num_tokens": 6261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5918258570891253}} {"text": "#pragma once\n\n#include \n#include \n\n#include \"../utils/Concepts.h\"\n#include \"General.h\"\n#include \"Random.h\"\n\nnamespace math {\n\tusing gsl::narrow_cast;\n\tusing utils::concepts::SignedNumeric, utils::concepts::Integral,\n\t\tutils::concepts::SignedIntegral, utils::concepts::FloatingPoint;\n\n\tenum class Vec2Idx : size_t\n\t{\n\t\tX = 0ULL,\n\t\tY\n\t};\n\n\ttemplate\n\tclass Vec2 {\n\t public:\n\t\t/// @brief Creates a default `Vec2`\n\t\tconstexpr Vec2() noexcept = default;\n\n\t\t/// @brief Creates a new `Vec2` with the given x and y components\n\t\t///\n\t\t/// @param x - The x component\n\t\t/// @param y - The y component\n\t\tconstexpr Vec2(T x, T y) noexcept : elements{x, y} {\n\t\t}\n\t\tconstexpr Vec2(const Vec2& vec) noexcept = default;\n\t\tconstexpr Vec2(Vec2&& vec) noexcept = default;\n\t\tconstexpr ~Vec2() noexcept = default;\n\n\t\t/// @brief Returns the x component\n\t\t///\n\t\t/// @return a const ref to the x component\n\t\t[[nodiscard]] inline constexpr auto x() const noexcept -> const T& {\n\t\t\treturn elements[X];\n\t\t}\n\n\t\t/// @brief Returns the x component\n\t\t///\n\t\t/// @return a mutable (ie: non-const) ref to the x component\n\t\tinline constexpr auto x() noexcept -> T& {\n\t\t\treturn elements[X];\n\t\t}\n\n\t\t/// @brief Returns the y component\n\t\t///\n\t\t/// @return a const ref to the y component\n\t\t[[nodiscard]] inline constexpr auto y() const noexcept -> const T& {\n\t\t\treturn elements[Y];\n\t\t}\n\n\t\t/// @brief Returns the y component\n\t\t///\n\t\t/// @return a mutable (ie: non-const) ref to the y component\n\t\tinline constexpr auto y() noexcept -> T& {\n\t\t\treturn elements[Y];\n\t\t}\n\n\t\t/// @brief Returns the magnitude (length) of the vector\n\t\t///\n\t\t/// @return The magnitude\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto magnitude() const noexcept -> TT {\n\t\t\treturn General::sqrt(narrow_cast(magnitude_squared()));\n\t\t}\n\n\t\t/// @brief Returns the dot product of this and `vec`\n\t\t///\n\t\t/// @param vec - The vector to perform the dot product with\n\t\t///\n\t\t/// @return The dot product\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto dot_prod(const Vec2& vec) const noexcept -> TT {\n\t\t\treturn narrow_cast(x()) * vec.x() + narrow_cast(y()) * vec.y();\n\t\t}\n\n\t\t/// @brief Returns the dot product of this and `vec`\n\t\t///\n\t\t/// @param vec - The vector to perform the dot product with\n\t\t///\n\t\t/// @return The dot product\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto dot_prod(const Vec2& vec) const noexcept -> T {\n\t\t\treturn x() * narrow_cast(vec.x()) + y() * narrow_cast(vec.y());\n\t\t}\n\n\t\t/// @brief Performs the 2D equivalent to the cross product\n\t\t/// @note This is equivalent to the z component of a 3D cross product\n\t\t///\n\t\t/// @param vec The vector to perform the cross product with\n\t\t///\n\t\t/// @return The 2D cross product\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto cross_prod(const Vec2& vec) const noexcept -> TT {\n\t\t\treturn narrow_cast(x()) * vec.y() - narrow_cast(y()) * vec.x();\n\t\t}\n\n\t\t/// @brief Performs the 2D equivalent to the cross product\n\t\t/// @note This is equivalent to the z component of a 3D cross product\n\t\t///\n\t\t/// @param vec The vector to perform the cross product with\n\t\t///\n\t\t/// @return The 2D cross product\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto cross_prod(const Vec2& vec) const noexcept -> T {\n\t\t\treturn x() * narrow_cast(vec.y()) - y() * narrow_cast(vec.x());\n\t\t}\n\n\t\t/// @brief Returns **a** vector normal to this one\n\t\t/// @note this is not necessarily the **only** vector normal to this one\n\t\t///\n\t\t/// @return a vector normal to this\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto normal() const noexcept -> Vec2 {\n\t\t\tconstexpr auto _x = narrow_cast(1.0);\n\t\t\tconst auto _y = (-_x * narrow_cast(x())) / narrow_cast(y());\n\t\t\treturn {_x, _y};\n\t\t}\n\n\t\t/// @brief Returns this vector with normalized magnitude\n\t\t///\n\t\t/// @return this vector, normalized\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto normalized() const noexcept -> Vec2 {\n\t\t\treturn std::move(*this / magnitude());\n\t\t}\n\n\t\ttemplate\n\t\t[[nodiscard]] inline static constexpr auto random() noexcept -> Vec2 {\n\t\t\treturn {random_value(), random_value()};\n\t\t}\n\n\t\ttemplate\n\t\t[[nodiscard]] inline static constexpr auto random(TT min, TT max) noexcept -> Vec2 {\n\t\t\treturn {random_value(min, max), random_value(min, max)};\n\t\t}\n\n\t\ttemplate\n\t\t[[nodiscard]] inline static constexpr auto random_in_unit_circle() noexcept -> Vec2 {\n\t\t\tdo {\n\t\t\t\tauto val = random(narrow_cast(-1), narrow_cast(1));\n\t\t\t\tif(val.magnitude_squared() < narrow_cast(1)) {\n\t\t\t\t\treturn val;\n\t\t\t\t}\n\t\t\t} while(true);\n\t\t}\n\n\t\tconstexpr auto operator=(const Vec2& vec) noexcept -> Vec2& = default;\n\t\tconstexpr auto operator=(Vec2&& vec) noexcept -> Vec2& = default;\n\n\t\ttemplate\n\t\tinline constexpr auto operator==(const Vec2& vec) const noexcept -> bool {\n\t\t\tconst auto xEqual\n\t\t\t\t= General::abs(narrow_cast(x()) - vec.x()) < narrow_cast(0.01);\n\t\t\tconst auto yEqual\n\t\t\t\t= General::abs(narrow_cast(y()) - vec.y()) < narrow_cast(0.01);\n\t\t\treturn xEqual && yEqual;\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator==(const Vec2& vec) const noexcept -> bool {\n\t\t\tif constexpr(FloatingPoint) {\n\t\t\t\tconst auto xEqual\n\t\t\t\t\t= General::abs(x() - narrow_cast(vec.x())) < narrow_cast(0.01);\n\t\t\t\tconst auto yEqual\n\t\t\t\t\t= General::abs(y() - narrow_cast(vec.y())) < narrow_cast(0.01);\n\t\t\t\treturn xEqual && yEqual;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn x() == narrow_cast(vec.x()) && y() == narrow_cast(vec.y());\n\t\t\t}\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator!=(const Vec2& vec) const noexcept -> bool {\n\t\t\treturn !(*this == vec);\n\t\t}\n\n\t\tinline constexpr auto operator-() const noexcept -> Vec2 {\n\t\t\treturn {-x(), -y()};\n\t\t}\n\n\t\tinline constexpr auto operator[](Vec2Idx i) const noexcept -> T {\n\t\t\tconst auto index = static_cast(i);\n\t\t\treturn elements[index]; // NOLINT\n\t\t}\n\t\tinline constexpr auto operator[](Vec2Idx i) noexcept -> T& {\n\t\t\tconst auto index = static_cast(i);\n\t\t\treturn elements[index]; // NOLINT\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator+(const Vec2& vec) const noexcept -> Vec2 {\n\t\t\treturn {narrow_cast(x()) + vec.x(), narrow_cast(y()) + vec.y()};\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator+(const Vec2& vec) const noexcept -> Vec2 {\n\t\t\treturn {x() + narrow_cast(vec.x()), y() + narrow_cast(vec.y())};\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator+=(const Vec2& vec) noexcept -> Vec2& {\n\t\t\tx() += narrow_cast(vec.x());\n\t\t\ty() += narrow_cast(vec.y());\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator-(const Vec2& vec) const noexcept -> Vec2 {\n\t\t\treturn {narrow_cast(x()) - vec.x(), narrow_cast(y()) - vec.y()};\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator-(const Vec2& vec) const noexcept -> Vec2 {\n\t\t\treturn {x() - narrow_cast(vec.x()), y() - narrow_cast(vec.y())};\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator-=(const Vec2& vec) noexcept -> Vec2& {\n\t\t\tx() -= narrow_cast(vec.x());\n\t\t\ty() -= narrow_cast(vec.y());\n\t\t\treturn *this;\n\t\t}\n\n\t\tinline constexpr auto operator*(FloatingPoint auto s) const noexcept -> Vec2 {\n\t\t\tusing TT = decltype(s);\n\t\t\treturn {narrow_cast(x()) * s, narrow_cast(y()) * s};\n\t\t}\n\n\t\tinline constexpr auto operator*(SignedIntegral auto s) const noexcept -> Vec2 {\n\t\t\tauto scalar = narrow_cast(s);\n\t\t\treturn {x() * scalar, y() * scalar};\n\t\t}\n\n\t\tinline constexpr auto operator*=(FloatingPoint auto s) noexcept -> Vec2& {\n\t\t\tusing TT = decltype(s);\n\t\t\tx() = narrow_cast(narrow_cast(x()) * s);\n\t\t\ty() = narrow_cast(narrow_cast(y()) * s);\n\t\t\treturn *this;\n\t\t}\n\n\t\tinline constexpr auto operator*=(SignedIntegral auto s) noexcept -> Vec2& {\n\t\t\tauto scalar = narrow_cast(s);\n\t\t\tx() *= scalar;\n\t\t\ty() *= scalar;\n\t\t\treturn *this;\n\t\t}\n\n\t\tfriend inline constexpr auto\n\t\toperator*(FloatingPoint auto lhs, const Vec2& rhs) noexcept -> Vec2 {\n\t\t\treturn rhs * lhs;\n\t\t}\n\n\t\tfriend inline constexpr auto\n\t\toperator*(SignedIntegral auto lhs, const Vec2& rhs) noexcept -> Vec2 {\n\t\t\treturn rhs * lhs;\n\t\t}\n\n\t\tinline constexpr auto operator/(FloatingPoint auto s) const noexcept -> Vec2 {\n\t\t\tusing TT = decltype(s);\n\t\t\treturn {narrow_cast(x()) / s, narrow_cast(y()) / s};\n\t\t}\n\n\t\tinline constexpr auto operator/(SignedIntegral auto s) const noexcept -> Vec2 {\n\t\t\tauto scalar = narrow_cast(s);\n\t\t\treturn {x() / scalar, y() / scalar};\n\t\t}\n\n\t\tfriend inline constexpr auto\n\t\toperator/(FloatingPoint auto lhs, const Vec2& rhs) noexcept -> Vec2 {\n\t\t\treturn rhs / lhs;\n\t\t}\n\n\t\tfriend inline constexpr auto\n\t\toperator/(SignedIntegral auto lhs, const Vec2& rhs) noexcept -> Vec2 {\n\t\t\treturn rhs / lhs;\n\t\t}\n\n\t\tinline constexpr auto operator/=(FloatingPoint auto s) noexcept -> Vec2 {\n\t\t\tusing TT = decltype(s);\n\t\t\tx() = narrow_cast(narrow_cast(x()) / s);\n\t\t\ty() = narrow_cast(narrow_cast(y()) / s);\n\t\t\treturn *this;\n\t\t}\n\n\t\tinline constexpr auto operator/=(SignedIntegral auto s) noexcept -> Vec2 {\n\t\t\tauto scalar = narrow_cast(s);\n\t\t\tx() /= scalar;\n\t\t\ty() /= scalar;\n\t\t\treturn *this;\n\t\t}\n\n\t\tfriend inline constexpr auto\n\t\toperator<<(std::ostream& out, const Vec2& vec) noexcept -> std::ostream& {\n\t\t\treturn out << vec.x() << ' ' << vec.y();\n\t\t}\n\n\t private:\n\t\tstatic constexpr size_t NUM_ELEMENTS = static_cast(Vec2Idx::Y) + 1;\n\t\tT elements[NUM_ELEMENTS] = {narrow_cast(0), narrow_cast(0)}; // NOLINT\n\n\t\t/// @brief Calculates the magnitude squared of this vector\n\t\t///\n\t\t/// @return The magnitude squared\n\t\t[[nodiscard]] inline constexpr auto magnitude_squared() const noexcept -> T {\n\t\t\treturn x() * x() + y() * y();\n\t\t}\n\n\t\t/// Index for x component\n\t\tstatic constexpr size_t X = static_cast(Vec2Idx::X);\n\t\t/// Index for y component\n\t\tstatic constexpr size_t Y = static_cast(Vec2Idx::Y);\n\t};\n\n\ttemplate\n\texplicit Vec2(T, T) -> Vec2;\n\n\ttemplate\n\texplicit Vec2(T, T) -> Vec2;\n} // namespace math\n", "meta": {"hexsha": "9adccd77bd5a94e542677ed4966856172bf60fcd", "size": 10495, "ext": "h", "lang": "C", "max_stars_repo_path": "src/math/Vec2.h", "max_stars_repo_name": "braxtons12/ray_tracer", "max_stars_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "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/math/Vec2.h", "max_issues_repo_name": "braxtons12/ray_tracer", "max_issues_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "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/math/Vec2.h", "max_forks_repo_name": "braxtons12/ray_tracer", "max_forks_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "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.9969512195, "max_line_length": 93, "alphanum_fraction": 0.6488804192, "num_tokens": 2982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5917672830807923}} {"text": "#include \n#include \n#include \"compressibleFlow.h\"\n#include \"mesh.h\"\n#include \"petscdmplex.h\"\n#include \"petscts.h\"\n\ntypedef struct {\n PetscInt dim;\n PetscReal rc;\n PetscReal xc;\n PetscReal yc;\n PetscReal L;\n PetscReal Tinf;\n PetscReal rhoInf;\n PetscReal Mac;\n PetscReal MaxInf;\n PetscReal MayInf;\n PetscReal Rgas;\n PetscReal gamma;\n} Constants;\n\ntypedef struct {\n Constants constants;\n FlowData flowData;\n} ProblemSetup;\n\nstatic PetscLogStage monitorStage;\n\n\nstatic PetscErrorCode EulerExact(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *node, void *ctx) {\n PetscFunctionBeginUser;\n\n Constants *constants = (Constants *)ctx;\n\n // define the speed of sound and other variables in the infinity\n PetscReal aInf = PetscSqrtReal(constants->gamma*constants->Rgas*constants->Tinf);\n PetscReal pInf = constants->rhoInf*constants->Rgas*constants->Tinf;\n PetscReal uInf = constants->MaxInf*aInf;\n PetscReal vInf = constants->MayInf*aInf;\n\n // compute the values for the vortex\n PetscReal Tvort = constants->Tinf/(1.0 + 0.5*(constants->gamma - 1.0)*constants->Mac*constants->Mac);\n PetscReal aVort = PetscSqrtReal(constants->gamma*constants->Rgas*Tvort);\n\n // compute the values at each location based upon the time and the var field velocity\n PetscReal distTraveledX = time*uInf;\n PetscReal distTraveledY = time*vInf;\n // compute the updated center\n PetscReal xc = constants->xc + distTraveledX;\n PetscReal yc = constants->yc + distTraveledY;\n\n while(xc > constants->L*2){\n xc -= constants->L*2;\n }\n while(yc > constants->L){\n yc -= constants->L;\n }\n\n PetscReal x = xyz[0];\n PetscReal y = xyz[1];\n\n PetscReal xStar = (x- xc)/constants->rc;\n PetscReal yStar = (y - yc)/constants->rc;\n PetscReal rStar = PetscSqrtReal(PetscSqr((x - xc))+ PetscSqr((y - yc)))/constants->rc;\n\n PetscReal u = uInf - constants->Mac*aVort*yStar* PetscExpReal(0.5*(1.0 - PetscSqr(rStar)));\n PetscReal v = vInf + constants->Mac*aVort*xStar* PetscExpReal(0.5*(1.0 - PetscSqr(rStar)));\n PetscReal machTerm = 0.5*(constants->gamma-1.0)*PetscSqr(constants->Mac);\n PetscReal T = constants->Tinf*(1.0 - machTerm/(1+machTerm)*PetscSqr(rStar)*PetscExpReal(1-PetscSqr(rStar)) );\n PetscReal p = pInf* PetscPowReal(T/constants->Tinf, constants->gamma/(constants->gamma - 1.0));\n PetscReal rho = p/constants->Rgas/T;\n PetscReal e = p/((constants->gamma - 1.0)*rho);\n PetscReal eT = e + 0.5*(u*u + v*v);\n\n // Store the values\n node[RHO] = rho;\n node[RHOE] = rho*eT;\n node[RHOU + 0] = rho*u;\n node[RHOU + 1] = rho*v;\n\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode MonitorError(TS ts, PetscInt step, PetscReal time, Vec u, void *ctx) {\n PetscFunctionBeginUser;\n PetscErrorCode ierr;\n PetscLogStagePush(monitorStage);\n\n PetscInt interval = 1;\n if(step % interval == 0) {\n // Get the DM\n DM dm;\n ierr = TSGetDM(ts, &dm);\n CHKERRQ(ierr);\n\n ierr = VecViewFromOptions(u, NULL, \"-sol_view\");\n CHKERRQ(ierr);\n\n // Open a vtk viewer\n // PetscViewer viewer;\n // char filename[PETSC_MAX_PATH_LEN];\n // ierr = PetscSNPrintf(filename,sizeof(filename),\"/Users/mcgurn/chrestScratch/results/vortex/flow%.4D.vtu\",step);CHKERRQ(ierr);\n // ierr = PetscViewerVTKOpen(PetscObjectComm((PetscObject)dm),filename,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr);\n // ierr = VecView(u,viewer);CHKERRQ(ierr);\n // ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);\n\n ierr = PetscPrintf(PetscObjectComm((PetscObject)dm), \"TS at %f\\n\", time);\n CHKERRQ(ierr);\n\n // Compute the error\n void *exactCtxs[1];\n PetscErrorCode (*exactFuncs[1])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx);\n PetscDS ds;\n ierr = DMGetDS(dm, &ds);\n CHKERRQ(ierr);\n\n // Get the exact solution\n ierr = PetscDSGetExactSolution(ds, 0, &exactFuncs[0], &exactCtxs[0]);\n CHKERRQ(ierr);\n\n // Create an vector to hold the exact solution\n Vec exactVec;\n ierr = VecDuplicate(u, &exactVec);\n CHKERRQ(ierr);\n ierr = DMProjectFunction(dm, time, exactFuncs, exactCtxs, INSERT_ALL_VALUES, exactVec);\n CHKERRQ(ierr);\n\n ierr = PetscObjectSetName((PetscObject)exactVec, \"exact\");\n CHKERRQ(ierr);\n ierr = VecViewFromOptions(exactVec, NULL, \"-exact_view\");\n CHKERRQ(ierr);\n\n // For each component, compute the l2 norms\n ierr = VecAXPY(exactVec, -1.0, u);\n CHKERRQ(ierr);\n\n PetscReal ferrors[4];\n ierr = VecSetBlockSize(exactVec, 4);\n CHKERRQ(ierr);\n\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"Timestep: %04d time = %-8.4g \\t\\n\", (int)step, (double)time);\n CHKERRQ(ierr);\n ierr = VecStrideNormAll(exactVec, NORM_2, ferrors);\n CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"\\tL_2 Error: [%2.3g, %2.3g, %2.3g, %2.3g]\\n\", (double)(ferrors[0]), (double)(ferrors[1]), (double)(ferrors[2]), (double)(ferrors[3]));\n CHKERRQ(ierr);\n\n // And the infinity error\n ierr = VecStrideNormAll(exactVec, NORM_INFINITY, ferrors);\n CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"\\tL_Inf Error: [%2.3g, %2.3g, %2.3g, %2.3g]\\n\", (double)ferrors[0], (double)ferrors[1], (double)ferrors[2], (double)ferrors[3]);\n CHKERRQ(ierr);\n\n ierr = PetscObjectSetName((PetscObject)exactVec, \"error\");\n CHKERRQ(ierr);\n ierr = VecViewFromOptions(exactVec, NULL, \"-exact_view\");\n CHKERRQ(ierr);\n ierr = VecDestroy(&exactVec);\n CHKERRQ(ierr);\n }\n PetscLogStagePop();\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PhysicsBoundary_Euler(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx) {\n PetscFunctionBeginUser;\n Constants *constants = (Constants *)ctx;\n\n // Offset the calc assuming the cells are square\n PetscReal x[3];\n\n for(PetscInt i =0; i < constants->dim; i++){\n x[i] = c[i] + n[i]*0.5;\n }\n\n EulerExact(constants->dim, time, x, 0, a_xG, ctx);\n PetscFunctionReturn(0);\n}\n\nint main(int argc, char **argv)\n{\n // Setup the problem\n Constants constants;\n\n // sub sonic\n constants.dim = 2;\n constants.L = 1.0;\n constants.xc = constants.L/2.0;\n constants.yc = constants.L/2.0;\n constants.Tinf =298.0;\n constants.rhoInf = 1.0;\n constants.Rgas = 287.0;\n constants.gamma = 1.4;\n constants.rc = .1*constants.L;\n constants.gamma = 1.4;\n constants.Mac = 0.3;\n constants.MaxInf = 0.3;\n constants.MayInf = 0.0;\n\n PetscErrorCode ierr;\n // create the mesh\n // setup the ts\n DM dm; /* problem definition */\n TS ts; /* timestepper */\n\n // initialize petsc and mpi\n PetscInitialize(&argc, &argv, NULL, \"HELP\");\n\n // Create a ts\n ierr = TSCreate(PETSC_COMM_WORLD, &ts);CHKERRQ(ierr);\n ierr = TSSetProblemType(ts, TS_NONLINEAR);CHKERRQ(ierr);\n ierr = TSSetType(ts, TSRK);CHKERRQ(ierr);\n ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);CHKERRQ(ierr);\n\n PetscInt lengthFactor = 2;\n ierr = PetscOptionsGetInt(NULL, NULL, \"-lengthFactor\", &lengthFactor, NULL);CHKERRQ(ierr);\n PetscPrintf(PETSC_COMM_WORLD, \"LengthFactor %d\\n\", lengthFactor);\n\n // Create a mesh\n // hard code the problem setup\n PetscReal start[] = {0.0, 0.0};\n PetscReal end[] = {constants.L*lengthFactor, constants.L};\n PetscReal nxHeight = 10;\n PetscInt nx[] = {lengthFactor*nxHeight, nxHeight};\n ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, constants.dim, PETSC_FALSE, nx, start, end, NULL, PETSC_TRUE, &dm);CHKERRQ(ierr);\n\n // Setup the flow data\n FlowData flowData; /* store some of the flow data*/\n ierr = FlowCreate(&flowData);CHKERRQ(ierr);\n\n // Combine the flow data\n ProblemSetup problemSetup;\n problemSetup.flowData = flowData;\n problemSetup.constants = constants;\n\n //Setup\n CompressibleFlow_SetupDiscretization(flowData, &dm);\n\n // Add in the flow parameters\n PetscScalar params[TOTAL_COMPRESSIBLE_FLOW_PARAMETERS];\n params[CFL] = 0.5;\n params[GAMMA] = constants.gamma;\n\n // set up the finite volume fluxes\n CompressibleFlow_StartProblemSetup(flowData, TOTAL_COMPRESSIBLE_FLOW_PARAMETERS, params);\n DMView(flowData->dm, PETSC_VIEWER_STDOUT_WORLD);\n // Add in any boundary conditions\n PetscDS prob;\n ierr = DMGetDS(flowData->dm, &prob);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n const PetscInt idsLeft[]= {1, 2, 3, 4};\n ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, \"wall left\", \"Face Sets\", 0, 0, NULL, (void (*)(void))PhysicsBoundary_Euler, NULL, 4, idsLeft, &constants);CHKERRQ(ierr);\n\n // Complete the problem setup\n ierr = CompressibleFlow_CompleteProblemSetup(flowData, ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Name the flow field\n ierr = PetscObjectSetName(((PetscObject)flowData->flowField), \"Numerical Solution\");\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Setup the TS\n ierr = TSSetFromOptions(ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n// ierr = TSMonitorSet(ts, MonitorError, &constants, NULL);CHKERRQ(ierr);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // set the initial conditions\n PetscErrorCode (*func[2]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {EulerExact};\n void* ctxs[1] ={&constants};\n ierr = DMProjectFunction(flowData->dm,0.0,func,ctxs,INSERT_ALL_VALUES,flowData->flowField);CHKERRQ(ierr);\n\n // for the mms, add the exact solution\n ierr = PetscDSSetExactSolution(prob, 0, EulerExact, &constants);CHKERRQ(ierr);\n\n // Output the mesh\n ierr = DMViewFromOptions(flowData->dm, NULL, \"-dm_view\");CHKERRQ(ierr);\n\n // Compute the end time so it goes around once\n PetscReal aInf = PetscSqrtReal(constants.gamma*constants.Rgas*constants.Tinf);\n PetscReal u_x = constants.MaxInf*aInf;\n PetscReal endTime = constants.L/u_x;\n\n TSSetMaxTime(ts, endTime);\n TSSetMaxSteps(ts, 50);\n PetscDSView(prob, PETSC_VIEWER_STDOUT_WORLD);\n PetscLogStage solveStage;\n PetscLogStageRegister(\"TSSolve\",&solveStage);\n PetscLogStageRegister(\"Monitor\", &monitorStage);\n\n PetscLogStagePush(solveStage);\n ierr = TSSolve(ts,flowData->flowField);CHKERRQ(ierr);\n PetscLogStagePop();\n PetscPrintf(PETSC_COMM_WORLD, \"Done\");\n FlowDestroy(&flowData);\n TSDestroy(&ts);\n\n return PetscFinalize();\n\n}\n", "meta": {"hexsha": "62f7bcce60b97dc81dfebd579a3a9b4cb3d11780", "size": 10702, "ext": "c", "lang": "C", "max_stars_repo_path": "eulerIsentropicVortex.c", "max_stars_repo_name": "mmcgurn/MattFlowCases", "max_stars_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eulerIsentropicVortex.c", "max_issues_repo_name": "mmcgurn/MattFlowCases", "max_issues_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eulerIsentropicVortex.c", "max_forks_repo_name": "mmcgurn/MattFlowCases", "max_forks_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4370860927, "max_line_length": 180, "alphanum_fraction": 0.6586619323, "num_tokens": 3064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7217432062975978, "lm_q1q2_score": 0.5917524450842689}} {"text": "/* statistics/gsl_statistics_uint.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_STATISTICS_UINT_H__\n#define __GSL_STATISTICS_UINT_H__\n\n#include \n#include \n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nGSL_EXPORT double gsl_stats_uint_mean (const unsigned int data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_uint_variance (const unsigned int data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_uint_sd (const unsigned int data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_uint_variance_with_fixed_mean (const unsigned int data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_uint_sd_with_fixed_mean (const unsigned int data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_uint_absdev (const unsigned int data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_uint_skew (const unsigned int data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_uint_kurtosis (const unsigned int data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_uint_lag1_autocorrelation (const unsigned int data[], const size_t stride, const size_t n);\n\nGSL_EXPORT double gsl_stats_uint_covariance (const unsigned int data1[], const size_t stride1,const unsigned int data2[], const size_t stride2, const size_t n);\n\nGSL_EXPORT double gsl_stats_uint_variance_m (const unsigned int data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_uint_sd_m (const unsigned int data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_uint_absdev_m (const unsigned int data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_uint_skew_m_sd (const unsigned int data[], const size_t stride, const size_t n, const double mean, const double sd);\nGSL_EXPORT double gsl_stats_uint_kurtosis_m_sd (const unsigned int data[], const size_t stride, const size_t n, const double mean, const double sd);\nGSL_EXPORT double gsl_stats_uint_lag1_autocorrelation_m (const unsigned int data[], const size_t stride, const size_t n, const double mean);\n\nGSL_EXPORT double gsl_stats_uint_covariance_m (const unsigned int data1[], const size_t stride1,const unsigned int data2[], const size_t stride2, const size_t n, const double mean1, const double mean2);\n\n\nGSL_EXPORT double gsl_stats_uint_pvariance (const unsigned int data1[], const size_t stride1, const size_t n1, const unsigned int data2[], const size_t stride2, const size_t n2);\nGSL_EXPORT double gsl_stats_uint_ttest (const unsigned int data1[], const size_t stride1, const size_t n1, const unsigned int data2[], const size_t stride2, const size_t n2);\n\nGSL_EXPORT unsigned int gsl_stats_uint_max (const unsigned int data[], const size_t stride, const size_t n);\nGSL_EXPORT unsigned int gsl_stats_uint_min (const unsigned int data[], const size_t stride, const size_t n);\nGSL_EXPORT void gsl_stats_uint_minmax (unsigned int * min, unsigned int * max, const unsigned int data[], const size_t stride, const size_t n);\n\nGSL_EXPORT size_t gsl_stats_uint_max_index (const unsigned int data[], const size_t stride, const size_t n);\nGSL_EXPORT size_t gsl_stats_uint_min_index (const unsigned int data[], const size_t stride, const size_t n);\nGSL_EXPORT void gsl_stats_uint_minmax_index (size_t * min_index, size_t * max_index, const unsigned int data[], const size_t stride, const size_t n);\n\nGSL_EXPORT double gsl_stats_uint_median_from_sorted_data (const unsigned int sorted_data[], const size_t stride, const size_t n) ;\nGSL_EXPORT double gsl_stats_uint_quantile_from_sorted_data (const unsigned int sorted_data[], const size_t stride, const size_t n, const double f) ;\n\n__END_DECLS\n\n#endif /* __GSL_STATISTICS_UINT_H__ */\n", "meta": {"hexsha": "a5327bc33a95a90a837b9c58d6999b98abd7bb13", "size": 4806, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_statistics_uint.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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/core/gsl/include/gsl/gsl_statistics_uint.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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/core/gsl/include/gsl/gsl_statistics_uint.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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": 62.4155844156, "max_line_length": 202, "alphanum_fraction": 0.7960882231, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5914558331963243}} {"text": "/* convolvedexponential.c -- model functions for multiple exponentials + background, convolved with an instrument response */\n/////////////////////////////////////////////////////////////////////////////////\n// \n// Calculation of multiple exponentials convolved with an instrument response. \n// using GNU Scientific Library. Also, calls Levenberg-Marquardt minimization routine\n// for fitting event counting histograms. Options include using the Maximum Likelihood Estimator\n// for Poisson deviates and least squares fitting.\n//\n// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory. Written by Ted Laurence (laurence2@llnl.gov)\n// LLNL-CODE-424602 All rights reserved.\n// This file is part of dlevmar_mle_der\n//\n// Please also read Our Notice and GNU General Public License.\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation; either version 2 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License \n// along with this program; if not, write to the \n// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n//\n/////////////////////////////////////////////////////////////////////////////////\n \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"levmar_mle.h\"\n\n\nstruct data {\n\tdouble deltaT;\t/*Spacing between bins*/\n\tsize_t n;\t\t/*Number of data elements*/\n\tsize_t nRadix2; /*Next higher power of 2 for n, giving size of irf and fWork arrays*/\n\tdouble *irfWork;/*Instrument Response Function*/\n\tdouble *fWork; /*Workspace for function calculation*/\n\tsize_t m_total;\t/*Number of parameters (number of exponentials = (m-1)/2 ) */\n\tdouble *a;\t\t/*Parameter Array; fitted parameters x are subsituted into this array */\n\tsize_t m;\t\t/*Number of fitted parameters*/\n\tint *ip;\t\t/*Mapping of fitted parameter array x to parameter array a*/\n};\n\nvoid complex_convolution_multiply(double *a, const double *b, int n)\n{\n\tint i,j;\n\tdouble re,im,factor;\n\n\tfactor = 1.0/n; /* to normalize inverse FFT */\n\n\ta[0]*=b[0]*factor;\n\ta[n/2]*=b[n/2]*factor;\n\n\tfor (i=1;ideltaT;\n\tsize_t nRadix2 = ((struct data *)data)->nRadix2;\n\tdouble *irfWork = ((struct data *) data)->irfWork;\n\tdouble *fWork = ((struct data *) data)->fWork;\n\tsize_t m_total = ((struct data *)data)->m_total;\n\tdouble *a = ((struct data *) data)->a;\n\tint *ip = ((struct data *) data)->ip;\n\n\tint i,j;\n\tint numExponentials = (m_total-1)/2;\n\tdouble tau, amp, sqrtTau,sqrtAmp;\n\n\tdouble constantValue;\n\tdouble totalT=deltaT*n;\n\tdouble factor1;\n\tdouble factor2;\n\n\tif ( (n != ((struct data *)data)->n ) || (m != ((struct data *)data)->m) ) return;\n\n\n\tfor (i=0; ideltaT;\n\tsize_t nRadix2 = ((struct data *)data)->nRadix2;\n\tdouble *irfWork = ((struct data *) data)->irfWork;\n\tdouble *fWork = ((struct data *) data)->fWork;\n\tsize_t m_total = ((struct data *)data)->m_total;\n\tdouble *a = ((struct data *) data)->a;\n\tint *ip = ((struct data *) data)->ip;\n\tdouble *jac_row;\n\n\tint i,k;\n\n\tif ( (n != ((struct data *)data)->n ) || (m != ((struct data *)data)->m) ) return;\n\n\tfor (k=0; k\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../utils/utils.h\"\n#include \"../datastructures/datastructures.h\"\n\nint *tsp_bs(gsl_vector **, int); /* brute-force search */\nint *tsp_nn(gsl_vector **, int); /* nearest-neighbor */\nint *tsp_cp(gsl_vector **, int); /* closest-pair */\ndouble pathlen(gsl_vector **, int *, int); /* path length of a permutation. */\n\ndouble pathlen(gsl_vector **data, int *path, int n){\n /* Compute the length of the path defined by the vectors\n * in `data`, traversed in order given in `path`,\n * and closing the loop by traversing path[n-1] -- path[0]\n * at the end.\n */\n int i;\n double total = 0.;\n for (i = 0; i < n-1; i++)\n total += vector_dist(data[path[i]], data[path[i+1]]);\n if (n > 0)\n total += vector_dist(data[path[n-1]], data[path[0]]);\n return total;\n}\n\n\nint *tsp_nn(gsl_vector **data, int n)\n{\n /* Solve the TSP using the nearest-neighbor heuristic. */\n if (n == 0)\n return NULL;\n int i, j, best_id;\n int usedup = 0; /* Flag already-used elements. */\n gsl_vector *current = data[0];\n double cur_dist;\n double best_dist;\n int *nn_path = (int *) calloc(n, sizeof(int));\n \n nn_path[0] = 0;\n usedup |= 1;\n for (i = 1; i < n; i++){\n best_dist = 0;\n for (j = 1; j < n; j++){\n if (!(usedup & (2 << (j-1)))){\n \tcur_dist = vector_dist(current, data[j]);\n \tif (cur_dist < best_dist || best_dist == 0){\n \t best_dist = cur_dist;\n\t best_id = j;\n \t}\n }\n }\n current = data[best_id];\n nn_path[i] = best_id;\n usedup |= (2 << (best_id-1));\n }\n \n return nn_path;\n}\n\n\nint *tsp_cp(gsl_vector **data, int n)\n{\n /* Solve the TSP using the closest pair heuristic. */\n int i, j, ch1_id, ch2_id, best_ch1, best_ch2;\n int match_flag;\n double dist, best_dist;\n dlist_node *node;\n int *best_path = (int *) calloc(n, sizeof(int));\n\n /* Create an array where each element corresponds to a chain. */\n dlist **chains = (dlist **) calloc(n, sizeof(dlist *));\n for (i = 0; i < n; i++){\n chains[i] = dlist_new(data[i]);\n }\n\n /* Merge the chains according to the heuristic. */\n for (i = 0; i < n-1; i++){\n /* Find the smallest-distance chain ends pair. */\n best_dist = 0.;\n for (ch1_id = 0; ch1_id < n; ch1_id++){\n if (chains[ch1_id] == NULL){\n\tcontinue;\n }\n for (ch2_id = 0; ch2_id < n; ch2_id++){\n\tif (chains[ch2_id] == NULL || ch1_id == ch2_id){\n\t continue;\n\t}\n\tdist = vector_dist(chains[ch1_id]->head->item,\n\t\t\t chains[ch2_id]->head->item);\n\tif (dist < best_dist || best_dist == 0){\n\t /* Heads match. */\n\t best_dist = dist;\n\t best_ch1 = ch1_id;\n\t best_ch2 = ch2_id;\n\t match_flag = 0;\n\t}\n\n\tdist = vector_dist(chains[ch1_id]->head->item,\n\t\t\t chains[ch2_id]->tail->item);\n\tif (dist < best_dist || best_dist == 0){\n\t /* Head1 matches tail2. */\n\t best_dist = dist;\n\t best_ch1 = ch1_id;\n\t best_ch2 = ch2_id;\n\t match_flag = 1;\n\t}\n\t \n\tdist = vector_dist(chains[ch1_id]->tail->item,\n\t\t\t chains[ch2_id]->head->item);\n\tif (dist < best_dist || best_dist == 0){\n\t /* Tail1 matches head2. */\n\t best_dist = dist;\n\t best_ch1 = ch1_id;\n\t best_ch2 = ch2_id;\n\t match_flag = 2;\n\t}\n\t \n\tdist = vector_dist(chains[ch1_id]->tail->item,\n\t\t\t chains[ch2_id]->head->item);\n\tif (dist < best_dist || best_dist == 0){\n\t /* Tail1 matches tail2. */\n\t best_dist = dist;\n\t best_ch1 = ch1_id;\n\t best_ch2 = ch2_id;\n\t match_flag = 3;\n\t}\n }\n }\n printf(\"Iter %d, best match (%d, %d) %f\\n\",\n\t i, best_ch1, best_ch2, best_dist);\n\n /* Merge the smallest-distance chain ends. */\n if (match_flag == 0){\n /* Heads match: push ch2 to the front of ch1 in reverse-order. */\n while(chains[best_ch2]->head){\n\tdlist_insert(chains[best_ch1], \n\t\t chains[best_ch2]->head->item);\n\tdlist_delete(chains[best_ch2], chains[best_ch2]->head);\n }\n }\n else if (match_flag == 1){\n /* Head1 to tail2 match: push ch2 to the front of ch1 in-order. */\n while(chains[best_ch2]->tail){\n\tdlist_insert(chains[best_ch1], \n\t\t chains[best_ch2]->tail->item);\n\tdlist_delete(chains[best_ch2], chains[best_ch2]->tail);\n }\n }\n else if (match_flag == 2){\n /* Head2 to tail1 match: push ch2 to the end of ch1 in-order. */\n while(chains[best_ch2]->head){\n\tdlist_insert_tail(chains[best_ch1], \n\t\t\t chains[best_ch2]->head->item);\n\tdlist_delete(chains[best_ch2], chains[best_ch2]->head);\n }\n }\n else if (match_flag == 3){\n /* Tails match: push ch2 to the end of ch1 in reverse-order. */\n while(chains[best_ch2]->tail){\n\tdlist_insert_tail(chains[best_ch1], \n\t\t\t chains[best_ch2]->tail->item);\n\tdlist_delete(chains[best_ch2], chains[best_ch2]->tail);\n }\n }\n chains[best_ch2] = NULL;\n }\n\n /* All the chains except for one should be null. The non-null\n chain contains the best (heuristic) path. */\n for (i = 0; i < n; i++)\n if (chains[i])\n node = chains[i]->head;\n\n for(i = 0; node; i++){\n for (j = 0; j < n; j++)\n if (data[j] == node->item)\n\tbest_path[i] = j;\n node = node->next;\n } \n return best_path;\n}\n \n\n\nint *tsp_bs(gsl_vector **data, int n)\n{\n /* Find the shortest loop between `n` points. stored in `data`. */\n if (n == 0)\n return NULL;\n double best_dist = 0;\n double cur_dist = 0;\n int i_perm, i_iter;\n int *cur_path;\n int *best_path = calloc(n, sizeof(int));\n \n int **perm = permutations(n);\n for (i_iter = 0; i_iter < factorial(n); i_iter++){\n /* Retrieve the permutation into an array. */\n cur_path = perm[i_iter];\n\n /* Compute the path length corresponding to this permutation. */\n printf(\"Iter %d, permutation \", i_iter);\n print_intarray(cur_path, n);\n cur_dist = pathlen(data, cur_path, n);\n printf(\" dist %.10f.\\n\", cur_dist);\n\n /* Save best pathlen to-date. */\n if (best_dist > cur_dist || best_dist == 0){\n best_dist = cur_dist;\n for (i_perm = 0; i_perm < n; i_perm++)\n\tbest_path[i_perm] = cur_path[i_perm];\n }\n }\n printf(\"\\n\");\n free(cur_path);\n free(perm);\n return best_path;\n}\n\n\nint main(){\n char *fname;\n int npoints;\n int *bestpath;\n gsl_vector **vecs;\n\n /* Load data into a vector array. */\n fname = \"tsp.dat\";\n npoints = get_nlines(fname);\n vecs = load_vectors_from_file(\"tsp.dat\", npoints);\n\n /* Compute the best path using the brute-force method. */\n bestpath = tsp_bs(vecs, npoints);\n printf(\"Best path (brute-force) len = %f, for path \",\n\t pathlen(vecs, bestpath, npoints));\n print_intarray(bestpath, npoints);\n printf(\"\\n\");\n\n /* Compute the best path using the nearest-neighbor heuristic. */\n bestpath = tsp_nn(vecs, npoints);\n printf(\"Best path (nearest-neighbor) len = %f, for path \",\n\t pathlen(vecs, bestpath, npoints));\n print_intarray(bestpath, npoints);\n printf(\"\\n\");\n\n /* Compute the best path using the closest-pairs heuristic. */\n bestpath = tsp_cp(vecs, npoints);\n printf(\"Best path (closest-pair) len = %f, for path \",\n\t pathlen(vecs, bestpath, npoints));\n print_intarray(bestpath, npoints);\n printf(\"\\n\");\n\n return 0;\n}\n", "meta": {"hexsha": "0c1b4638feb1dfde5d7b05b79eff1d1950ebcc23", "size": 7189, "ext": "c", "lang": "C", "max_stars_repo_path": "skiena/chap1/ex1_26.c", "max_stars_repo_name": "kjchalup/algorithm_design", "max_stars_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "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": "skiena/chap1/ex1_26.c", "max_issues_repo_name": "kjchalup/algorithm_design", "max_issues_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "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": "skiena/chap1/ex1_26.c", "max_forks_repo_name": "kjchalup/algorithm_design", "max_forks_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2310606061, "max_line_length": 78, "alphanum_fraction": 0.6146891084, "num_tokens": 2224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.591074234104325}} {"text": "// Copyright [1999-2017] EMBL-European Bioinformatics Institute\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \n#include \n#include \n\n#include \"multiSet.h\"\n\ntypedef struct setComparisonData_st {\n\tMultiset * multi;\n} SetComparisonData;\n\nvoid SetComparisonSeek(WiggleIterator * iter, const char * chrom, int start, int finish) {\n\tSetComparisonData * data = (SetComparisonData* ) iter->data;\n\tseekMultiset(data->multi, chrom, start, finish);\n\tpop(iter);\n}\n\n////////////////////////////////////////////////////////\n// T-test\n////////////////////////////////////////////////////////\n\nvoid TTestReductionPop(WiggleIterator * wi) {\n\tif (wi->done)\n\t\treturn;\n\n\tSetComparisonData * data = (SetComparisonData *) wi->data;\n\tMultiset * multi = data->multi;\n\n\tif (multi->done) {\n\t\twi->done = true;\n\t\treturn;\n\t}\n\n\t// Go to first position where both of the sets have at least one value\n\twhile (!multi->inplay[0] || !multi->inplay[1]) {\n\t\tpopMultiset(multi);\n\t\tif (multi->done) {\n\t\t\twi->done = true;\n\t\t\treturn;\n\t\t}\n\t}\n\twi->chrom = multi->chrom;\n\twi->start = multi->start;\n\twi->finish = multi->finish;\n\n\t// Compute measurements\n\tdouble sum1, sum2, sumSq1, sumSq2;\n\tint count1, count2;\n\tint index;\n\n\tsum1 = sum2 = 0;\n\tsumSq1 = sumSq2 = 0;\n\tcount1 = multi->multis[0]->count;\n\tcount2 = multi->multis[1]->count;\n\n\tfor (index = 0; index < multi->multis[0]->count; index++) {\n\t\tif (multi->multis[0]->inplay[index]) {\n\t\t\tsum1 += multi->values[0][index];\n\t\t\tsumSq1 += multi->values[0][index] * multi->values[0][index];\n\t\t}\n\t}\n\n\tfor (index = 0; index < multi->multis[1]->count; index++) {\n\t\tif (multi->multis[1]->inplay[index]) {\n\t\t\tsum2 += multi->values[1][index];\n\t\t\tsumSq2 += multi->values[1][index] * multi->values[1][index];\n\t\t}\n\t}\n\n\t// To avoid divisions by 0:\n\tif (count1 == 0 || count2 == 0) {\n\t\twi->value = NAN;\n\t\tpopMultiset(multi);\n\t\treturn;\n\t}\n\n\tdouble mean1 = sum1 / count1;\n\tdouble mean2 = sum2 / count2;\n\tdouble meanSq1 = sumSq1 / count1;\n\tdouble meanSq2 = sumSq2 / count2;\n\tdouble var1 = meanSq1 - mean1 * mean1;\n\tdouble var2 = meanSq2 - mean2 * mean2;\n\n\t// To avoid divisions by 0:\n\tif (var1 + var2 == 0) {\n\t\twi->value = NAN;\n\t\tpopMultiset(multi);\n\t\treturn;\n\t}\n\n\t// T-statistic\n\n\tdouble t = (mean1 - mean2) / sqrt(var1 / count1 + var2 / count2);\n\n\tif (t < 0)\n\t\tt = -t;\n\n\t// Degrees of freedom\n\t\n\tdouble nu = (var1 / count1 + var2 / count2) * (var1 / count1 + var2 / count2) / ((var1 * var1) / (count1 * count1 * (count1 - 1)) + (var2 * var2) / (count2 * count2 * (count2 - 1)));\n\n\t// P-value\n\n\twi->value = 2 * gsl_cdf_tdist_Q(t, nu);\n\n\t// Update inputs\n\tpopMultiset(multi);\n}\n\nWiggleIterator * TTestReduction(Multiset * multi) {\n\tSetComparisonData * data = (SetComparisonData *) calloc(1, sizeof(SetComparisonData));\n\tif (multi->count != 2 || multi->multis[0]->count < 3 || multi->multis[1]->count < 3) {\n\t\tputs(\"The t-test function only works for two sets with enough elements to compute variance\");\n\t\texit(1);\n\t}\t\n\tdata->multi = multi;\n\treturn newWiggleIterator(data, &TTestReductionPop, &SetComparisonSeek, NAN);\n}\n\n\n////////////////////////////////////////////////////////\n// F-test\n////////////////////////////////////////////////////////\n\ntypedef struct ftestData_st {\n\tMultiset * multi;\n\tint * counts;\n\tdouble * means;\n\tint total_count;\n} FTestData;\n\nvoid FTestSeek(WiggleIterator * iter, const char * chrom, int start, int finish) {\n\tFTestData * data = (FTestData* ) iter->data;\n\tseekMultiset(data->multi, chrom, start, finish);\n\tpop(iter);\n}\n\n\nvoid FTestReductionPop(WiggleIterator * wi) {\n\tif (wi->done)\n\t\treturn;\n\n\tFTestData * data = (FTestData *) wi->data;\n\tMultiset * multi = data->multi;\n\n\tif (multi->done) {\n\t\twi->done = true;\n\t\treturn;\n\t}\n\n\t// Go to first position where both of the sets have at least one value\n\twhile (!multi->inplay[0] || !multi->inplay[1]) {\n\t\tpopMultiset(multi);\n\t\tif (multi->done) {\n\t\t\twi->done = true;\n\t\t\treturn;\n\t\t}\n\t}\n\twi->chrom = multi->chrom;\n\twi->start = multi->start;\n\twi->finish = multi->finish;\n\n\t// Compute means\n\tdouble mean = 0;\n\tint groups = multi->count;\n\tint index, index2;\n\tfor (index = 0; index < groups; index++) {\n\t\tMultiplexer * mplx = multi->multis[index];\n\t\tdata->means[index] = 0;\n\t\tfor (index2 = 0; index < mplx->count; index++) {\n\t\t\tif (mplx->inplay[index2])\n\t\t\t\tdata->means[index] += mplx->values[index2];\n\t\t\telse\n\t\t\t\tdata->means[index] += mplx->iters[index2]->default_value;\n\t\t}\n\t\tmean += data->means[index];\n\t\tdata->means[index] /= data->counts[index];\n\t}\n\tmean /= data->total_count;\n\n\tdouble inter = 0;\n\tdouble intra = 0;\n\tfor (index = 0; index < groups; index++) {\n\t\tMultiplexer * mplx = multi->multis[index];\n\t\tinter += mplx->count * (data->means[index] - mean) * (data->means[index] - mean);\n\t\tfor (index2 = 0; index < mplx->count; index++) {\n\t\t\tif (mplx->inplay[index2])\n\t\t\t\tintra += (mplx->values[index2] - data->means[index]) * (mplx->values[index2] - data->means[index]);\n\t\t\telse\n\t\t\t\tintra += (mplx->iters[index2]->default_value - data->means[index]) * (mplx->iters[index2]->default_value - data->means[index]);\n\t\t}\n\t}\n\n\t// F-statistic\n\tinter /= groups - 1;\n\tintra /= data->total_count - groups;\n\tdouble f = inter / intra;\n\n\t// P-value\n\twi->value = 2 * gsl_cdf_fdist_Q(f, multi->count - 1, data->total_count - multi->count);\n\n\t// Update inputs\n\tpopMultiset(multi);\n}\n\nWiggleIterator * FTestReduction(Multiset * multi) {\n\tFTestData * data = (FTestData *) calloc(1, sizeof(FTestData));\n\tdata->multi = multi;\n\tdata->means = calloc(multi->count, sizeof(double)); \n\tdata->counts = calloc(multi->count, sizeof(int)); \n\tint index;\n\tfor (index = 0; index < multi->count; index++) {\n\t\tdata->counts[index] = multi->multis[index]->count;\n\t\tdata->total_count += data->counts[index];\n\t}\n\treturn newWiggleIterator(data, &FTestReductionPop, &FTestSeek, NAN);\n}\n\n////////////////////////////////////////////////////////\n// Mann-Whitney U (Wilcoxon rank-sum test)\n////////////////////////////////////////////////////////\n\ntypedef struct valueSetPair_st {\n\tdouble value;\n\tbool set;\n} ValueSetPair;\n\ntypedef struct mwuData_st {\n\tMultiset * multi;\n\tint n1;\n\tint n2;\n\tint N;\n\t// Pre-allocated table for sorting\n\tValueSetPair * rankingTable;\n\t// For normal approximation\n\tbool normalApproximation;\n\tdouble mu_U, sigma_U;\n} MWUData;\n\nvoid MWUSeek(WiggleIterator * iter, const char * chrom, int start, int finish) {\n\tMWUData * data = (MWUData* ) iter->data;\n\tseekMultiset(data->multi, chrom, start, finish);\n\tpop(iter);\n}\n\nstatic int compareValueSetPairs(const void * A, const void * B) {\n\tValueSetPair * vspA = (ValueSetPair *) A;\n\tValueSetPair * vspB = (ValueSetPair *) B;\n\tif (vspA->value < vspB->value)\n\t\treturn -1;\n\tif (vspA->value > vspB->value)\n\t\treturn 1;\n\treturn 0;\n}\n\nvoid MWUReductionPop(WiggleIterator * wi) {\n\tif (wi->done)\n\t\treturn;\n\n\tMWUData * data = (MWUData *) wi->data;\n\tMultiset * multi = data->multi;\n\n\tif (multi->done) {\n\t\twi->done = true;\n\t\treturn;\n\t}\n\n\t// Go to first position where both of the sets have at least one value\n\twhile (!multi->inplay[0] || !multi->inplay[1]) {\n\t\tpopMultiset(multi);\n\t\tif (multi->done) {\n\t\t\twi->done = true;\n\t\t\treturn;\n\t\t}\n\t}\n\twi->chrom = multi->chrom;\n\twi->start = multi->start;\n\twi->finish = multi->finish;\n\n\t// Compute measurements\n\tint index;\n\tValueSetPair * vspPtr = data->rankingTable;\n\n\tfor (index = 0; index < data->n1; index++) {\n\t\tif (multi->multis[0]->inplay[index]) \n\t\t\tvspPtr->value = multi->values[0][index];\n\t\telse\n\t\t\tvspPtr->value = multi->multis[0]->iters[index]->default_value;\n\t\tif (isnan(vspPtr->value)) {\n\t\t\twi->value = NAN;\n\t\t\tpopMultiset(multi);\n\t\t\treturn;\n\t\t}\n\t\tvspPtr->set = false;\n\t\tvspPtr++;\n\t}\n\n\tfor (index = 0; index < data->n2; index++) {\n\t\tif (multi->multis[1]->inplay[index]) \n\t\t\tvspPtr->value = multi->values[1][index];\n\t\telse\n\t\t\tvspPtr->value = multi->multis[1]->iters[index]->default_value;\n\t\tif (isnan(vspPtr->value)) {\n\t\t\twi->value = NAN;\n\t\t\tpopMultiset(multi);\n\t\t\treturn;\n\t\t}\n\t\tvspPtr->set = true;\n\t\tvspPtr++;\n\t}\n\n\tqsort(data->rankingTable, data->N, sizeof(ValueSetPair), compareValueSetPairs);\n\n\t// Sum of ranks of elements of set 1\n\tdouble U1 = 0;\n\t// Rolling count of elements of set 1 seen prior on the list\n\tint prev = 0;\n\t// Warns you when you have a tie with the previously visited Value-Set pairs\n\tint ties = 0;\n\tint previousTies = 0;\n\tvspPtr = data->rankingTable;\n\tfor (index = 0; index < data->N && prev < data->n1; index++) {\n\t\tif (!vspPtr->set) {\n\t\t\tU1 += index - prev;\n\t\t\tif (ties) {\n\t\t\t\t// Look for ties on the table prior to the current position and after the last occurence of an element of set 1.\n\t\t\t\tint index2;\n\t\t\t\tfor (index2 = index + 1; index2 < data->N && data->rankingTable[index2].value == vspPtr->value && data->rankingTable[index2].set; index2++)\n\t\t\t\t\tpreviousTies++;\n\t\t\t\tU1 -= previousTies / 2.0;\n\t\t\t\tU1 += (ties - previousTies) / 2.0;\n\t\t\t\tif (previousTies == ties)\n\t\t\t\t\tpreviousTies = ties = 0;\n\t\t\t} else {\n\t\t\t\tint index2;\n\t\t\t\t// Look for ties with next values\n\t\t\t\tfor (index2 = index + 1; index2 < data->N && data->rankingTable[index2].value == vspPtr->value; index2++)\n\t\t\t\t\tif (data->rankingTable[index2].set)\n\t\t\t\t\t\tties++;\n\t\t\t\tif (ties) \n\t\t\t\t\tU1 += ties / 2.0;\n\t\t\t}\n\t\t\tprev++;\n\t\t}\n\t\tvspPtr++;\n\t}\n\n\tif (data->normalApproximation) {\n\t\tif (U1 > data->mu_U)\n\t\t\twi->value = 2 * erf((data->mu_U - U1) / data->sigma_U);\n\t\telse\n\t\t\twi->value = 2 * erf((U1 - data->mu_U) / data->sigma_U);\n\t}\n\n\t// Update inputs\n\tpopMultiset(multi);\n}\n\nWiggleIterator * MWUReduction(Multiset * multi) {\n\tMWUData * data = (MWUData *) calloc(1, sizeof(MWUData));\n\tif (multi->count != 2 || multi->multis[0]->count == 0 || multi->multis[1]->count == 0) {\n\t\tputs(\"The Mann-Whitney U function only works for two non-empty sets\");\n\t\texit(1);\n\t}\t\n\tdata->multi = multi;\n\tdata->n1 = multi->multis[0]->count;\n\tdata->n2 = multi->multis[1]->count;\n\tdata->N = data->n1 + data->n2;\n\tdata->rankingTable = calloc(data->N, sizeof(ValueSetPair));\n\tif (true) {\n\t\t// Ideally, tables could be used for small values of n1 and n2\n\t\tdata->normalApproximation = true;\n\t\tdata->mu_U = data->n1 * data->n2 / 2;\n\t\tdata->sigma_U = sqrt(data->n1 * data->n2 * (data->n1 + data->n2 + 1) / 12);\n\t}\n\treturn newWiggleIterator(data, &MWUReductionPop, &MWUSeek, NAN);\n}\n", "meta": {"hexsha": "16f6d5dd32ac9f849ad90607ff9d835b60065fbe", "size": 10617, "ext": "c", "lang": "C", "max_stars_repo_path": "src/setComparisons.c", "max_stars_repo_name": "juettemann/WiggleTools", "max_stars_repo_head_hexsha": "867b6ce6fcfa7aa02c4ff647adb6e4a25744e06a", "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/setComparisons.c", "max_issues_repo_name": "juettemann/WiggleTools", "max_issues_repo_head_hexsha": "867b6ce6fcfa7aa02c4ff647adb6e4a25744e06a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/setComparisons.c", "max_forks_repo_name": "juettemann/WiggleTools", "max_forks_repo_head_hexsha": "867b6ce6fcfa7aa02c4ff647adb6e4a25744e06a", "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": 27.1534526854, "max_line_length": 183, "alphanum_fraction": 0.6272958463, "num_tokens": 3301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5908430937234859}} {"text": "/**\n *\n * @file core_cpltmg_condex.c\n *\n * PLASMA core_blas kernel\n * PLASMA is a software package provided by Univ. of Tennessee,\n * Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated c Tue Jan 7 11:44:47 2014\n *\n **/\n#include \n#include \n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex32_t\n *\n * CORE_cpltmg_condexq generates the Q used in condex matrix generation\n *\n * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-999898\n * gallery('condex',n,4,100)\n *\n * Returns a \"counter-example\" matrix to a condition estimator. It has order n\n * and scalar parameter theta (default 100).\n *\n * LAPACK (RCOND): It is the inverse of this matrix that is a counter-example.\n *\n *******************************************************************************\n *\n * @param[in] M\n * The number of rows of the matrix Q used in condex generation. M >= 0.\n *\n * @param[in] N\n * The number of columns of the matrix A to be generated. N >= 0.\n *\n * @param[out] Q\n * On entry, the M-by-3 matrix to be initialized.\n * On exit, the housholder reflectors required for condex generation.\n *\n * @param[in] LDQ\n * The leading dimension of the matrix Q. LDQ >= max(1,M).\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_cpltmg_condexq = PCORE_cpltmg_condexq\n#define CORE_cpltmg_condexq PCORE_cpltmg_condexq\n#endif\nvoid CORE_cpltmg_condexq( int M, int N, PLASMA_Complex32_t *Q, int LDQ )\n{\n PLASMA_Complex32_t tau[3];\n PLASMA_Complex32_t *tQ = Q;\n int i;\n\n /* First column is [ 1 ... 1 ] */\n for( i=0; i < M; i++, tQ++ )\n *tQ = (PLASMA_Complex32_t)1.0;\n\n /* Second column is [1 0 0 ... 0] */\n tQ = Q + LDQ;\n *tQ = (PLASMA_Complex32_t)1.;\n tQ++;\n memset( tQ, 0, (M-1) * sizeof(PLASMA_Complex32_t) );\n\n /* Third column is (-1)^i * (1. + i / (N-1)) */\n tQ = Q + 2 * LDQ;\n for( i=0; i\n#include \n#include \n#include \n#include \n#include \n#define USAGE \"./mcmc_solar.x n_burn n_steps\"\n\n//------------------------------------------------------------------------------------------------------------\n\nfloat *load_matrix(char *filename, int *n, int *m);\nvoid get_data( float *array , float *x, int n_row);\nfloat *reserva(int n);\nvoid print_data(float *array, float *array2, float *array3, float *array4 , float *array5 , float *array6 , float *array7 , float *array8, int n_puntos);\nvoid get_patch( float *array, float *x , int n_row);\nvoid my_model( float *x_obs, float *array, float a, float b, float c , float d, int n_row);\nfloat likelihood(float *y_obs, float *y_model, int n_row);\nint min_likelihood( float *array , int n_row);\n\n\n//------------------------------------------------------------------------------------------------------------\n\nint main(int argc, char **argv){\n float *matrix , *tim, *man, *count, *a_walk, *b_walk, *c_walk, *d_walk, *l_walk, *y_init, *y_prime, *best_y;\n srand48(time(NULL));\n float a_prime, b_prime, c_prime, d_prime, l_prime, l_init, gamma, alpha, beta , best_a , best_b, best_c, best_d;\n int n_row, n_cols , i, rlin = 0;\n \n \n a_walk = reserva(atof(argv[1])+atof(argv[2]));\n b_walk = reserva(atof(argv[1])+atof(argv[2]));\n c_walk = reserva(atof(argv[1])+atof(argv[2]));\n d_walk = reserva(atof(argv[1])+atof(argv[2]));\n l_walk = reserva(atof(argv[1])+atof(argv[2]));\n y_init = reserva(n_row);\n y_prime = reserva(n_row);\n\n \n a_walk[0] = drand48();\n b_walk[0] = drand48();\n c_walk[0] = drand48();\n d_walk[0] = drand48();\n \n \n\n matrix = load_matrix( \"sol.dat\" , &n_row, &n_cols);\n \n man = reserva( n_row);\n tim = reserva(n_row);\n man = reserva(n_row);\n best_y = reserva( n_row);\n get_data( matrix , tim , n_row);\n get_patch( matrix , man , n_row);\n \n for (i=0;i=0.0) {\n a_walk[i+1] = a_prime;\n b_walk[i+1] = b_prime;\n c_walk[i+1] = c_prime;\n d_walk[i+1] = d_prime;\n l_walk[i+1] = l_prime;\n }\n else{\n \n beta = drand48();\n alpha = exp(gamma);\n if (beta <= alpha) {\n \n a_walk[i+1] = a_prime;\n b_walk[i+1] = b_prime;\n c_walk[i+1] = c_prime;\n d_walk[i+1] = d_prime;\n l_walk[i+1] = l_prime;\n }\n else{\n \n a_walk[i+1] = a_walk[i];\n b_walk[i+1] = b_walk[i];\n c_walk[i+1] = c_walk[i];\n d_walk[i+1] = d_walk[i];\n l_walk[i+1] = l_init;\n \n }\n \n }\n }\n \n i = min_likelihood( l_walk , n_row);\n best_a = a_walk[i];\n best_b = b_walk[i];\n best_c = c_walk[i];\n best_d = d_walk[i];\n \n my_model( tim , best_y , best_a, best_b , best_c , best_d , n_row);\n \n print_data( tim , man, l_walk , a_walk , b_walk , c_walk , d_walk , best_y, n_row);\n \n gsl_rng_free (r);\n\n \n return 0;\n}\n\n//------------------------------------------------------------------------------------------------------------\n\nfloat *load_matrix(char *filename, int *n, int *m){\n float *matrix;\n FILE *in;\n int n_row = 4632, n_cols = 5;\n int i;\n int j;\n \n if(!(in=fopen(filename, \"r\"))){\n printf(\"Problem opening file %s\\n\", filename);\n exit(1);\n }\n\n \n matrix = malloc(n_row * n_cols * sizeof(float));\n \n for(i=0;i\n#include \n#include \n#include \n\nint\nfunc (double t, const double y[], double f[],\n void *params)\n{\n double mu = *(double *)params;\n f[0] = y[1];\n f[1] = -y[0] - mu*y[1]*(y[0]*y[0] - 1);\n return GSL_SUCCESS;\n}\n\nint\njac (double t, const double y[], double *dfdy, \n double dfdt[], void *params)\n{\n double mu = *(double *)params;\n gsl_matrix_view dfdy_mat \n = gsl_matrix_view_array (dfdy, 2, 2);\n gsl_matrix * m = &dfdy_mat.matrix; \n gsl_matrix_set (m, 0, 0, 0.0);\n gsl_matrix_set (m, 0, 1, 1.0);\n gsl_matrix_set (m, 1, 0, -2.0*mu*y[0]*y[1] - 1.0);\n gsl_matrix_set (m, 1, 1, -mu*(y[0]*y[0] - 1.0));\n dfdt[0] = 0.0;\n dfdt[1] = 0.0;\n return GSL_SUCCESS;\n}\n\nint\nmain (void)\n{\n double mu = 10;\n gsl_odeiv2_system sys = {func, jac, 2, &mu};\n\n gsl_odeiv2_driver * d = \n gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rk8pd,\n\t\t\t\t 1e-6, 1e-6, 0.0);\n int i;\n double t = 0.0, t1 = 100.0;\n double y[2] = { 1.0, 0.0 };\n\n for (i = 1; i <= 100; i++)\n {\n double ti = i * t1 / 100.0;\n int status = gsl_odeiv2_driver_apply (d, &t, ti, y);\n\n if (status != GSL_SUCCESS)\n\t{\n\t printf (\"error, return value=%d\\n\", status);\n\t break;\n\t}\n\n printf (\"%.5e %.5e %.5e\\n\", t, y[0], y[1]);\n }\n\n gsl_odeiv2_driver_free (d);\n return 0;\n}\n", "meta": {"hexsha": "5a336515d2a2bc905590c020c56bf663668944d1", "size": 1345, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/ode-initval.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/ode-initval.c", "max_issues_repo_name": "ruslankuzmin/julia", "max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/ode-initval.c", "max_forks_repo_name": "ruslankuzmin/julia", "max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 21.3492063492, "max_line_length": 63, "alphanum_fraction": 0.5710037175, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.590579220444762}} {"text": "/**\n * Subroutines used in the \"aXe_AF2PET.c\" for the task aXe_AF2PET\n */\n\n#include \n\n#include \n#include \n#include \n\n#include \"spc_wl_calib.h\"\n#include \"aXe_grism.h\"\n#include \"aXe_errors.h\"\n#include \"disp_conf.h\"\n\n\n/**\n * The function performs a wavelength calibration on an allready\n * existing ap_pixel table. It fills in the lambda and dlambda fields.\n *\n * @param ap_p - the ap_pixel table to work on, with the pathlength field\n * filled out\n * @param calib - the calibration function\n */\nvoid\nwl_calib (ap_pixel * ap_p, const calib_function * const calib)\n{\n double l1,l2;\n\n while (ap_p->p_x != -1)\n {\n ap_p->lambda = calib->func (ap_p->xi, calib->order, calib->coeffs);\n\n l1 = calib->func (ap_p->xi - .5, calib->order, calib->coeffs);\n l2 = calib->func (ap_p->xi + .5, calib->order, calib->coeffs);\n ap_p->dlambda = fabs(l2-l1);\n ap_p++;\n }\n}\n\n/*\n * Function: pwise_wl_calib\n * Make for every PET pixel an individual wavelength\n * calibration. The function was developed for FORS2 MXU spectra\n * and makes especially sense for long spectra and/or fast\n * variations of the 2D calibration solution.\n */\nvoid\npwise_wl_calib(const global_disp *gdisp, const d_point pixel,\n\t const beam actbeam, const int for_grism, ap_pixel *ap_p, const calib_function *old_calib)\n{\n\n calib_function *calib;\n d_point actpix;\n\n double l1,l2;\n double tmp;\n\n int i=0;\n\n while (ap_p[i].p_x != -1)\n {\n // get the current xy-position of the pixel\n actpix.x = pixel.x + ap_p[i].dist*cos(actbeam.orient);\n actpix.y = pixel.y + ap_p[i].dist*sin(actbeam.orient);\n\n // create a calibration for that position\n calib = create_calib_from_gsl_vector(for_grism, get_calvector_from_gdisp(gdisp, actpix));\n\n // determine the wavelength value\n ap_p[i].lambda = calib->func (ap_p[i].xi, calib->order, calib->coeffs);\n\n // determine the dlambda value\n l1 = calib->func (ap_p[i].xi - .5, calib->order, calib->coeffs);\n l2 = calib->func (ap_p[i].xi + .5, calib->order, calib->coeffs);\n ap_p[i].dlambda = fabs(l2-l1);\n\n // determine the trace length\n tmp = old_calib->func (ap_p[i].xi, old_calib->order, old_calib->coeffs);\n ap_p[i].xi = ap_p[i].xi + (ap_p[i].lambda - tmp) / ap_p[i].dlambda;\n\n // free the calibration\n // structure\n free_calib(calib);\n\n // enhance the counter\n i++;\n }\n}\n\n/**\n * The function trims down an ap_pixel table to only allowed values\n * for the trace path length or trace distance. The input ap_pixel\n * is only changed. Valid entries are moved to the front side,\n * and a new endmark is set after all valid entries\n *\n * @param ap_pixel the input ap_pixel table\n * @param prange the valid trace range\n * @param wl_calibration the calibration structure, needed to get the\n * first dispersion coefficient\n *\n * @return ret ap_pixel table output\n */\nap_pixel *\nprange_cut(ap_pixel * in_p, const gsl_vector * prange,\n const calib_function * wl_calibration)\n{\n\n //long nelem;\n ap_pixel * ret, *cur_ap, *ap_p;\n double prel;\n double trmin=1.0E+06, trmax=-1.0E6;\n\n // set all PET list pointers\n // to the beginning of the array\n ret = in_p;\n cur_ap = in_p;\n ap_p = in_p;\n\n while (ap_p->p_x != -1)\n {\n // search for new minimum\n // and amximum in tracelength\n if (ap_p->xi > trmax)\n trmax = ap_p->xi;\n if (ap_p->xi < trmin)\n trmin = ap_p->xi;\n\n // compute the tracelength with\n // respect to the zeropoint\n prel = ap_p->xi - wl_calibration->coeffs[0];\n\n // check whether the realitive zeropoint is within the allowed range\n if (prel > gsl_vector_get(prange,0) && prel < gsl_vector_get(prange,1))\n {\n // transfer the properties\n // of the good pixel to the next\n // PET element in the list of good PET's\n cur_ap->p_x = ap_p->p_x;\n cur_ap->p_y = ap_p->p_y;\n cur_ap->x = ap_p->x;\n cur_ap->y = ap_p->y;\n cur_ap->dist = ap_p->dist;\n cur_ap->xs = ap_p->xs;\n cur_ap->ys = ap_p->ys;\n cur_ap->dxs = ap_p->dxs;\n cur_ap->xi = ap_p->xi;\n cur_ap->count = ap_p->count;\n cur_ap->error = ap_p->error;\n cur_ap->weight = ap_p->weight;\n cur_ap->contam = ap_p->contam;\n cur_ap->dq = ap_p->dq;\n\n // forward the pointer\n // of good pixels\n cur_ap++;\n }\n\n // always forward the\n // general pointer\n ap_p++;\n }\n\n // make a new endmark\n cur_ap->p_x = -1;\n cur_ap->p_y = -1;\n cur_ap->count = -1;\n\n // return the pointer\n return ret;\n}\n\n\n/**\n * Calibration function for the grism: simple polynomial\n *\n * @param xi the path length of the sample point\n * @param order the order of the polynomial, i.e. the number of coefficients\n * minus one\n * @param coeffs a pointer to order+1 doubles, starting with the zeroth\n * coefficent\n *\n * @return res wavelength at xi\n */\nstatic double\ngrism_calib_func (const double xi, const int order,\n\t\t const double *const coeffs)\n{\n int i;\n double res = 0;\n\n for (i = 0; i <= order; i++)\n {\n res += coeffs[i] * pow(xi,i*1.0);\n }\n\n return res;\n}\n\n\n/**\n * Calibration function for the prism: reciprocal polynomial in the\n * form: lambda = a1 + a2/(xi-a0) + a3/(xi-a0)**2 + a4/(xi-a0)**3\n *\n * @param xi the path length of the sample point\n * @param order the order of the polynomial, i.e. the number of coefficients\n * minus one\n * @param coeffs a pointer to order+1 doubles, starting with the zeroth\n * coefficent\n * @return res wavelength at xi\n */\nstatic double\nprism_calib_func (const double xi, const int order,\n\t\t const double *const coeffs)\n{\n int i;\n double res = 0;\n\n if (xi==0.) return GSL_NAN;\n for (i = 0; i <= order-1; i++)\n {\n //\t res += coeffs[i] / pow(xi,i*1.0);\n res += coeffs[i+1] / pow((xi-coeffs[0]),i*1.0);\n }\n\n return res;\n}\n\n/**\n * Create a prism or grism calibration function, i.e. a function of one of\n * the forms \"sum(a_i 1/x^i, i=0..order)\" or \"sum(a_i x^i, i=0..order)\"\n * for transforming pathlength along the trace to lambda.\n *\n *@param for_grism if true, a the second form of the calibration function\n * is used (normal polynom), otherwise the first one.\n *@param order order of the polynom\n *@param a a GSL vector of length n containing the n coefficients\n * describing the wavelength calibration polynomial.\n *@return calib an allocated structure containing an allocated array\n * for the coefficients. Free using calib_free.\n */\ncalib_function *\ncreate_calib_from_gsl_vector (const int for_grism, const gsl_vector * a)\n{\n calib_function *calib;\n int i, order;\n\n // set the polynomial order\n order = a->size - 1;\n\n // allocate memory\n calib = malloc(sizeof (calib_function));\n\n // complain if memory\n // allocation failed\n if (!calib)\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__, \"Out of memory\");\n\n // store the order of the\n // calibration\n calib->order = order;\n\n // transfer the calibration functions\n if (for_grism)\n calib->func = &grism_calib_func;\n else\n calib->func = &prism_calib_func;\n\n // allocate memory; complain if problems occur\n calib->coeffs = malloc ((order + 1) * sizeof (double));\n if (!calib->coeffs)\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__, \"Out of memory\");\n\n // transfer the coefficients\n calib->coeffs[0] = gsl_vector_get (a, 0);\n for (i = 1; i <= order; i++)\n calib->coeffs[i] = gsl_vector_get (a, i);\n\n // set the allowed range for\n // the trace lengths to NULL\n calib->pr_range = NULL;\n\n // return the calibration\n // structure\n return calib;\n}\n\n/**\n * Function: free_calib\n * Free a calibration function and its assoicated data.\n *\n * @param calib the calibration structure to be freed\n *\n */\nvoid\nfree_calib(calib_function * calib)\n{\n free (calib->coeffs);\n calib->coeffs = NULL;\n if (calib->pr_range != NULL)\n {\n gsl_vector_free(calib->pr_range);\n calib->pr_range = NULL;\n }\n free (calib);\n calib = NULL;\n}\n", "meta": {"hexsha": "ec6ddbb89000adfb0d55faf275f0d009cdd1d555", "size": 8339, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/spc_wl_calib.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spc_wl_calib.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spc_wl_calib.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0746753247, "max_line_length": 97, "alphanum_fraction": 0.6211775992, "num_tokens": 2432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5903552965567694}} {"text": "/* integration/qmomo.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n\nstatic void\ninitialise (double * ri, double * rj, double * rg, double * rh,\n double alpha, double beta);\n\ngsl_integration_qaws_table * \ngsl_integration_qaws_table_alloc (double alpha, double beta, int mu, int nu)\n{\n gsl_integration_qaws_table * t;\n\n if (alpha < -1.0)\n {\n GSL_ERROR_VAL (\"alpha must be greater than -1.0\", GSL_EINVAL, 0);\n }\n\n if (beta < -1.0)\n {\n GSL_ERROR_VAL (\"beta must be greater than -1.0\", GSL_EINVAL, 0);\n }\n\n if (mu != 0 && mu != 1)\n {\n GSL_ERROR_VAL (\"mu must be 0 or 1\", GSL_EINVAL, 0);\n }\n\n if (nu != 0 && nu != 1)\n {\n GSL_ERROR_VAL (\"nu must be 0 or 1\", GSL_EINVAL, 0);\n }\n\n t = (gsl_integration_qaws_table *) \n malloc(sizeof(gsl_integration_qaws_table));\n\n if (t == 0)\n {\n GSL_ERROR_VAL (\"failed to allocate space for qaws_table struct\",\n GSL_ENOMEM, 0);\n }\n\n t->alpha = alpha;\n t->beta = beta;\n t->mu = mu;\n t->nu = nu;\n \n initialise (t->ri, t->rj, t->rg, t->rh, alpha, beta);\n \n return t;\n}\n\n\nint\ngsl_integration_qaws_table_set (gsl_integration_qaws_table * t,\n double alpha, double beta, int mu, int nu)\n{\n if (alpha < -1.0)\n {\n GSL_ERROR (\"alpha must be greater than -1.0\", GSL_EINVAL);\n }\n\n if (beta < -1.0)\n {\n GSL_ERROR (\"beta must be greater than -1.0\", GSL_EINVAL);\n }\n\n if (mu != 0 && mu != 1)\n {\n GSL_ERROR (\"mu must be 0 or 1\", GSL_EINVAL);\n }\n\n if (nu != 0 && nu != 1)\n {\n GSL_ERROR (\"nu must be 0 or 1\", GSL_EINVAL);\n }\n\n t->alpha = alpha;\n t->beta = beta;\n t->mu = mu;\n t->nu = nu;\n \n initialise (t->ri, t->rj, t->rg, t->rh, alpha, beta);\n\n return GSL_SUCCESS;\n}\n\n\nvoid\ngsl_integration_qaws_table_free (gsl_integration_qaws_table * t)\n{\n RETURN_IF_NULL (t);\n free (t);\n}\n\nstatic void\ninitialise (double * ri, double * rj, double * rg, double * rh,\n double alpha, double beta)\n{\n const double alpha_p1 = alpha + 1.0;\n const double beta_p1 = beta + 1.0;\n\n const double alpha_p2 = alpha + 2.0;\n const double beta_p2 = beta + 2.0;\n\n const double r_alpha = pow (2.0, alpha_p1);\n const double r_beta = pow (2.0, beta_p1);\n\n size_t i;\n \n double an, anm1;\n\n ri[0] = r_alpha / alpha_p1;\n ri[1] = ri[0] * alpha / alpha_p2;\n\n an = 2.0;\n anm1 = 1.0;\n\n for (i = 2; i < 25; i++)\n {\n ri[i] = -(r_alpha + an * (an - alpha_p2) * ri[i - 1])\n / (anm1 * (an + alpha_p1));\n anm1 = an;\n an = an + 1.0;\n }\n\n rj[0] = r_beta / beta_p1;\n rj[1] = rj[0] * beta / beta_p2;\n\n an = 2.0;\n anm1 = 1.0;\n\n for (i = 2; i < 25; i++)\n {\n rj[i] = -(r_beta + an * (an - beta_p2) * rj[i - 1])\n / (anm1 * (an + beta_p1));\n anm1 = an;\n an = an + 1.0;\n }\n\n rg[0] = -ri[0] / alpha_p1;\n rg[1] = -rg[0] - 2.0 * r_alpha / (alpha_p2 * alpha_p2);\n\n an = 2.0;\n anm1 = 1.0;\n\n for (i = 2; i < 25; i++)\n {\n rg[i] = -(an * (an - alpha_p2) * rg[i - 1] - an * ri[i - 1]\n + anm1 * ri[i]) / (anm1 * (an + alpha_p1));\n anm1 = an;\n an = an + 1.0;\n }\n\n rh[0] = -rj[0] / beta_p1;\n rh[1] = -rh[0] - 2.0 * r_beta / (beta_p2 * beta_p2);\n\n an = 2.0;\n anm1 = 1.0;\n\n for (i = 2; i < 25; i++)\n {\n rh[i] = -(an * (an - beta_p2) * rh[i - 1] - an * rj[i - 1]\n + anm1 * rj[i]) / (anm1 * (an + beta_p1));\n anm1 = an;\n an = an + 1.0;\n }\n\n for (i = 1; i < 25; i += 2)\n {\n rj[i] *= -1;\n rh[i] *= -1;\n }\n}\n", "meta": {"hexsha": "f2573cdb1b5e016cf9519c58816a1a84126643ff", "size": 4379, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/integration/qmomo.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/qmomo.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/qmomo.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 22.4564102564, "max_line_length": 81, "alphanum_fraction": 0.5526375885, "num_tokens": 1560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5892963348853945}} {"text": "/* specfunc/legendre_poly.c\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#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n\n\n/* Calculate P_m^m(x) from the analytic result:\n * P_m^m(x) = (-1)^m (2m-1)!! (1-x^2)^(m/2) , m > 0\n * = 1 , m = 0\n */\nstatic double legendre_Pmm(int m, double x)\n{\n if(m == 0)\n {\n return 1.0;\n }\n else\n {\n double p_mm = 1.0;\n double root_factor = sqrt(1.0-x)*sqrt(1.0+x);\n double fact_coeff = 1.0;\n int i;\n for(i=1; i<=m; i++)\n {\n p_mm *= -fact_coeff * root_factor;\n fact_coeff += 2.0;\n }\n return p_mm;\n }\n}\n\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_legendre_P1_e(double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n {\n result->val = x;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_sf_legendre_P2_e(double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n {\n result->val = 0.5*(3.0*x*x - 1.0);\n result->err = GSL_DBL_EPSILON * (fabs(3.0*x*x) + 1.0);\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_sf_legendre_P3_e(double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n {\n result->val = 0.5*x*(5.0*x*x - 3.0);\n result->err = GSL_DBL_EPSILON * (fabs(result->val) + 0.5 * fabs(x) * (fabs(5.0*x*x) + 3.0));\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_sf_legendre_Pl_e(const int l, const double x, gsl_sf_result * result)\n{ \n /* CHECK_POINTER(result) */\n\n if(l < 0 || x < -1.0 || x > 1.0) {\n DOMAIN_ERROR(result);\n }\n else if(l == 0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(l == 1) {\n result->val = x;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(l == 2) {\n result->val = 0.5 * (3.0*x*x - 1.0);\n result->err = GSL_DBL_EPSILON * (fabs(3.0*x*x) + 1.0);\n /*result->err = 3.0 * GSL_DBL_EPSILON * fabs(result->val);\n removed this old bogus estimate [GJ]\n */\n return GSL_SUCCESS;\n }\n else if(x == 1.0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(x == -1.0) {\n result->val = ( GSL_IS_ODD(l) ? -1.0 : 1.0 );\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(l < 100000) {\n /* upward recurrence: l P_l = (2l-1) z P_{l-1} - (l-1) P_{l-2} */\n\n double p_ellm2 = 1.0; /* P_0(x) */\n double p_ellm1 = x; /* P_1(x) */\n double p_ell = p_ellm1;\n\n double e_ellm2 = GSL_DBL_EPSILON;\n double e_ellm1 = fabs(x)*GSL_DBL_EPSILON;\n double e_ell = e_ellm1;\n\n int ell;\n\n for(ell=2; ell <= l; ell++){\n p_ell = (x*(2*ell-1)*p_ellm1 - (ell-1)*p_ellm2) / ell;\n p_ellm2 = p_ellm1;\n p_ellm1 = p_ell;\n\n e_ell = 0.5*(fabs(x)*(2*ell-1.0) * e_ellm1 + (ell-1.0)*e_ellm2)/ell;\n e_ellm2 = e_ellm1;\n e_ellm1 = e_ell;\n }\n\n result->val = p_ell;\n result->err = e_ell + l*fabs(p_ell)*GSL_DBL_EPSILON;\n return GSL_SUCCESS;\n }\n else {\n /* Asymptotic expansion.\n * [Olver, p. 473]\n */\n double u = l + 0.5;\n double th = acos(x);\n gsl_sf_result J0;\n gsl_sf_result Jm1;\n int stat_J0 = gsl_sf_bessel_J0_e(u*th, &J0);\n int stat_Jm1 = gsl_sf_bessel_Jn_e(-1, u*th, &Jm1);\n double pre;\n double B00;\n double c1;\n\n /* B00 = 1/8 (1 - th cot(th) / th^2\n * pre = sqrt(th/sin(th))\n */\n if(th < GSL_ROOT4_DBL_EPSILON) {\n B00 = (1.0 + th*th/15.0)/24.0;\n pre = 1.0 + th*th/12.0;\n }\n else {\n double sin_th = sqrt(1.0 - x*x);\n double cot_th = x / sin_th;\n B00 = 1.0/8.0 * (1.0 - th * cot_th) / (th*th);\n pre = sqrt(th/sin_th);\n }\n\n c1 = th/u * B00;\n\n result->val = pre * (J0.val + c1 * Jm1.val);\n result->err = pre * (J0.err + fabs(c1) * Jm1.err);\n result->err += GSL_SQRT_DBL_EPSILON * fabs(result->val);\n\n return GSL_ERROR_SELECT_2(stat_J0, stat_Jm1);\n }\n}\n\n\nint\ngsl_sf_legendre_Pl_array(const int lmax, const double x, double * result_array)\n{\n /* CHECK_POINTER(result_array) */\n\n if(lmax < 0 || x < -1.0 || x > 1.0) {\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(lmax == 0) {\n result_array[0] = 1.0;\n return GSL_SUCCESS;\n }\n else if(lmax == 1) {\n result_array[0] = 1.0;\n result_array[1] = x;\n return GSL_SUCCESS;\n }\n else {\n /* upward recurrence: l P_l = (2l-1) z P_{l-1} - (l-1) P_{l-2} */\n\n double p_ellm2 = 1.0; /* P_0(x) */\n double p_ellm1 = x; /* P_1(x) */\n double p_ell = p_ellm1;\n int ell;\n\n result_array[0] = 1.0;\n result_array[1] = x;\n\n for(ell=2; ell <= lmax; ell++){\n p_ell = (x*(2*ell-1)*p_ellm1 - (ell-1)*p_ellm2) / ell;\n p_ellm2 = p_ellm1;\n p_ellm1 = p_ell;\n result_array[ell] = p_ell;\n }\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_sf_legendre_Pl_deriv_array(const int lmax, const double x, double * result_array, double * result_deriv_array)\n{\n int stat_array = gsl_sf_legendre_Pl_array(lmax, x, result_array);\n\n if(lmax >= 0) result_deriv_array[0] = 0.0;\n if(lmax >= 1) result_deriv_array[1] = 1.0;\n\n if(stat_array == GSL_SUCCESS)\n {\n int ell;\n\n if(fabs(x - 1.0)*(lmax+1.0)*(lmax+1.0) < GSL_SQRT_DBL_EPSILON)\n {\n /* x is near 1 */\n for(ell = 2; ell <= lmax; ell++)\n {\n const double pre = 0.5 * ell * (ell+1.0);\n result_deriv_array[ell] = pre * (1.0 - 0.25 * (1.0-x) * (ell+2.0)*(ell-1.0));\n }\n }\n else if(fabs(x + 1.0)*(lmax+1.0)*(lmax+1.0) < GSL_SQRT_DBL_EPSILON)\n {\n /* x is near -1 */\n for(ell = 2; ell <= lmax; ell++)\n {\n const double sgn = ( GSL_IS_ODD(ell) ? 1.0 : -1.0 ); /* derivative is odd in x for even ell */\n const double pre = sgn * 0.5 * ell * (ell+1.0);\n result_deriv_array[ell] = pre * (1.0 - 0.25 * (1.0+x) * (ell+2.0)*(ell-1.0));\n }\n }\n else\n {\n const double diff_a = 1.0 + x;\n const double diff_b = 1.0 - x;\n for(ell = 2; ell <= lmax; ell++)\n {\n result_deriv_array[ell] = - ell * (x * result_array[ell] - result_array[ell-1]) / (diff_a * diff_b);\n }\n }\n\n return GSL_SUCCESS;\n }\n else\n {\n return stat_array;\n }\n}\n\n\nint\ngsl_sf_legendre_Plm_e(const int l, const int m, const double x, gsl_sf_result * result)\n{\n /* If l is large and m is large, then we have to worry\n * about overflow. Calculate an approximate exponent which\n * measures the normalization of this thing.\n */\n const double dif = l-m;\n const double sum = l+m;\n const double t_d = ( dif == 0.0 ? 0.0 : 0.5 * dif * (log(dif)-1.0) );\n const double t_s = ( dif == 0.0 ? 0.0 : 0.5 * sum * (log(sum)-1.0) );\n const double exp_check = 0.5 * log(2.0*l+1.0) + t_d - t_s;\n\n /* CHECK_POINTER(result) */\n\n if(m < 0 || l < m || x < -1.0 || x > 1.0) {\n DOMAIN_ERROR(result);\n }\n else if(exp_check < GSL_LOG_DBL_MIN + 10.0){\n /* Bail out. */\n OVERFLOW_ERROR(result);\n }\n else {\n /* Account for the error due to the\n * representation of 1-x.\n */\n const double err_amp = 1.0 / (GSL_DBL_EPSILON + fabs(1.0-fabs(x)));\n\n /* P_m^m(x) and P_{m+1}^m(x) */\n double p_mm = legendre_Pmm(m, x);\n double p_mmp1 = x * (2*m + 1) * p_mm;\n\n if(l == m){\n result->val = p_mm;\n result->err = err_amp * 2.0 * GSL_DBL_EPSILON * fabs(p_mm);\n return GSL_SUCCESS;\n }\n else if(l == m + 1) {\n result->val = p_mmp1;\n result->err = err_amp * 2.0 * GSL_DBL_EPSILON * fabs(p_mmp1);\n return GSL_SUCCESS;\n }\n else{\n /* upward recurrence: (l-m) P(l,m) = (2l-1) z P(l-1,m) - (l+m-1) P(l-2,m)\n * start at P(m,m), P(m+1,m)\n */\n\n double p_ellm2 = p_mm;\n double p_ellm1 = p_mmp1;\n double p_ell = 0.0;\n int ell;\n\n for(ell=m+2; ell <= l; ell++){\n p_ell = (x*(2*ell-1)*p_ellm1 - (ell+m-1)*p_ellm2) / (ell-m);\n p_ellm2 = p_ellm1;\n p_ellm1 = p_ell;\n }\n\n result->val = p_ell;\n result->err = err_amp * (0.5*(l-m) + 1.0) * GSL_DBL_EPSILON * fabs(p_ell);\n\n return GSL_SUCCESS;\n }\n }\n}\n\n\nint\ngsl_sf_legendre_Plm_array(const int lmax, const int m, const double x, double * result_array)\n{\n /* If l is large and m is large, then we have to worry\n * about overflow. Calculate an approximate exponent which\n * measures the normalization of this thing.\n */\n const double dif = lmax-m;\n const double sum = lmax+m;\n const double t_d = ( dif == 0.0 ? 0.0 : 0.5 * dif * (log(dif)-1.0) );\n const double t_s = ( dif == 0.0 ? 0.0 : 0.5 * sum * (log(sum)-1.0) );\n const double exp_check = 0.5 * log(2.0*lmax+1.0) + t_d - t_s;\n\n /* CHECK_POINTER(result_array) */\n\n if(m < 0 || lmax < m || x < -1.0 || x > 1.0) {\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(m > 0 && (x == 1.0 || x == -1.0)) {\n int ell;\n for(ell=m; ell<=lmax; ell++) result_array[ell-m] = 0.0;\n return GSL_SUCCESS;\n }\n else if(exp_check < GSL_LOG_DBL_MIN + 10.0){\n /* Bail out. */\n GSL_ERROR (\"overflow\", GSL_EOVRFLW);\n }\n else {\n double p_mm = legendre_Pmm(m, x);\n double p_mmp1 = x * (2.0*m + 1.0) * p_mm;\n\n if(lmax == m){\n result_array[0] = p_mm;\n return GSL_SUCCESS;\n }\n else if(lmax == m + 1) {\n result_array[0] = p_mm;\n result_array[1] = p_mmp1;\n return GSL_SUCCESS;\n }\n else {\n double p_ellm2 = p_mm;\n double p_ellm1 = p_mmp1;\n double p_ell = 0.0;\n int ell;\n\n result_array[0] = p_mm;\n result_array[1] = p_mmp1;\n\n for(ell=m+2; ell <= lmax; ell++){\n p_ell = (x*(2.0*ell-1.0)*p_ellm1 - (ell+m-1)*p_ellm2) / (ell-m);\n p_ellm2 = p_ellm1;\n p_ellm1 = p_ell;\n result_array[ell-m] = p_ell;\n }\n\n return GSL_SUCCESS;\n }\n }\n}\n\n\nint\ngsl_sf_legendre_Plm_deriv_array(\n const int lmax, const int m, const double x,\n double * result_array,\n double * result_deriv_array)\n{\n if(m < 0 || m > lmax)\n {\n GSL_ERROR(\"m < 0 or m > lmax\", GSL_EDOM);\n }\n else if(m == 0)\n {\n /* It is better to do m=0 this way, so we can more easily\n * trap the divergent case which can occur when m == 1.\n */\n return gsl_sf_legendre_Pl_deriv_array(lmax, x, result_array, result_deriv_array);\n }\n else\n {\n int stat_array = gsl_sf_legendre_Plm_array(lmax, m, x, result_array);\n\n if(stat_array == GSL_SUCCESS)\n {\n int ell;\n\n if(m == 1 && (1.0 - fabs(x) < GSL_DBL_EPSILON))\n {\n /* This divergence is real and comes from the cusp-like\n * behaviour for m = 1. For example, P[1,1] = - Sqrt[1-x^2].\n */\n GSL_ERROR(\"divergence near |x| = 1.0 since m = 1\", GSL_EOVRFLW);\n }\n else if(m == 2 && (1.0 - fabs(x) < GSL_DBL_EPSILON))\n {\n /* m = 2 gives a finite nonzero result for |x| near 1 */\n if(fabs(x - 1.0) < GSL_DBL_EPSILON)\n {\n for(ell = m; ell <= lmax; ell++) result_deriv_array[ell-m] = -0.25 * x * (ell - 1.0)*ell*(ell+1.0)*(ell+2.0);\n }\n else if(fabs(x + 1.0) < GSL_DBL_EPSILON)\n {\n for(ell = m; ell <= lmax; ell++)\n {\n const double sgn = ( GSL_IS_ODD(ell) ? 1.0 : -1.0 );\n result_deriv_array[ell-m] = -0.25 * sgn * x * (ell - 1.0)*ell*(ell+1.0)*(ell+2.0);\n }\n }\n return GSL_SUCCESS;\n }\n else \n {\n /* m > 2 is easier to deal with since the endpoints always vanish */\n if(1.0 - fabs(x) < GSL_DBL_EPSILON)\n {\n for(ell = m; ell <= lmax; ell++) result_deriv_array[ell-m] = 0.0;\n return GSL_SUCCESS;\n }\n else\n {\n const double diff_a = 1.0 + x;\n const double diff_b = 1.0 - x;\n result_deriv_array[0] = - m * x / (diff_a * diff_b) * result_array[0];\n if(lmax-m >= 1) result_deriv_array[1] = (2.0 * m + 1.0) * (x * result_deriv_array[0] + result_array[0]);\n for(ell = m+2; ell <= lmax; ell++)\n {\n result_deriv_array[ell-m] = - (ell * x * result_array[ell-m] - (ell+m) * result_array[ell-1-m]) / (diff_a * diff_b);\n }\n return GSL_SUCCESS;\n }\n }\n }\n else\n {\n return stat_array;\n }\n }\n}\n\n\nint\ngsl_sf_legendre_sphPlm_e(const int l, int m, const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(m < 0 || l < m || x < -1.0 || x > 1.0) {\n DOMAIN_ERROR(result);\n }\n else if(m == 0) {\n gsl_sf_result P;\n int stat_P = gsl_sf_legendre_Pl_e(l, x, &P);\n double pre = sqrt((2.0*l + 1.0)/(4.0*M_PI));\n result->val = pre * P.val;\n result->err = pre * P.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_P;\n }\n else if(x == 1.0 || x == -1.0) {\n /* m > 0 here */\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else {\n /* m > 0 and |x| < 1 here */\n\n /* Starting value for recursion.\n * Y_m^m(x) = sqrt( (2m+1)/(4pi m) gamma(m+1/2)/gamma(m) ) (-1)^m (1-x^2)^(m/2) / pi^(1/4)\n */\n gsl_sf_result lncirc;\n gsl_sf_result lnpoch;\n double lnpre_val;\n double lnpre_err;\n gsl_sf_result ex_pre;\n double sr;\n const double sgn = ( GSL_IS_ODD(m) ? -1.0 : 1.0);\n const double y_mmp1_factor = x * sqrt(2.0*m + 3.0);\n double y_mm, y_mm_err;\n double y_mmp1, y_mmp1_err;\n gsl_sf_log_1plusx_e(-x*x, &lncirc);\n gsl_sf_lnpoch_e(m, 0.5, &lnpoch); /* Gamma(m+1/2)/Gamma(m) */\n lnpre_val = -0.25*M_LNPI + 0.5 * (lnpoch.val + m*lncirc.val);\n lnpre_err = 0.25*M_LNPI*GSL_DBL_EPSILON + 0.5 * (lnpoch.err + fabs(m)*lncirc.err);\n /* Compute exp(ln_pre) with error term, avoiding call to gsl_sf_exp_err BJG */\n ex_pre.val = exp(lnpre_val);\n ex_pre.err = 2.0*(sinh(lnpre_err) + GSL_DBL_EPSILON)*ex_pre.val;\n sr = sqrt((2.0+1.0/m)/(4.0*M_PI));\n y_mm = sgn * sr * ex_pre.val;\n y_mm_err = 2.0 * GSL_DBL_EPSILON * fabs(y_mm) + sr * ex_pre.err;\n y_mm_err *= 1.0 + 1.0/(GSL_DBL_EPSILON + fabs(1.0-x));\n y_mmp1 = y_mmp1_factor * y_mm;\n y_mmp1_err=fabs(y_mmp1_factor) * y_mm_err;\n\n if(l == m){\n result->val = y_mm;\n result->err = y_mm_err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(y_mm);\n return GSL_SUCCESS;\n }\n else if(l == m + 1) {\n result->val = y_mmp1;\n result->err = y_mmp1_err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(y_mmp1);\n return GSL_SUCCESS;\n }\n else{\n double y_ell = 0.0;\n double y_ell_err;\n int ell;\n\n /* Compute Y_l^m, l > m+1, upward recursion on l. */\n for(ell=m+2; ell <= l; ell++){\n const double rat1 = (double)(ell-m)/(double)(ell+m);\n const double rat2 = (ell-m-1.0)/(ell+m-1.0);\n const double factor1 = sqrt(rat1*(2.0*ell+1.0)*(2.0*ell-1.0));\n const double factor2 = sqrt(rat1*rat2*(2.0*ell+1.0)/(2.0*ell-3.0));\n y_ell = (x*y_mmp1*factor1 - (ell+m-1.0)*y_mm*factor2) / (ell-m);\n y_mm = y_mmp1;\n y_mmp1 = y_ell;\n\n y_ell_err = 0.5*(fabs(x*factor1)*y_mmp1_err + fabs((ell+m-1.0)*factor2)*y_mm_err) / fabs(ell-m);\n y_mm_err = y_mmp1_err;\n y_mmp1_err = y_ell_err;\n }\n\n result->val = y_ell;\n result->err = y_ell_err + (0.5*(l-m) + 1.0) * GSL_DBL_EPSILON * fabs(y_ell);\n\n return GSL_SUCCESS;\n }\n }\n}\n\n\nint\ngsl_sf_legendre_sphPlm_array(const int lmax, int m, const double x, double * result_array)\n{\n /* CHECK_POINTER(result_array) */\n\n if(m < 0 || lmax < m || x < -1.0 || x > 1.0) {\n GSL_ERROR (\"error\", GSL_EDOM);\n }\n else if(m > 0 && (x == 1.0 || x == -1.0)) {\n int ell;\n for(ell=m; ell<=lmax; ell++) result_array[ell-m] = 0.0;\n return GSL_SUCCESS;\n }\n else {\n double y_mm;\n double y_mmp1;\n\n if(m == 0) {\n y_mm = 0.5/M_SQRTPI; /* Y00 = 1/sqrt(4pi) */\n y_mmp1 = x * M_SQRT3 * y_mm;\n }\n else {\n /* |x| < 1 here */\n\n gsl_sf_result lncirc;\n gsl_sf_result lnpoch;\n double lnpre;\n const double sgn = ( GSL_IS_ODD(m) ? -1.0 : 1.0);\n gsl_sf_log_1plusx_e(-x*x, &lncirc);\n gsl_sf_lnpoch_e(m, 0.5, &lnpoch); /* Gamma(m+1/2)/Gamma(m) */\n lnpre = -0.25*M_LNPI + 0.5 * (lnpoch.val + m*lncirc.val);\n y_mm = sqrt((2.0+1.0/m)/(4.0*M_PI)) * sgn * exp(lnpre);\n y_mmp1 = x * sqrt(2.0*m + 3.0) * y_mm;\n }\n\n if(lmax == m){\n result_array[0] = y_mm;\n return GSL_SUCCESS;\n }\n else if(lmax == m + 1) {\n result_array[0] = y_mm;\n result_array[1] = y_mmp1;\n return GSL_SUCCESS;\n }\n else{\n double y_ell;\n int ell;\n\n result_array[0] = y_mm;\n result_array[1] = y_mmp1;\n\n /* Compute Y_l^m, l > m+1, upward recursion on l. */\n for(ell=m+2; ell <= lmax; ell++){\n const double rat1 = (double)(ell-m)/(double)(ell+m);\n const double rat2 = (ell-m-1.0)/(ell+m-1.0);\n const double factor1 = sqrt(rat1*(2*ell+1)*(2*ell-1));\n const double factor2 = sqrt(rat1*rat2*(2*ell+1)/(2*ell-3));\n y_ell = (x*y_mmp1*factor1 - (ell+m-1)*y_mm*factor2) / (ell-m);\n y_mm = y_mmp1;\n y_mmp1 = y_ell;\n result_array[ell-m] = y_ell;\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_sf_legendre_sphPlm_deriv_array(\n const int lmax, const int m, const double x,\n double * result_array,\n double * result_deriv_array)\n{\n if(m < 0 || lmax < m || x < -1.0 || x > 1.0)\n {\n GSL_ERROR (\"domain\", GSL_EDOM);\n }\n else if(m == 0)\n {\n /* m = 0 is easy to trap */\n const int stat_array = gsl_sf_legendre_Pl_deriv_array(lmax, x, result_array, result_deriv_array);\n int ell;\n for(ell = 0; ell <= lmax; ell++)\n {\n const double prefactor = sqrt((2.0 * ell + 1.0)/(4.0*M_PI));\n result_array[ell] *= prefactor;\n result_deriv_array[ell] *= prefactor;\n }\n return stat_array;\n }\n else if(m == 1)\n {\n /* Trapping m = 1 is necessary because of the possible divergence.\n * Recall that this divergence is handled properly in ..._Plm_deriv_array(),\n * and the scaling factor is not large for small m, so we just scale.\n */\n const int stat_array = gsl_sf_legendre_Plm_deriv_array(lmax, m, x, result_array, result_deriv_array);\n int ell;\n for(ell = 1; ell <= lmax; ell++)\n {\n const double prefactor = sqrt((2.0 * ell + 1.0)/(ell + 1.0) / (4.0*M_PI*ell));\n result_array[ell-1] *= prefactor;\n result_deriv_array[ell-1] *= prefactor;\n }\n return stat_array;\n }\n else\n {\n /* as for the derivative of P_lm, everything is regular for m >= 2 */\n\n int stat_array = gsl_sf_legendre_sphPlm_array(lmax, m, x, result_array);\n\n if(stat_array == GSL_SUCCESS)\n {\n int ell;\n\n if(1.0 - fabs(x) < GSL_DBL_EPSILON)\n {\n for(ell = m; ell <= lmax; ell++) result_deriv_array[ell-m] = 0.0;\n return GSL_SUCCESS;\n }\n else\n {\n const double diff_a = 1.0 + x;\n const double diff_b = 1.0 - x;\n result_deriv_array[0] = - m * x / (diff_a * diff_b) * result_array[0];\n if(lmax-m >= 1) result_deriv_array[1] = sqrt(2.0 * m + 3.0) * (x * result_deriv_array[0] + result_array[0]);\n for(ell = m+2; ell <= lmax; ell++)\n {\n const double c1 = sqrt(((2.0*ell+1.0)/(2.0*ell-1.0)) * ((double)(ell-m)/(double)(ell+m)));\n result_deriv_array[ell-m] = - (ell * x * result_array[ell-m] - c1 * (ell+m) * result_array[ell-1-m]) / (diff_a * diff_b);\n }\n return GSL_SUCCESS;\n }\n }\n else\n {\n return stat_array;\n }\n }\n}\n\nint\ngsl_sf_legendre_array_size(const int lmax, const int m)\n{\n return lmax-m+1;\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_legendre_P1(const double x)\n{\n EVAL_RESULT(gsl_sf_legendre_P1_e(x, &result));\n}\n\ndouble gsl_sf_legendre_P2(const double x)\n{\n EVAL_RESULT(gsl_sf_legendre_P2_e(x, &result));\n}\n\ndouble gsl_sf_legendre_P3(const double x)\n{\n EVAL_RESULT(gsl_sf_legendre_P3_e(x, &result));\n}\n\ndouble gsl_sf_legendre_Pl(const int l, const double x)\n{\n EVAL_RESULT(gsl_sf_legendre_Pl_e(l, x, &result));\n}\n\ndouble gsl_sf_legendre_Plm(const int l, const int m, const double x)\n{\n EVAL_RESULT(gsl_sf_legendre_Plm_e(l, m, x, &result));\n}\n\ndouble gsl_sf_legendre_sphPlm(const int l, const int m, const double x)\n{\n EVAL_RESULT(gsl_sf_legendre_sphPlm_e(l, m, x, &result));\n}\n\n", "meta": {"hexsha": "654a4b04458ff55a95cad5a424cd6a1824a84f55", "size": 21080, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/specfunc/legendre_poly.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/specfunc/legendre_poly.c", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/specfunc/legendre_poly.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 27.0256410256, "max_line_length": 131, "alphanum_fraction": 0.5628083491, "num_tokens": 7561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5892233620073762}} {"text": "\n/* \n** gsl routines for double data type\n**\n** G.Lohmann, July 2004\n*/\n\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#define dvset gsl_vector_set \n#define dvget gsl_vector_get \n#define dmset gsl_matrix_set \n#define dmget gsl_matrix_get\n\n#define fvset gsl_vector_float_set \n#define fvget gsl_vector_float_get \n#define fmset gsl_matrix_float_set \n#define fmget gsl_matrix_float_get\n\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\n\n/*\n** y = Ax\n*/\ngsl_vector *\ndmat_x_vector(gsl_matrix *A, gsl_vector *x, gsl_vector *y)\n{\n int i,j,nrows,ncols;\n double *ptr1,*ptr2,*ptr3,sum;\n\n nrows = A->size1;\n ncols = A->size2;\n\n if (y == NULL) {\n y = gsl_vector_alloc (nrows);\n }\n\n if (x->size != ncols || y->size != nrows) {\n fprintf(stderr,\" dmat_x_vector: incongruent dimensions\\n\");\n exit(0);\n }\n\n ptr1 = A->data;\n ptr3 = y->data;\n\n for (i=0; idata;\n for (j=0; jsize1;\n ncols = A->size2;\n\n if (y == NULL) {\n y = gsl_vector_alloc (nrows);\n }\n\n if (x->size != ncols || y->size != nrows) {\n fprintf(stderr,\" dmat_x_vector: incongruent dimensions\\n\");\n exit(0);\n }\n\n ptr1 = A->data;\n ptr3 = y->data;\n\n for (i=0; idata;\n for (j=0; jsize;\n if (y->size != n) {\n fprintf(stderr,\" dskalarproduct: incongruent vector sizes: %d %d\",n,y->size);\n exit(0);\n }\n\n ptr1 = x->data;\n ptr2 = y->data;\n sum = 0;\n for (i=0; isize1;\n n = A->size2;\n\n if (B == NULL) {\n B = gsl_matrix_alloc (n,m);\n }\n else if (B->size1 != n || B->size2 != m) {\n gsl_matrix_free(B);\n B = gsl_matrix_alloc (n, m);\n }\n\n if (U == NULL) {\n U = gsl_matrix_alloc (m, n);\n V = gsl_matrix_alloc (n, n);\n w = gsl_vector_alloc (n);\n }\n else if (U->size1 != m || w->size != n) {\n gsl_matrix_free(U);\n gsl_matrix_free(V);\n gsl_vector_free(w);\n U = gsl_matrix_alloc (m, n);\n V = gsl_matrix_alloc (n, n);\n w = gsl_vector_alloc (n);\n }\n\n /* singular value decomposition */\n gsl_matrix_memcpy(U,A);\n gsl_linalg_SV_decomp_jacobi(U,V,w);\n\n gsl_matrix_set_zero(B);\n\n for (k=0; k 1.0e-6) {\n x = dmget(B,k,l);\n\t x += dmget(V,k,j)*dmget(U,l,j)/u;\n dmset(B,k,l,x);\n }\n }\n }\n }\n return B;\n}\n\n\n\n\n/*\n** C = A x B^T\n*/\ngsl_matrix *\ndmat_x_matT(gsl_matrix *A,gsl_matrix *B,gsl_matrix *C)\n{\n int i,j,k;\n int n,r,m;\n double *ptr1,*ptr2,*ptr3,sum;\n\n\n n = A->size1;\n r = A->size2;\n m = B->size1;\n\n if (B->size2 != r) {\n fprintf(stderr,\"fmat_x_matT: incongruent matrix dimensions (A,B).\\n\");\n exit(0);\n }\n\n if (C == NULL) {\n C = gsl_matrix_alloc (n,m);\n }\n else {\n if (C->size1 != n || C->size2 != m) {\n fprintf(stderr,\"fmat_x_matT: incongruent matrix dimensions(C).\\n\");\n exit(0);\n }\n }\n ptr1 = C->data;\n for (i=0; isize1;\n r = A->size2;\n m = B->size2;\n\n if (B->size1 != n) {\n fprintf(stderr,\"dmatT_x_mat: incongruent matrix dimensions (A,B).\\n\");\n exit(0);\n }\n\n if (C == NULL) {\n C = gsl_matrix_alloc (r,m);\n }\n else {\n if (C->size1 != r || C->size2 != m) {\n fprintf(stderr,\"dmatT_x_mat: incongruent matrix dimensions (C, %d %d, %d %d).\\n\",\n\t C->size1,C->size2,r,m);\n exit(0);\n }\n }\n\n ptr1 = C->data;\n for (i=0; itda;\n\tptr3 += B->tda;\n }\n *ptr1++ = sum;\n }\n }\n\n return C;\n}\n\n\n\n\n\n/*\n** C = A x B\n*/\ngsl_matrix *\ndmat_x_mat(gsl_matrix *A,gsl_matrix *B,gsl_matrix *C)\n{\n int i,j,k,m,n,r;\n int nrowsA,ncolsA;\n int nrowsB,ncolsB;\n int nrowsC,ncolsC;\n double *ptr1,*ptr2,*ptr3,sum;\n\n \n nrowsA = A->size1;\n ncolsA = A->size2;\n\n nrowsB = B->size1;\n ncolsB = B->size2;\n\n if (C == NULL)\n C = gsl_matrix_alloc (nrowsA,ncolsB);\n \n\n nrowsC = C->size1;\n ncolsC = C->size2;\n \n if (ncolsA != nrowsB || nrowsA != nrowsC || ncolsB != ncolsC) {\n fprintf(stderr,\"dmat_x_mat: incongruent matrix dimensions.\\n\");\n exit(0);\n }\n\n m = A->size1;\n n = A->size2;\n r = B->size2;\n\n ptr1 = C->data;\n\n for (i=0; itda;\n }\n *ptr1++ = sum;\n }\n }\n return C;\n}\n\n\n\ngsl_matrix *\ndtranspose(gsl_matrix *A,gsl_matrix *B)\n{\n int i,j,n,m;\n\n n = A->size1;\n m = A->size2;\n \n if (B == NULL) {\n B = gsl_matrix_alloc(m,n);\n }\n else if (B->size1 != m || B->size2 != n) {\n gsl_matrix_free(B);\n B = gsl_matrix_alloc(m,n);\n }\n\n for (i=0; i\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"ccl.h\"\n\n// Global variable to hold the neutrino phase-space spline\ngsl_spline* nu_spline = NULL;\n\n// these are NOT adjustable\n// this phase space integral is only done once and the following is accurate\n// enough according to tests done by the devs\n/**\n * Absolute precision in neutrino root finding\n */\n#define GSL_EPSABS_NU 1E-7\n\n/**\n * Relative precision in neutrino root finding\n */\n#define GSL_EPSREL_NU 1E-7\n\n/**\n * Number of iterations for neutrino root finding\n */\n#define GSL_N_ITERATION_NU 1000\n\n\n\n/* ------- ROUTINE: nu_integrand ------\nINPUTS: x: dimensionless momentum, *r: pointer to a dimensionless mass / temperature\nTASK: Integrand of phase-space massive neutrino integral\n*/\nstatic double nu_integrand(double x, void *r) {\n double rat = *((double*)(r));\n double x2 = x*x;\n return sqrt(x2 + rat*rat) / (exp(x)+1.0) * x2;\n}\n\n/* ------- ROUTINE: ccl_calculate_nu_phasespace_spline ------\nTASK: Get the spline of the result of the phase-space integral required for massive neutrinos.\n*/\n\ngsl_spline* calculate_nu_phasespace_spline(int *status) {\n int N = CCL_NU_MNUT_N;\n double *mnut = NULL;\n double *y = NULL;\n gsl_spline* spl = NULL;\n gsl_integration_cquad_workspace * workspace = NULL;\n int stat = 0, gslstatus;\n gsl_function F;\n\n mnut = ccl_linear_spacing(log(CCL_NU_MNUT_MIN), log(CCL_NU_MNUT_MAX), N);\n y = malloc(sizeof(double)*CCL_NU_MNUT_N);\n if ((y == NULL) || (mnut == NULL)) {\n // Not setting a status_message here because we can't easily pass a\n // cosmology to this function - message printed in ccl_error.c.\n *status = CCL_ERROR_NU_INT;\n }\n\n if (*status == 0) {\n workspace = gsl_integration_cquad_workspace_alloc(GSL_N_ITERATION_NU);\n if (workspace == NULL)\n *status = CCL_ERROR_NU_INT;\n }\n\n if (*status == 0) {\n F.function = &nu_integrand;\n for (int i=0; i < CCL_NU_MNUT_N; i++) {\n double mnut_ = exp(mnut[i]);\n F.params = &(mnut_);\n gslstatus = gsl_integration_cquad(&F, 0, 1000.0,\n GSL_EPSABS_NU,\n GSL_EPSREL_NU,\n workspace, &y[i], NULL, NULL);\n if (gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_neutrinos.c: calculate_nu_phasespace_spline():\");\n stat |= gslstatus;\n }\n }\n\n double renorm = 1./y[0];\n for (int i=0; i < CCL_NU_MNUT_N; i++)\n y[i] *= renorm;\n\n if (stat) {\n *status = CCL_ERROR_NU_INT;\n }\n }\n\n if (*status == 0) {\n spl = gsl_spline_alloc(gsl_interp_akima, CCL_NU_MNUT_N);\n if (spl == NULL)\n *status = CCL_ERROR_NU_INT;\n }\n\n if (*status == 0) {\n stat |= gsl_spline_init(spl, mnut, y, CCL_NU_MNUT_N);\n if (stat) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_neutrinos.c: calculate_nu_phasespace_spline():\");\n *status = CCL_ERROR_NU_INT;\n }\n }\n\n // Check for errors in creating the spline\n if (stat || (*status)) {\n // Not setting a status_message here because we can't easily pass a\n // cosmology to this function - message printed in ccl_error.c.\n *status = CCL_ERROR_NU_INT;\n gsl_spline_free(spl);\n }\n\n gsl_integration_cquad_workspace_free(workspace);\n free(mnut);\n free(y);\n\n return spl;\n}\n\n/* ------- ROUTINE: ccl_nu_phasespace_intg ------\nINPUTS: mnuOT: the dimensionless mass / temperature of a single massive neutrino\nTASK: Get the value of the phase space integral at mnuOT\n*/\ndouble nu_phasespace_intg(double mnuOT, int* status)\n{\n // Check if the global variable for the phasespace spline has been defined yet:\n if (nu_spline == NULL)\n nu_spline = calculate_nu_phasespace_spline(status);\n\n if (*status) {\n return NAN;\n }\n\n double integral_value = 0.;\n\n // First check the cases where we are in the limits.\n if (mnuOT < CCL_NU_MNUT_MIN)\n return 7./8.;\n else if (mnuOT > CCL_NU_MNUT_MAX)\n return 0.2776566337 * mnuOT;\n\n int gslstatus = gsl_spline_eval_e(nu_spline, log(mnuOT), NULL, &integral_value);\n if (gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_neutrinos.c: nu_phasespace_intg():\");\n *status |= gslstatus;\n }\n return integral_value * 7./8.;\n}\n\n/* -------- ROUTINE: Omeganuh2 ---------\nINPUTS: a: scale factor, Nnumass: number of massive neutrino species,\n mnu: total mass in eV of neutrinos, T_CMB: CMB temperature, status: pointer to status integer.\nTASK: Compute Omeganu * h^2 as a function of time.\n!! To all practical purposes, Neff is simply N_nu_mass !!\n*/\ndouble ccl_Omeganuh2 (double a, int N_nu_mass, double* mnu, double T_CMB, int* status) {\n double Tnu, a4, prefix_massless, mnuone, OmNuh2;\n double Tnu_eff, mnuOT, intval, prefix_massive;\n double total_mass; // To check if this is the massless or massive case.\n\n // First check if N_nu_mass is 0\n if (N_nu_mass == 0) return 0.0;\n\n Tnu = T_CMB*pow(4./11.,1./3.);\n a4 = a*a*a*a;\n // Check if mnu=0. We assume that in the massless case mnu is a\n // pointer to a single element and that element is 0. This should in principle never be called.\n if (mnu[0] < 0.00017) { // Limit taken from Lesgourges et al. 2012\n prefix_massless = NU_CONST * Tnu * Tnu * Tnu * Tnu;\n return N_nu_mass*prefix_massless*7./8./a4;\n }\n\n // And the remaining massive case.\n // Tnu_eff is used in the massive case because CLASS uses an effective\n // temperature of nonLCDM components to match to mnu / Omeganu =93.14eV. Tnu_eff = T_ncdm * T_CMB = 0.71611 * T_CMB\n Tnu_eff = Tnu * ccl_constants.TNCDM / (pow(4./11.,1./3.));\n\n // Define the prefix using the effective temperature (to get mnu / Omega = 93.14 eV) for the massive case:\n prefix_massive = NU_CONST * Tnu_eff * Tnu_eff * Tnu_eff * Tnu_eff;\n\n OmNuh2 = 0.; // Initialize to 0 - we add to this for each massive neutrino species.\n for(int i=0; i < N_nu_mass; i++) {\n // Get mass over T (mass (eV) / ((kb eV/s/K) Tnu_eff (K))\n // This returns the density normalized so that we get nuh2 at a=0\n mnuOT = mnu[i] / (Tnu_eff/a) * (ccl_constants.EV_IN_J / (ccl_constants.KBOLTZ));\n\n // Get the value of the phase-space integral\n intval = nu_phasespace_intg(mnuOT, status);\n OmNuh2 = intval*prefix_massive/a4 + OmNuh2;\n }\n\n return OmNuh2;\n}\n\n/* -------- ROUTINE: Omeganuh2_to_Mnu ---------\nINPUTS: OmNuh2: neutrino mass density today Omeganu * h^2,\n label: how you want to split up the masses, see ccl_neutrinos.h for options,\n T_CMB: CMB temperature, status: pointer to status integer.\nTASK: Given Omeganuh2 today, the method of splitting into masses, and the temperature of the\n CMB, output a pointer to the array of neutrino masses (may be length 1 if label asks for sum)\n*/\ndouble* ccl_nu_masses(double OmNuh2, ccl_neutrino_mass_splits mass_split,\n double T_CMB, int* status) {\n double sumnu;\n double *mnu = NULL;\n\n sumnu = 93.14 * OmNuh2;\n\n // Now split the sum up into three masses depending on the label given:\n if (mass_split == ccl_nu_normal) {\n mnu = malloc(3*sizeof(double));\n if (mnu == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n\n if (*status == 0) {\n // See CCL note for how we get these expressions for the neutrino masses in\n // normal and inverted hierarchy.\n mnu[0] = (\n 2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5)\n - 0.25 * ccl_constants.DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. *\n ccl_constants.DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5)));\n mnu[1] = (\n 2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5)\n + 0.25 * ccl_constants.DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. *\n ccl_constants.DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5)));\n mnu[2] = (\n -1./3. * sumnu + 1./3 * pow(-6. * ccl_constants.DELTAM12_sq +\n 12. * ccl_constants.DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5));\n\n if (mnu[0] < 0 || mnu[1] < 0 || mnu[2] < 0) {\n // The user has provided a sum that is below the physical limit.\n if (sumnu < 1e-14) {\n mnu[0] = 0.;\n mnu[1] = 0.;\n mnu[2] = 0.;\n }\n else {\n *status = CCL_ERROR_MNU_UNPHYSICAL;\n ccl_raise_warning(\n *status,\n \"CCL_ERROR_MNU_UNPHYSICAL: Sum of neutrinos masses for this Omeganu \"\n \"value is incompatible with the requested mass hierarchy.\");\n }\n }\n }\n }\n else if (mass_split == ccl_nu_inverted) {\n mnu = malloc(3*sizeof(double));\n if (mnu == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n\n if (*status == 0) {\n mnu[0] = (\n 2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_neg + 4. * sumnu * sumnu, 0.5)\n - 0.25 * ccl_constants.DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. *\n ccl_constants.DELTAM13_sq_neg + 4. * sumnu * sumnu, 0.5)));\n mnu[1] = (\n 2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_neg + 4. * sumnu*sumnu, 0.5)\n + 0.25 * ccl_constants.DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. *\n ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_neg + 4. * sumnu*sumnu, 0.5)));\n mnu[2] = (\n -1./3. * sumnu + 1./3 * pow(-6. * ccl_constants.DELTAM12_sq +\n 12. * ccl_constants.DELTAM13_sq_neg + 4. * sumnu*sumnu, 0.5));\n\n if (mnu[0] < 0 || mnu[1] < 0 || mnu[2] < 0) {\n // The user has provided a sum that is below the physical limit.\n if (sumnu < 1e-14) {\n mnu[0] = 0.;\n mnu[1] = 0.;\n mnu[2] = 0.;;\n }\n else {\n *status = CCL_ERROR_MNU_UNPHYSICAL;\n ccl_raise_warning(\n *status,\n \"CCL_ERROR_MNU_UNPHYSICAL: Sum of neutrinos masses for this Omeganu \"\n \"value is incompatible with the requested mass hierarchy.\");\n }\n }\n }\n }\n else if (mass_split == ccl_nu_equal) {\n mnu = malloc(3*sizeof(double));\n if (mnu == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n\n if (*status == 0) {\n mnu[0] = sumnu/3.;\n mnu[1] = sumnu/3.;\n mnu[2] = sumnu/3.;\n }\n }\n else if (mass_split == ccl_nu_sum) {\n mnu = malloc(sizeof(double));\n if (mnu == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n\n if (*status == 0) {\n mnu[0] = sumnu;\n }\n }\n else {\n *status = CCL_ERROR_MNU_UNPHYSICAL;\n ccl_raise_warning(\n *status,\n \"mass option = %d not yet supported!\", mass_split);\n }\n\n return mnu;\n}\n\n\n#undef GSL_EPSABS_NU\n#undef GSL_EPSREL_NU\n#undef GSL_N_ITERATION_NU\n", "meta": {"hexsha": "15d0cd7534b6aebf0c05ec450a301da391e62190", "size": 10966, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_neutrinos.c", "max_stars_repo_name": "benediktdiemer/CCL", "max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "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_neutrinos.c", "max_issues_repo_name": "benediktdiemer/CCL", "max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "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_neutrinos.c", "max_forks_repo_name": "benediktdiemer/CCL", "max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z", "avg_line_length": 33.5351681957, "max_line_length": 131, "alphanum_fraction": 0.6266642349, "num_tokens": 3582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5891477609454023}} {"text": "#include \n#include \n#include \n#include \n#include \"compearth.h\"\n#ifdef COMPEARTH_USE_MKL\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#pragma clang diagnostic ignored \"-Wstrict-prototypes\"\n#endif\n#include \n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include \n#endif\n\n/*!\n * @brief Computes the omega angles between two moment tensors.\n *\n * @param[in] nmt1 Number of moment tensors in M1. This can be 1 otherwise\n * it must be equal to nmt2. If it is 1 then the angle will\n * be between M1 and all the moment tensors in M2.\n * @param[in] M1 First array of moment tensors. M1 is packed\n * \\f$ M = \\{M_{11} M_{22} M_{33} M_{12} M_{13} M_{23}\\} \\f$.\n * This is an array of dimension [6 x nmt1] with leading\n * dimension 6.\n * @param[in] nmt2 Number of moment tensors in M2. This can be 1 otherwise\n * it must be equal to nmt1. If it is 1 then the angle will\n * be between M2 and all the moment tensors in M1.\n * @param[in] M2 Second array of moment tensors. M2 is packed\n * \\f$ M = \\{M_{11} M_{22} M_{33} M_{12} M_{13} M_{23}\\} \\f$.\n * This is an array of dimension [6 x nmt2] with leading\n * dimension 6.\n *\n * @param[out] omega This is a measure between two moment tensors and combines\n * differences in eigenvalues (source types) and orientation\n * but not magnitude.\n * This is an array of dimension [MAX(nmt1, nmt2)].\n *\n * @author Carl Tape and translated to C by Ben Baker\n *\n * @copyright MIT\n *\n */\nint compearth_CMT2omega(const int nmt1, const double *__restrict__ M1,\n const int nmt2, const double *__restrict__ M2,\n double *__restrict__ omega)\n{\n double Mwork[6*CE_CHUNKSIZE] __attribute__((aligned(64)));\n int ierr, imt, nmtLoc;\n const double pi180i = 180.0/M_PI;\n ierr = 0;\n if (nmt1 < 1 || M1 == NULL || nmt2 < 1 || M2 == NULL || omega == NULL)\n {\n if (nmt1 < 1)\n {\n fprintf(stderr, \"%s: Error nmt1 must be positive\\n\", __func__);\n }\n if (nmt2 < 1)\n {\n fprintf(stderr, \"%s: Error nmt2 must be positive\\n\", __func__);\n }\n if (M1 == NULL){fprintf(stderr, \"%s: Error M1 is NULL\\n\", __func__);}\n if (M2 == NULL){fprintf(stderr, \"%s: Error M2 is NULL\\n\", __func__);}\n if (omega == NULL)\n {\n fprintf(stderr, \"%s: Error omega is NULL\\n\", __func__);\n }\n return -1;\n }\n // Straight compuation\n if (nmt1 == nmt2)\n {\n ierr = compearth_angleMT(nmt1, M1, M2, omega);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Error computing angleMT 1\\n\", __func__);\n }\n // Convert to degrees\n cblas_dscal(nmt1, pi180i, omega, 1);\n return ierr; \n }\n else\n {\n if (nmt1 == 1 || nmt2 == 1)\n {\n // Copy nmt1 and repeat computation with it\n if (nmt1 == 1)\n {\n for (imt=0; imt\n#include \n#include \n#include \n#include \n#include \n#include \n\ndouble globx;\n\ndouble analytic(double w0, double t);\n\ndouble spring_euler(double w0, double x);\nvoid test_euler(GtkWidget *darea);\n\nint func(double t, const double x[], double f[], void *params);\nint jac(double t, const double x[], double *dfdy, double dfdt[], void *params);\nint test_gsl(GtkWidget *darea);\n\nvoid do_drawing(cairo_t *cr);\ngboolean on_draw_event(GtkWidget *widget, cairo_t *cr, gpointer user_data);\n\ngboolean terminate(GThread *thread);\n\nvoid *thread_func(GtkWidget *entry) {\n //test_euler(entry);\n test_gsl(entry);\n\n gdk_threads_add_idle((GSourceFunc)terminate, g_thread_self());\n return NULL;\n}\n\nint main(int argc, char *argv[]) {\n\tGtkWidget *window;\n\tGtkWidget *darea;\n\n gtk_init(&argc, &argv);\n\n\twindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n\n\tdarea = gtk_drawing_area_new();\n\tgtk_container_add(GTK_CONTAINER(window), darea);\n\n\tg_signal_connect(G_OBJECT(darea), \"draw\", G_CALLBACK(on_draw_event), NULL); \n\tg_signal_connect(window, \"destroy\",\tG_CALLBACK(gtk_main_quit), NULL); \n\t \n\tgtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);\n\tgtk_window_set_default_size(GTK_WINDOW(window), 400, 300); \n\tgtk_window_set_title(GTK_WINDOW(window), \"Spring simulation\");\n\n\tgtk_widget_show_all(window);\n\n \tg_thread_new(\"eval\", (GThreadFunc)thread_func, darea);\n\n\tgtk_main();\n\n\treturn 0;\t\n}\n\ndouble analytic(double w0, double t) {\n\treturn cos(w0 * t);\n}\n\n// euler\n\ndouble spring_euler(double w0, double x) {\n\treturn -w0 * w0 * x;\n} \n\nvoid test_euler(GtkWidget *darea) {\n\tconst int n = 1000;\n\n\t// x - position\n\t// v - speed\n\t// t - time\n\t// dt - step\n\t// w0 = sqrt(k/m)\n\tdouble x[n], v[n], t[n], dt;\n\t\n\tconst double w0 = 1.0;\n\tx[0] = 1.0; v[0] = 0.0; t[0] = 0.0;\n\tdt = 0.05; \n\n\tint i;\n\tfor (i = 0; i < n - 1 ; i++) {\n\t\tx[i+1] = x[i] + v[i] * dt;\n\t\tv[i+1] = v[i] + spring_euler(w0, x[i]) * dt;\n\t\tt[i+1] = t[i] + dt;\n\t}\n\n\tfor (i = 0; i < n; i++) {\n\t\t// draw\n\t\tglobx = x[i];\n\t\tgtk_widget_queue_draw(darea);\n\t\tprintf(\"t: %f\\tx: %f\\tanalytic: \\t%f\\n\", t[i], x[i], analytic(w0, t[i])); \n\t\tg_usleep(10000); \n\t}\n}\n\n// gsl\n\nint func(double t, const double x[], double f[], void *params) {\n\t// x' = v\n\t// v' = -w0^2 * x\n\tdouble w0 = *(double *) params;\n\tf[0] = x[1];\n\tf[1] = -w0 * w0 * x[0];\n\treturn GSL_SUCCESS;\n}\n\nint jac(double t, const double x[], double *dfdy, double dfdt[], void *params) {\n\tdouble w0 = *(double *)params;\n\tgsl_matrix_view dfdy_mat = gsl_matrix_view_array(dfdy, 2, 2);\n\tgsl_matrix * m = &dfdy_mat.matrix; \n\tgsl_matrix_set(m, 0, 0, 0.0);\n\tgsl_matrix_set(m, 0, 1, 1.0);\n\tgsl_matrix_set(m, 1, 0, -w0 * w0);\n\tgsl_matrix_set(m, 1, 1, 0.0);\n\tdfdt[0] = 0.0;\n\tdfdt[1] = 0.0;\n\treturn GSL_SUCCESS;\n}\n\nint test_gsl(GtkWidget *darea) {\n\tdouble w0 = 1.0;\n\tgsl_odeiv2_system sys = { func, jac, 2, &w0 };\n\n\tgsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new(&sys, gsl_odeiv2_step_rk4, 0.05, 1e-6, 1e-6);\n\n\tdouble t = 0.0;\n\tdouble x[2] = { 1.0, 0.0 };\n\tint i, s;\n\n\tfor (i = 0; i < 1000; i++) {\n\t\ts = gsl_odeiv2_driver_apply_fixed_step(d, &t, 0.05, 1, x);\n\n\t\tif (s != GSL_SUCCESS) {\n\t\t\tprintf (\"error: driver returned %d\\n\", s);\n\t\t\tbreak;\n\t\t}\n\n\t\t// draw\n\t\tglobx = x[0];\n\t\tgtk_widget_queue_draw(darea);\n\t\tprintf(\"t: %.4f\\tanalytic: %.8f\\tx:%.8f\\n\", t, analytic(w0, t), x[0]);\n\t\tg_usleep(10000); \n\t}\n\n\tgsl_odeiv2_driver_free(d);\n\treturn s;\n}\n\n// drawing\n\ngboolean on_draw_event(GtkWidget *widget, cairo_t *cr, gpointer user_data) {\n\tdo_drawing(cr);\n\t\n\treturn FALSE;\n}\n\nvoid do_drawing(cairo_t *cr) {\n\tcairo_set_source_rgb(cr, 0, 0, 0);\n\tcairo_set_line_width(cr, 1);\n\n\tint k;\n\tint prevy = 0;\n\tcairo_move_to(cr, 200, 0);\n\tfor (k = 0; k < 20; k++) {\n\t\tint j = k % 2 == 0 ? -1 : 1;\n\t\tcairo_line_to(cr, 200 + j * 20, k*5*(globx + 1) + prevy);\n\t\tprevy = k*2;\n\t}\n\tcairo_line_to(cr, 200, 100*(globx + 1) + prevy);\n\t//cairo_stroke(cr); \n\tcairo_rectangle(cr, 180, 100*(globx + 1) + prevy, 40, 40);\n\t//cairo_stroke_preserve(cr); \n\t//cairo_fill(cr);\n\tcairo_stroke(cr);\n}\n\n// threads\n\ngboolean terminate(GThread *thread) {\n g_thread_join(thread);\n\n //g_thread_unref(thread);\n\n return FALSE;\n}", "meta": {"hexsha": "faa73b5080b7221e4403bbf31895fb2feea373e1", "size": 4216, "ext": "c", "lang": "C", "max_stars_repo_path": "spring_ode.c", "max_stars_repo_name": "Hoobie/spring-simulation", "max_stars_repo_head_hexsha": "f21cd62d512bb55f1c29fe3e310f4a9352284d93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T06:58:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T06:58:39.000Z", "max_issues_repo_path": "spring_ode.c", "max_issues_repo_name": "Hoobie/spring-simulation", "max_issues_repo_head_hexsha": "f21cd62d512bb55f1c29fe3e310f4a9352284d93", "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": "spring_ode.c", "max_forks_repo_name": "Hoobie/spring-simulation", "max_forks_repo_head_hexsha": "f21cd62d512bb55f1c29fe3e310f4a9352284d93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-15T09:06:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-15T09:06:12.000Z", "avg_line_length": 22.3068783069, "max_line_length": 99, "alphanum_fraction": 0.6368595825, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5887257074251638}} {"text": "//\n// herk.h\n// Linear Algebra Template Library\n//\n// Created by Rodney James on 1/6/12.\n// Copyright (c) 2012 University of Colorado Denver. All rights reserved.\n//\n\n#ifndef _herk_h\n#define _herk_h\n\n/// @file herk.h Performs complex matrix-matrix multiplication operations resulting in Hermitian matrices.\n\n#include \n#include \"latl.h\"\n\nnamespace LATL\n{\n /// @brief Performs multiplcation of a complex matrix with its conjugate transpose.\n ///\n /// For complex matrix A, complex Hermitian matrix C, and real scalars alpha and beta\n ///\n /// C := alpha*A*A'+beta*C or C := alpha*A'*A+beta*C\n /// is computed.\n /// @return 0 if success.\n /// @return -i if the ith argument is invalid.\n /// @tparam real_t Floating point type.\n /// @param uplo Specifies whether the upper or lower triangular part of the Hermitian matrix C\n /// is to be referenced: \n ///\n /// if uplo = 'U' or 'u' then C is upper triangular,\n /// if uplo = 'L' or 'l' then C is lower triangular.\n /// @param trans Specifies the operation to be perfomed as follows:\n ///\n /// if trans = 'N' or 'n' then C := alpha*A*A'+beta*C\n /// if trans = 'C' or 'c' then C := alpha*A'*A+beta*C\n /// @param n Specifies the order of the complex Hermitian matrix C. n>=0\n /// @param k Specifies the other dimension of the complex matrix A (see below). k>=0\n /// @param alpha Real scalar.\n /// @param A Pointer to complex matrix.\n ///\n /// if trans = 'N' or 'n' then A is n-by-k\n /// if trans = 'C' or 'c' then A is k-by-n\n /// @param ldA Column length of the matrix A. If trans = 'N' or 'n' ldA>=n, otherwise ldA>=k.\n /// @param beta Real scalar.\n /// @param C Pointer to complex Hermitian n-by-n matrix C. \n /// Only the upper or lower triangular part of C is referenced, depending on the value of uplo above.\n /// @param ldC Column length of the matrix C. ldC>=n\n /// @ingroup BLAS\n\n template \n int HERK(char uplo, char trans, int_t n, int_t k, real_t alpha, complex *A, int_t ldA, real_t beta, complex *C, int_t ldC)\n {\n using std::toupper;\n uplo=toupper(uplo);\n trans=toupper(trans);\n using std::real;\n using std::conj;\n const complex zero(0.0,0.0);\n const real_t rzero=0.0;\n const real_t one=1.0;\n int_t i,j,l;\n complex *a,*c,*at;\n complex t;\n real_t s;\n \n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='C'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldC\n\n template <> int HERK(char uplo, char trans, int_t n, int_t k, float alpha, complex *A, int_t ldA, float beta, complex *C, int_t ldC)\n {\n using std::toupper;\n uplo=toupper(uplo);\n trans=toupper(trans);\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='C'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldC int HERK(char uplo, char trans, int_t n, int_t k, double alpha, complex *A, int_t ldA, double beta, complex *C, int_t ldC)\n {\n using std::toupper;\n uplo=toupper(uplo);\n trans=toupper(trans);\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='C'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldC\n#include \n\n/* compilar: gcc fonte.c -o exec -lblas */\n\n\nint main( void ) {\n int lda = 3;\n float A[] = { 1, 0, -1,\n 2, 3, 1 };\n\n int ldb = 2;\n float B[] = { 5, 1,\n 6, -1,\n 7, 2 };\n\n int ldc = 2;\n float C[] = { 0.00, 0.00,\n 0.00, 0.00 };\n\n /* Compute C = A B */\n\n cblas_sgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, 2, 2, 3, 1.0, A, lda, B, ldb, 0.0, C, ldc );\n\n printf( \"[ %g, %g\\n\", C[ 0 ], C[ 1 ] );\n printf( \" %g, %g ]\\n\", C[ 2 ], C[ 3 ] );\n\n return( 0 );\n}\n", "meta": {"hexsha": "aca2bdb28bace7bca6bab91ab1a26b603e63bab5", "size": 564, "ext": "c", "lang": "C", "max_stars_repo_path": "at02-cache/exemplos/sgemm.c", "max_stars_repo_name": "lellisls/PAD", "max_stars_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "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": "at02-cache/exemplos/sgemm.c", "max_issues_repo_name": "lellisls/PAD", "max_issues_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "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": "at02-cache/exemplos/sgemm.c", "max_forks_repo_name": "lellisls/PAD", "max_forks_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "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": 18.8, "max_line_length": 102, "alphanum_fraction": 0.420212766, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5886068514041781}} {"text": "/* stable/stable_koutrouvelis.h\n *\n * Koutrouvelis method for parameter estimation of alpha-stable\n * distributions. Based on [1] and MATLAB code available in [2].\n *\n * [1] Koutrouvelis, I. A. An Iterative Procedure for the Estimation\n * of the Parameters of Stable Laws Communications in Statistics\n * - Simulation and Computation, 1981, 10, 17-28\n * [2] Mark S. Veillete. Alpha-Stable Distributions in MATLAB\n * http://math.bu.edu/people/mveillet/research.html\n *\n * Copyright (C) 2013. Javier Royuela del Val\n * Federico Simmross Wattenberg\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful, 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, see .\n *\n *\n * Javier Royuela del Val.\n * E.T.S.I. Telecomunicación\n * Universidad de Valladolid\n * Paseo de Belén 15, 47002 Valladolid, Spain.\n * jroyval@lpi.tel.uva.es\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"stable.h\"\n\ninline double sign(double x) {\n return ((.0 < x) - (x < .0));\n}\n\ndouble var(const double * data, const int N) {\n double acum = .0, acum2 = .0;\n double v;\n\n int i;\n for(i=0;ialpha;\n double beta = dist->beta;\n double sigma = dist->sigma;\n double mu1 = dist->mu_1;\n\n double alphaold = alpha;\n double mu1old = mu1;\n\n double diff = .0;\n double diffbest = DBL_MAX;\n double diffmax = .0;\n\n double alphabest = alpha;\n double betabest = beta;\n double sigmabest = sigma;\n double mu1best = mu1;\n\n double * t = NULL;\n double * w = NULL;\n double * y = NULL;\n double * p = NULL;\n\n double * t2 = NULL;\n double * w2 = NULL;\n double * y2 = NULL;\n double * p2 = NULL;\n\n gsl_matrix * X;\n gsl_matrix * covmat;\n gsl_vector * cvout;\n gsl_vector * ydat;\n gsl_vector * weights;\n\n int stat;\n double sumsq = .0;\n double c0 = .0, c1 = .0;\n double cov00 = .0, cov01 = .0, cov11 = .0;\n double sigmanew = 0;\n\n double **covYY;// **covZZ;\n double **covZZ;\n\n int iter = 0;\n int K,L;\n int row;\n double t_0=0;\n double step_u=0;\n double estshift;\n\n gsl_multifit_linear_workspace * linws;\n\n if (sigma == 0) {\n sigma = sqrt(var(data,N));\n\tstable_setparams(dist,alpha,beta,sigma,mu1,1);\n }\n\n s = (double *) malloc(N*sizeof(double));\n for (i=0;i2) alpha = 2;\n if (beta<-1) beta = -1;\n if (beta> 1) beta = 1;\n if (sigma<0) sigma = 0;\n\n\n /********** refine beta and mu **************/\n // printf(\"refbetamu\\n\");fflush(stdout);\n if (iter <= 1) {\n L = chooseL(alpha,N);\n// printf(\"alpha = %f, N = %d, L = %d\\n\",alpha,N,L);fflush(stdout);\n t_0 = ecfRoot(s,N);\n step_u = M_PI/50;\n if (t_0/L1.98 || alpha < 0.05 || fabs(alpha-1.0)<0.05 || isnan(alpha)) {\n beta = 0.0;\n } else {\n beta = gsl_vector_get(cvout,1)/tan(alpha*M_PI*0.5);\n }\n estshift = gsl_vector_get(cvout,0);\n mu1 = mu1 + sigma * estshift;\n\n// printf(\"rem shift\\n\");\n /*** remove estimated shift ***/\n for (i=0;i diffmax) {\n diffmax = diff;\n }\n// else if (diff > 2.0*diffmax) {\n#ifdef DEBUG\n printf(\"blow up on iter %d\\n\",iter);\n#endif\n// break;\n// }\n\n// printf(\"check best\\n\");\n if (fabs(diff) < diffbest) {\n alphabest = alpha;\n betabest = beta;\n sigmabest = sigma;\n mu1best = mu1;\n\n diffbest = diff;\n\n if (diff < xTol) {\n gsl_matrix_free(X);\n gsl_vector_free(ydat);\n if (iter>0) gsl_vector_free(weights);\n iter++;\n break;\n }\n }\n\n alphaold = alpha;\n mu1old = mu1;\n\n gsl_matrix_free(X);\n gsl_vector_free(ydat);\n if (iter>0) {\n gsl_vector_free(weights);\n }\n }\n\n\n if (maxiter > 0 && iter >= 0) {\n alpha = alphabest;\n beta = betabest;\n sigma = sigmabest;\n mu1 = mu1best;\n }\n\n if (alpha<0) alpha = 0;\n if (alpha>2) alpha = 2;\n if (beta<-1) beta = -1;\n if (beta> 1) beta = 1;\n if (sigma<0) sigma = 0;\n\n stable_setparams(dist,alpha,beta,sigma,mu1,1);\n\n free(t);\n free(p);\n free(w);\n free(y);\n free(phi);\n free(t2);\n free(p2);\n free(w2);\n free(y2);\n free(phi2);\n gsl_matrix_free(covmat);\n gsl_vector_free(cvout);\n free(s);\n\n if (iter>1) {\n free(covYY[0]);\n free(covYY);\n free(covZZ[0]);\n free(covZZ);\n }\n\n gsl_multifit_linear_free(linws);\n\n //printf(\" iter %d diff %f a %f b %f s %f m %f\\n\",iter,diff,alpha,beta,sigma,dist->mu_0);\n\n return 0;\n} // end stable_fit_koutrouvelis\n\nint chooseK(double alpha, int N) {\n double a[]={1.9,1.5,1.3,1.1,.9,.7,.5,.3};\n int n[] = {200, 800, 1600};\n\n double Kmat[8][3]={{ 9, 9, 9},\n {11,11,11},\n {22,16,14},\n {24,18,15},\n {28,22,18},\n {30,24,20},\n {86,68,56},\n {134,124,118}};\n\n int i,j;\n double xi;\n double xj;\n double Kp;\n\n if (alpha < 0.3) alpha = 0.3;\n if (alpha > 1.9) alpha = 1.9;\n if (N<200) N=200;\n if (N>1600) N=1600;\n\n i=1;\n j=1;\n while (i<7 && a[i]>=alpha) {\n ++i;\n }\n while (j<2 && n[j]<=N) {\n ++j;\n }\n\n xi = 1.0 - (alpha-a[i])/(a[i-1]-a[i]);\n xj = 1.0 - (double)(n[j]-N)/(double)(n[j]-n[j-1]);\n\n// printf(\"i,j = %d, %d; xi,xj = %f, %f\\n\",i,j,xi,xj);\n\n /* bilinear interpolation */\n Kp = xj * (xi * Kmat[i][ j ] + (1.0-xi) * Kmat[i-1][ j ] ) +\n (1.0-xj) * (xi * Kmat[i][j-1] + (1.0-xi) * Kmat[i-1][j-1] );\n\n Kp = floor(Kp+.5);\n\n return (int)Kp;\n}\n\nint chooseL(double alpha, int N) {\n double a[]={1.9,1.5,1.1,.9,.7,.5,.3};\n int n[] = {200, 800, 1600};\n\n double Lmat[7][3]={{ 9,10,11},\n {12,14,15},\n {16,18,17},\n {14,14,14},\n {24,16,16},\n {40,38,36},\n {70,68,66}};\n\n int i,j;\n double xi, xj;\n double Lp;\n\n if (alpha < 0.3) alpha = 0.3;\n if (alpha > 1.9) alpha = 1.9;\n if (N<200) N=200;\n if (N>1600) N=1600;\n\n i=1;\n j=1;\n while (i<6 && a[i]>=alpha) {\n ++i;\n }\n while (j<2 && n[j]<=N) {\n ++j;\n }\n\n xi = 1.0 - (alpha-a[i])/(a[i-1]-a[i]);\n xj = 1.0 - (double)(n[j]-N)/(double)(n[j]-n[j-1]);\n\n// printf(\"i,j = %d, %d; xi,xj = %f, %f\\n\",i,j,xi,xj);\n /* bilinear interpolation */\n Lp = xj * (xi * Lmat[i][ j ] + (1.0-xi) * Lmat[i-1][ j ] ) +\n (1.0-xj) * (xi * Lmat[i][j-1] + (1.0-xi) * Lmat[i-1][j-1] );\n\n Lp = floor(Lp + .5);\n\n return (int)Lp;\n}\n\nvoid setcovYY(const double * t, int K, int N, double alpha, double beta, double gam, double **covYY) {\n double w = tan(alpha*M_PI_2);\n double calpha = pow(gam,alpha);\n int j = 0, k = 0;\n\n double * talpha = (double *)malloc(K*sizeof(double));\n\n for (j=0;j1e-3) {\n t += GSL_REAL(val)/m;\n val = stable_samplecharfunc_point(data, N, t);\n }\n\n return t;\n}\n\ngsl_complex stable_samplecharfunc_point(const double* x,\n const unsigned int N, double t)\n{\n unsigned int i;\n double zr=0.0,zi=0.0;\n gsl_complex z;\n\n for(i=0;i\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\nGSL_EXPORT double gsl_stats_long_double_mean (const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_long_double_variance (const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_long_double_sd (const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_long_double_variance_with_fixed_mean (const long double data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_long_double_sd_with_fixed_mean (const long double data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_long_double_absdev (const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_long_double_skew (const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_long_double_kurtosis (const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_long_double_lag1_autocorrelation (const long double data[], const size_t stride, const size_t n);\n\nGSL_EXPORT double gsl_stats_long_double_covariance (const long double data1[], const size_t stride1,const long double data2[], const size_t stride2, const size_t n);\n\nGSL_EXPORT double gsl_stats_long_double_variance_m (const long double data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_long_double_sd_m (const long double data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_long_double_absdev_m (const long double data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_long_double_skew_m_sd (const long double data[], const size_t stride, const size_t n, const double mean, const double sd);\nGSL_EXPORT double gsl_stats_long_double_kurtosis_m_sd (const long double data[], const size_t stride, const size_t n, const double mean, const double sd);\nGSL_EXPORT double gsl_stats_long_double_lag1_autocorrelation_m (const long double data[], const size_t stride, const size_t n, const double mean);\n\nGSL_EXPORT double gsl_stats_long_double_covariance_m (const long double data1[], const size_t stride1,const long double data2[], const size_t stride2, const size_t n, const double mean1, const double mean2);\n\n/* DEFINED FOR FLOATING POINT TYPES ONLY */\n\nGSL_EXPORT double gsl_stats_long_double_wmean (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_long_double_wvariance (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_long_double_wsd (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_long_double_wvariance_with_fixed_mean (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_long_double_wsd_with_fixed_mean (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double mean);\nGSL_EXPORT double gsl_stats_long_double_wabsdev (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_long_double_wskew (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT double gsl_stats_long_double_wkurtosis (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n);\n\nGSL_EXPORT double gsl_stats_long_double_wvariance_m (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean);\nGSL_EXPORT double gsl_stats_long_double_wsd_m (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean);\nGSL_EXPORT double gsl_stats_long_double_wabsdev_m (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean);\nGSL_EXPORT double gsl_stats_long_double_wskew_m_sd (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean, const double wsd);\nGSL_EXPORT double gsl_stats_long_double_wkurtosis_m_sd (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean, const double wsd);\n\n/* END OF FLOATING POINT TYPES */\n\nGSL_EXPORT double gsl_stats_long_double_pvariance (const long double data1[], const size_t stride1, const size_t n1, const long double data2[], const size_t stride2, const size_t n2);\nGSL_EXPORT double gsl_stats_long_double_ttest (const long double data1[], const size_t stride1, const size_t n1, const long double data2[], const size_t stride2, const size_t n2);\n\nGSL_EXPORT long double gsl_stats_long_double_max (const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT long double gsl_stats_long_double_min (const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT void gsl_stats_long_double_minmax (long double * min, long double * max, const long double data[], const size_t stride, const size_t n);\n\nGSL_EXPORT size_t gsl_stats_long_double_max_index (const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT size_t gsl_stats_long_double_min_index (const long double data[], const size_t stride, const size_t n);\nGSL_EXPORT void gsl_stats_long_double_minmax_index (size_t * min_index, size_t * max_index, const long double data[], const size_t stride, const size_t n);\n\nGSL_EXPORT double gsl_stats_long_double_median_from_sorted_data (const long double sorted_data[], const size_t stride, const size_t n) ;\nGSL_EXPORT double gsl_stats_long_double_quantile_from_sorted_data (const long double sorted_data[], const size_t stride, const size_t n, const double f) ;\n\n__END_DECLS\n\n#endif /* __GSL_STATISTICS_LONG_DOUBLE_H__ */\n", "meta": {"hexsha": "74ca27e819cbb51a71f35fac3da0c39817ce1010", "size": 7337, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_statistics_long_double.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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/core/gsl/include/gsl/gsl_statistics_long_double.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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/core/gsl/include/gsl/gsl_statistics_long_double.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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": 77.2315789474, "max_line_length": 207, "alphanum_fraction": 0.8030530189, "num_tokens": 1758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5884531980682025}} {"text": "/* linalg/tridiag.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2002, 2004 Gerard Jungman,\n * Brian Gough, David Necas\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \"tridiag.h\"\n#include \n\n/* for description of method see [Engeln-Mullges + Uhlig, p. 92]\n *\n * diag[0] offdiag[0] 0 .....\n * offdiag[0] diag[1] offdiag[1] .....\n * 0 offdiag[1] diag[2]\n * 0 0 offdiag[2] .....\n */\nstatic\nint \nsolve_tridiag(\n const double diag[], size_t d_stride,\n const double offdiag[], size_t o_stride,\n const double b[], size_t b_stride,\n double x[], size_t x_stride,\n size_t N)\n{\n int status;\n double *gamma = (double *) malloc (N * sizeof (double));\n double *alpha = (double *) malloc (N * sizeof (double));\n double *c = (double *) malloc (N * sizeof (double));\n double *z = (double *) malloc (N * sizeof (double));\n\n if (gamma == 0 || alpha == 0 || c == 0 || z == 0)\n {\n status = GSL_ENOMEM;\n }\n else\n {\n size_t i, j;\n\n /* Cholesky decomposition\n A = L.D.L^t\n lower_diag(L) = gamma\n diag(D) = alpha\n */\n alpha[0] = diag[0];\n gamma[0] = offdiag[0] / alpha[0];\n\n for (i = 1; i < N - 1; i++)\n {\n alpha[i] = diag[d_stride * i] - offdiag[o_stride*(i - 1)] * gamma[i - 1];\n gamma[i] = offdiag[o_stride * i] / alpha[i];\n }\n\n if (N > 1) \n {\n alpha[N - 1] = diag[d_stride * (N - 1)] - offdiag[o_stride*(N - 2)] * gamma[N - 2];\n }\n\n /* update RHS */\n z[0] = b[0];\n for (i = 1; i < N; i++)\n {\n z[i] = b[b_stride * i] - gamma[i - 1] * z[i - 1];\n }\n for (i = 0; i < N; i++)\n {\n c[i] = z[i] / alpha[i];\n }\n\n /* backsubstitution */\n x[x_stride * (N - 1)] = c[N - 1];\n if (N >= 2)\n {\n for (i = N - 2, j = 0; j <= N - 2; j++, i--)\n {\n x[x_stride * i] = c[i] - gamma[i] * x[x_stride * (i + 1)];\n }\n }\n\n status = GSL_SUCCESS;\n }\n\n if (z != 0)\n free (z);\n if (c != 0)\n free (c);\n if (alpha != 0)\n free (alpha);\n if (gamma != 0)\n free (gamma);\n\n return status;\n}\n\n/* plain gauss elimination, only not bothering with the zeroes\n *\n * diag[0] abovediag[0] 0 .....\n * belowdiag[0] diag[1] abovediag[1] .....\n * 0 belowdiag[1] diag[2]\n * 0 0 belowdiag[2] .....\n */\nstatic\nint \nsolve_tridiag_nonsym(\n const double diag[], size_t d_stride,\n const double abovediag[], size_t a_stride,\n const double belowdiag[], size_t b_stride,\n const double rhs[], size_t r_stride,\n double x[], size_t x_stride,\n size_t N)\n{\n int status;\n double *alpha = (double *) malloc (N * sizeof (double));\n double *z = (double *) malloc (N * sizeof (double));\n\n if (alpha == 0 || z == 0)\n {\n status = GSL_ENOMEM;\n }\n else\n {\n size_t i, j;\n\n /* Bidiagonalization (eliminating belowdiag)\n & rhs update\n diag' = alpha\n rhs' = z\n */\n alpha[0] = diag[0];\n z[0] = rhs[0];\n\n for (i = 1; i < N; i++)\n {\n const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1];\n alpha[i] = diag[d_stride*i] - t*abovediag[a_stride*(i - 1)];\n z[i] = rhs[r_stride*i] - t*z[i-1];\n /* FIXME!!! */\n if (alpha[i] == 0) {\n status = GSL_EZERODIV;\n goto solve_tridiag_nonsym_END;\n }\n }\n\n /* backsubstitution */\n x[x_stride * (N - 1)] = z[N - 1]/alpha[N - 1];\n if (N >= 2)\n {\n for (i = N - 2, j = 0; j <= N - 2; j++, i--)\n {\n x[x_stride * i] = (z[i] - abovediag[a_stride*i] * x[x_stride * (i + 1)])/alpha[i];\n }\n }\n\n status = GSL_SUCCESS;\n }\n\nsolve_tridiag_nonsym_END:\n if (z != 0)\n free (z);\n if (alpha != 0)\n free (alpha);\n\n return status;\n}\n\n/* for description of method see [Engeln-Mullges + Uhlig, p. 96]\n *\n * diag[0] offdiag[0] 0 ..... offdiag[N-1]\n * offdiag[0] diag[1] offdiag[1] .....\n * 0 offdiag[1] diag[2]\n * 0 0 offdiag[2] .....\n * ... ...\n * offdiag[N-1] ...\n *\n */\nstatic\nint \nsolve_cyc_tridiag(\n const double diag[], size_t d_stride,\n const double offdiag[], size_t o_stride,\n const double b[], size_t b_stride,\n double x[], size_t x_stride,\n size_t N)\n{\n int status;\n double * delta = (double *) malloc (N * sizeof (double));\n double * gamma = (double *) malloc (N * sizeof (double));\n double * alpha = (double *) malloc (N * sizeof (double));\n double * c = (double *) malloc (N * sizeof (double));\n double * z = (double *) malloc (N * sizeof (double));\n\n if (delta == 0 || gamma == 0 || alpha == 0 || c == 0 || z == 0)\n {\n status = GSL_ENOMEM;\n }\n else\n {\n size_t i, j;\n double sum = 0.0;\n\n /* factor */\n\n if (N == 1) \n {\n x[0] = b[0] / diag[0];\n return GSL_SUCCESS;\n }\n\n alpha[0] = diag[0];\n gamma[0] = offdiag[0] / alpha[0];\n delta[0] = offdiag[o_stride * (N-1)] / alpha[0];\n\n for (i = 1; i < N - 2; i++)\n {\n alpha[i] = diag[d_stride * i] - offdiag[o_stride * (i-1)] * gamma[i - 1];\n gamma[i] = offdiag[o_stride * i] / alpha[i];\n delta[i] = -delta[i - 1] * offdiag[o_stride * (i-1)] / alpha[i];\n }\n\n for (i = 0; i < N - 2; i++)\n {\n sum += alpha[i] * delta[i] * delta[i];\n }\n\n alpha[N - 2] = diag[d_stride * (N - 2)] - offdiag[o_stride * (N - 3)] * gamma[N - 3];\n\n gamma[N - 2] = (offdiag[o_stride * (N - 2)] - offdiag[o_stride * (N - 3)] * delta[N - 3]) / alpha[N - 2];\n\n alpha[N - 1] = diag[d_stride * (N - 1)] - sum - alpha[(N - 2)] * gamma[N - 2] * gamma[N - 2];\n\n /* update */\n z[0] = b[0];\n for (i = 1; i < N - 1; i++)\n {\n z[i] = b[b_stride * i] - z[i - 1] * gamma[i - 1];\n }\n sum = 0.0;\n for (i = 0; i < N - 2; i++)\n {\n sum += delta[i] * z[i];\n }\n z[N - 1] = b[b_stride * (N - 1)] - sum - gamma[N - 2] * z[N - 2];\n for (i = 0; i < N; i++)\n {\n c[i] = z[i] / alpha[i];\n }\n\n /* backsubstitution */\n x[x_stride * (N - 1)] = c[N - 1];\n x[x_stride * (N - 2)] = c[N - 2] - gamma[N - 2] * x[x_stride * (N - 1)];\n if (N >= 3)\n {\n for (i = N - 3, j = 0; j <= N - 3; j++, i--)\n {\n x[x_stride * i] = c[i] - gamma[i] * x[x_stride * (i + 1)] - delta[i] * x[x_stride * (N - 1)];\n }\n }\n\n status = GSL_SUCCESS;\n }\n\n if (z != 0)\n free (z);\n if (c != 0)\n free (c);\n if (alpha != 0)\n free (alpha);\n if (gamma != 0)\n free (gamma);\n if (delta != 0)\n free (delta);\n\n return status;\n}\n\n/* solve following system w/o the corner elements and then use\n * Sherman-Morrison formula to compensate for them\n *\n * diag[0] abovediag[0] 0 ..... belowdiag[N-1]\n * belowdiag[0] diag[1] abovediag[1] .....\n * 0 belowdiag[1] diag[2]\n * 0 0 belowdiag[2] .....\n * ... ...\n * abovediag[N-1] ...\n */\nstatic\nint solve_cyc_tridiag_nonsym(\n const double diag[], size_t d_stride,\n const double abovediag[], size_t a_stride,\n const double belowdiag[], size_t b_stride,\n const double rhs[], size_t r_stride,\n double x[], size_t x_stride,\n size_t N)\n{\n int status;\n double *alpha = (double *) malloc (N * sizeof (double));\n double *zb = (double *) malloc (N * sizeof (double));\n double *zu = (double *) malloc (N * sizeof (double));\n double *w = (double *) malloc (N * sizeof (double));\n double beta;\n\n if (alpha == 0 || zb == 0 || zu == 0 || w == 0)\n {\n status = GSL_ENOMEM;\n }\n else\n {\n /* Bidiagonalization (eliminating belowdiag)\n & rhs update\n diag' = alpha\n rhs' = zb\n rhs' for Aq=u is zu\n */\n zb[0] = rhs[0];\n if (diag[0] != 0) beta = -diag[0]; else beta = 1;\n {\n const double q = 1 - abovediag[0]*belowdiag[0]/(diag[0]*diag[d_stride]);\n if (fabs(q/beta) > 0.5 && fabs(q/beta) < 2) {\n beta *= (fabs(q/beta) < 1) ? 0.5 : 2;\n }\n }\n zu[0] = beta;\n alpha[0] = diag[0] - beta;\n\n\n { \n size_t i;\n for (i = 1; i+1 < N; i++)\n {\n const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1];\n alpha[i] = diag[d_stride*i] - t*abovediag[a_stride*(i - 1)];\n zb[i] = rhs[r_stride*i] - t*zb[i-1];\n zu[i] = -t*zu[i-1];\n /* FIXME!!! */\n if (alpha[i] == 0) {\n status = GSL_EZERODIV;\n goto solve_cyc_tridiag_nonsym_END;\n }\n }\n }\n\n {\n const size_t i = N-1;\n const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1];\n alpha[i] = diag[d_stride*i]\n - abovediag[a_stride*i]*belowdiag[b_stride*i]/beta\n - t*abovediag[a_stride*(i - 1)];\n zb[i] = rhs[r_stride*i] - t*zb[i-1];\n zu[i] = abovediag[a_stride*i] - t*zu[i-1];\n /* FIXME!!! */\n if (alpha[i] == 0) {\n status = GSL_EZERODIV;\n goto solve_cyc_tridiag_nonsym_END;\n }\n }\n\n\n /* backsubstitution */\n {\n size_t i, j;\n w[N-1] = zu[N-1]/alpha[N-1];\n x[N-1] = zb[N-1]/alpha[N-1];\n for (i = N - 2, j = 0; j <= N - 2; j++, i--)\n {\n w[i] = (zu[i] - abovediag[a_stride*i] * w[i+1])/alpha[i];\n x[i*x_stride] = (zb[i] - abovediag[a_stride*i] * x[x_stride*(i + 1)])/alpha[i];\n }\n }\n \n /* Sherman-Morrison */\n {\n const double vw = w[0] + belowdiag[b_stride*(N - 1)]/beta * w[N-1];\n const double vx = x[0] + belowdiag[b_stride*(N - 1)]/beta * x[x_stride*(N - 1)];\n /* FIXME!!! */\n if (vw + 1 == 0) {\n status = GSL_EZERODIV;\n goto solve_cyc_tridiag_nonsym_END;\n }\n\n {\n size_t i;\n for (i = 0; i < N; i++)\n x[i] -= vx/(1 + vw)*w[i];\n }\n }\n\n status = GSL_SUCCESS;\n }\n\nsolve_cyc_tridiag_nonsym_END:\n if (zb != 0)\n free (zb);\n if (zu != 0)\n free (zu);\n if (w != 0)\n free (w);\n if (alpha != 0)\n free (alpha);\n\n return status;\n}\n\nint\ngsl_linalg_solve_symm_tridiag(\n const gsl_vector * diag,\n const gsl_vector * offdiag,\n const gsl_vector * rhs,\n gsl_vector * solution)\n{\n if(diag->size != rhs->size)\n {\n GSL_ERROR (\"size of diag must match rhs\", GSL_EBADLEN);\n }\n else if (offdiag->size != rhs->size-1)\n {\n GSL_ERROR (\"size of offdiag must match rhs-1\", GSL_EBADLEN);\n }\n else if (solution->size != rhs->size)\n {\n GSL_ERROR (\"size of solution must match rhs\", GSL_EBADLEN);\n }\n else \n {\n return solve_tridiag(diag->data, diag->stride,\n offdiag->data, offdiag->stride,\n rhs->data, rhs->stride,\n solution->data, solution->stride,\n diag->size);\n }\n}\n\nint\ngsl_linalg_solve_tridiag(\n const gsl_vector * diag,\n const gsl_vector * abovediag,\n const gsl_vector * belowdiag,\n const gsl_vector * rhs,\n gsl_vector * solution)\n{\n if(diag->size != rhs->size)\n {\n GSL_ERROR (\"size of diag must match rhs\", GSL_EBADLEN);\n }\n else if (abovediag->size != rhs->size-1)\n {\n GSL_ERROR (\"size of abovediag must match rhs-1\", GSL_EBADLEN);\n }\n else if (belowdiag->size != rhs->size-1)\n {\n GSL_ERROR (\"size of belowdiag must match rhs-1\", GSL_EBADLEN);\n }\n else if (solution->size != rhs->size)\n {\n GSL_ERROR (\"size of solution must match rhs\", GSL_EBADLEN);\n }\n else \n {\n return solve_tridiag_nonsym(diag->data, diag->stride,\n abovediag->data, abovediag->stride,\n belowdiag->data, belowdiag->stride,\n rhs->data, rhs->stride,\n solution->data, solution->stride,\n diag->size);\n }\n}\n\n\nint\ngsl_linalg_solve_symm_cyc_tridiag(\n const gsl_vector * diag,\n const gsl_vector * offdiag,\n const gsl_vector * rhs,\n gsl_vector * solution)\n{\n if(diag->size != rhs->size)\n {\n GSL_ERROR (\"size of diag must match rhs\", GSL_EBADLEN);\n }\n else if (offdiag->size != rhs->size)\n {\n GSL_ERROR (\"size of offdiag must match rhs\", GSL_EBADLEN);\n }\n else if (solution->size != rhs->size)\n {\n GSL_ERROR (\"size of solution must match rhs\", GSL_EBADLEN);\n }\n else if (diag->size < 3)\n {\n GSL_ERROR (\"size of cyclic system must be 3 or more\", GSL_EBADLEN);\n }\n else \n {\n return solve_cyc_tridiag(diag->data, diag->stride,\n offdiag->data, offdiag->stride,\n rhs->data, rhs->stride,\n solution->data, solution->stride,\n diag->size);\n }\n}\n\nint\ngsl_linalg_solve_cyc_tridiag(\n const gsl_vector * diag,\n const gsl_vector * abovediag,\n const gsl_vector * belowdiag,\n const gsl_vector * rhs,\n gsl_vector * solution)\n{\n if(diag->size != rhs->size)\n {\n GSL_ERROR (\"size of diag must match rhs\", GSL_EBADLEN);\n }\n else if (abovediag->size != rhs->size)\n {\n GSL_ERROR (\"size of abovediag must match rhs\", GSL_EBADLEN);\n }\n else if (belowdiag->size != rhs->size)\n {\n GSL_ERROR (\"size of belowdiag must match rhs\", GSL_EBADLEN);\n }\n else if (solution->size != rhs->size)\n {\n GSL_ERROR (\"size of solution must match rhs\", GSL_EBADLEN);\n }\n else if (diag->size < 3)\n {\n GSL_ERROR (\"size of cyclic system must be 3 or more\", GSL_EBADLEN);\n }\n else \n {\n return solve_cyc_tridiag_nonsym(diag->data, diag->stride,\n abovediag->data, abovediag->stride,\n belowdiag->data, belowdiag->stride,\n rhs->data, rhs->stride,\n solution->data, solution->stride,\n diag->size);\n }\n}\n", "meta": {"hexsha": "485fdcbbbcc4be188d7a9319a52437c4b660d2c3", "size": 15150, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/linalg/tridiag.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/linalg/tridiag.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/linalg/tridiag.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.1019677996, "max_line_length": 111, "alphanum_fraction": 0.4900990099, "num_tokens": 4706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5883884945043036}} {"text": "#include \n#include \n#include \n#include \n\nint\nmain (int argc, char **argv)\n{\n (void)(argc); /* avoid unused parameter warning */\n int i, n = 256, nc = 20;\n double *orig_data = malloc (n * sizeof (double));\n double *data = malloc (n * sizeof (double));\n double *abscoeff = malloc (n * sizeof (double));\n size_t *p = malloc (n * sizeof (size_t));\n\n FILE * f;\n gsl_wavelet *w;\n gsl_wavelet_workspace *work;\n\n w = gsl_wavelet_alloc (gsl_wavelet_daubechies, 4);\n work = gsl_wavelet_workspace_alloc (n);\n\n f = fopen (argv[1], \"r\");\n for (i = 0; i < n; i++)\n {\n fscanf (f, \"%lg\", &orig_data[i]);\n data[i] = orig_data[i];\n }\n fclose (f);\n\n gsl_wavelet_transform_forward (w, data, 1, n, work);\n\n for (i = 0; i < n; i++)\n {\n abscoeff[i] = fabs (data[i]);\n }\n \n gsl_sort_index (p, abscoeff, 1, n);\n \n for (i = 0; (i + nc) < n; i++)\n data[p[i]] = 0;\n \n gsl_wavelet_transform_inverse (w, data, 1, n, work);\n \n for (i = 0; i < n; i++)\n {\n printf (\"%g %g\\n\", orig_data[i], data[i]);\n }\n \n gsl_wavelet_free (w);\n gsl_wavelet_workspace_free (work);\n\n free (data);\n free (orig_data);\n free (abscoeff);\n free (p);\n return 0;\n}\n", "meta": {"hexsha": "422c55d54ed7875b757da960a4e4b888e7cc17fc", "size": 1232, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/dwt.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/dwt.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/dwt.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 20.8813559322, "max_line_length": 54, "alphanum_fraction": 0.5722402597, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.588318808902142}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n/* Computation of the integral,\n\n I = int (dx dy dz)/(2pi)^3 1/(1-cos(x)cos(y)cos(z))\n\n over (-pi,-pi,-pi) to (+pi, +pi, +pi). The exact answer\n is Gamma(1/4)^4/(4 pi^3). This example is taken from\n C.Itzykson, J.M.Drouffe, \"Statistical Field Theory -\n Volume 1\", Section 1.1, p21, which cites the original\n paper M.L.Glasser, I.J.Zucker, Proc.Natl.Acad.Sci.USA 74\n 1800 (1977) */\n\n/* For simplicity we compute the integral over the region \n (0,0,0) -> (pi,pi,pi) and multiply by 8 */\n\ndouble exact = 1.3932039296856768591842462603255;\n\ndouble\ng (double *k, size_t dim, void *params)\n{\n double A = 1.0 / (M_PI * M_PI * M_PI);\n return A / (1.0 - cos (k[0]) * cos (k[1]) * cos (k[2]));\n}\n\nvoid\ndisplay_results (char *title, double result, double error)\n{\n printf (\"%s ==================\\n\", title);\n printf (\"result = % .6f\\n\", result);\n printf (\"sigma = % .6f\\n\", error);\n printf (\"exact = % .6f\\n\", exact);\n printf (\"error = % .6f = %.2g sigma\\n\", result - exact,\n fabs (result - exact) / error);\n}\n\nint\nmain (void)\n{\n double res, err;\n\n double xl[3] = { 0, 0, 0 };\n double xu[3] = { M_PI, M_PI, M_PI };\n\n const gsl_rng_type *T;\n gsl_rng *r;\n\n gsl_monte_function G = { &g, 3, 0 };\n\n size_t calls = 500000;\n\n gsl_rng_env_setup ();\n\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n\n {\n gsl_monte_plain_state *s = gsl_monte_plain_alloc (3);\n gsl_monte_plain_integrate (&G, xl, xu, 3, calls, r, s, \n &res, &err);\n gsl_monte_plain_free (s);\n\n display_results (\"plain\", res, err);\n }\n\n {\n gsl_monte_miser_state *s = gsl_monte_miser_alloc (3);\n gsl_monte_miser_integrate (&G, xl, xu, 3, calls, r, s,\n &res, &err);\n gsl_monte_miser_free (s);\n\n display_results (\"miser\", res, err);\n }\n\n {\n gsl_monte_vegas_state *s = gsl_monte_vegas_alloc (3);\n\n gsl_monte_vegas_integrate (&G, xl, xu, 3, 10000, r, s,\n &res, &err);\n display_results (\"vegas warm-up\", res, err);\n\n printf (\"converging...\\n\");\n\n do\n {\n gsl_monte_vegas_integrate (&G, xl, xu, 3, calls/5, r, s,\n &res, &err);\n printf (\"result = % .6f sigma = % .6f \"\n \"chisq/dof = %.1f\\n\", res, err, gsl_monte_vegas_chisq (s));\n }\n while (fabs (gsl_monte_vegas_chisq (s) - 1.0) > 0.5);\n\n display_results (\"vegas final\", res, err);\n\n gsl_monte_vegas_free (s);\n }\n\n gsl_rng_free (r);\n\n return 0;\n}\n", "meta": {"hexsha": "a2b95fcf974e9e2fde88e54f11481b7b1b0ae1d0", "size": 2673, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/monte.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/doc/examples/monte.c", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/doc/examples/monte.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 24.9813084112, "max_line_length": 75, "alphanum_fraction": 0.5746352413, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.5882645999666705}} {"text": "#include \n#include \n#include \n#include \n\n#define REAL(z,i) ((z)[2*(i)])\n#define IMAG(z,i) ((z)[2*(i)+1])\n\nint\nmain (void)\n{\n int i; double data[2*128];\n\n for (i = 0; i < 128; i++)\n {\n REAL(data,i) = 0.0; IMAG(data,i) = 0.0;\n }\n\n REAL(data,0) = 1.0;\n\n for (i = 1; i <= 10; i++)\n {\n REAL(data,i) = REAL(data,128-i) = 1.0;\n }\n\n for (i = 0; i < 128; i++)\n {\n printf (\"%d %e %e\\n\", i, \n REAL(data,i), IMAG(data,i));\n }\n printf (\"\\n\");\n\n gsl_fft_complex_radix2_forward (data, 1, 128);\n\n for (i = 0; i < 128; i++)\n {\n printf (\"%d %e %e\\n\", i, \n REAL(data,i)/sqrt(128), \n IMAG(data,i)/sqrt(128));\n }\n\n return 0;\n}\n", "meta": {"hexsha": "aa00242fdade49fbb0acc77054b977ddea2b3cac", "size": 757, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/fft.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/fft.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/fft.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": 17.2045454545, "max_line_length": 48, "alphanum_fraction": 0.4623513871, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5880439287949264}} {"text": "/* cdf/cdf_beta.c\n * \n * Copyright (C) 2003 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"beta_inc.c\"\n\ndouble\ngsl_cdf_beta_P (const double x, const double a, const double b)\n{\n double P;\n\n if (x <= 0.0 )\n {\n return 0.0;\n }\n\n if ( x >= 1.0 )\n {\n return 1.0;\n }\n\n P = beta_inc_AXPY (1.0, 0.0, a, b, x);\n\n return P;\n}\n\ndouble\ngsl_cdf_beta_Q (const double x, const double a, const double b)\n{\n double Q;\n\n if ( x >= 1.0)\n {\n return 0.0;\n }\n\n if ( x <= 0.0 )\n {\n return 1.0;\n }\n\n Q = beta_inc_AXPY (-1.0, 1.0, a, b, x);\n\n return Q;\n}\n", "meta": {"hexsha": "524391da14e0bffcc75c8bf49943acafc1f22e69", "size": 1405, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/cdf/beta.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/beta.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/beta.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": 20.9701492537, "max_line_length": 77, "alphanum_fraction": 0.6476868327, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5872083136090486}} {"text": "/* specfunc/hyperg_1F1.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \"gsl_sf_elementary.h\"\n#include \"gsl_sf_exp.h\"\n#include \"gsl_sf_bessel.h\"\n#include \"gsl_sf_gamma.h\"\n#include \"gsl_sf_laguerre.h\"\n#include \"gsl_sf_hyperg.h\"\n\n#include \"error.h\"\n#include \"hyperg.h\"\n\n#define _1F1_INT_THRESHOLD (100.0*GSL_DBL_EPSILON)\n\n\n/* Asymptotic result for 1F1(a, b, x) x -> -Infinity.\n * Assumes b-a != neg integer and b != neg integer.\n */\nstatic\nint\nhyperg_1F1_asymp_negx(const double a, const double b, const double x,\n gsl_sf_result * result)\n{\n gsl_sf_result lg_b;\n gsl_sf_result lg_bma;\n double sgn_b;\n double sgn_bma;\n\n int stat_b = gsl_sf_lngamma_sgn_e(b, &lg_b, &sgn_b);\n int stat_bma = gsl_sf_lngamma_sgn_e(b-a, &lg_bma, &sgn_bma);\n\n if(stat_b == GSL_SUCCESS && stat_bma == GSL_SUCCESS) {\n gsl_sf_result F;\n int stat_F = gsl_sf_hyperg_2F0_series_e(a, 1.0+a-b, -1.0/x, -1, &F);\n if(F.val != 0) {\n double ln_term_val = a*log(-x);\n double ln_term_err = 2.0 * GSL_DBL_EPSILON * (fabs(a) + fabs(ln_term_val));\n double ln_pre_val = lg_b.val - lg_bma.val - ln_term_val;\n double ln_pre_err = lg_b.err + lg_bma.err + ln_term_err;\n int stat_e = gsl_sf_exp_mult_err_e(ln_pre_val, ln_pre_err,\n sgn_bma*sgn_b*F.val, F.err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_F);\n }\n else {\n result->val = 0.0;\n result->err = 0.0;\n return stat_F;\n }\n }\n else {\n DOMAIN_ERROR(result);\n }\n}\n\n\n/* Asymptotic result for 1F1(a, b, x) x -> +Infinity\n * Assumes b != neg integer and a != neg integer\n */\nstatic\nint\nhyperg_1F1_asymp_posx(const double a, const double b, const double x,\n gsl_sf_result * result)\n{\n gsl_sf_result lg_b;\n gsl_sf_result lg_a;\n double sgn_b;\n double sgn_a;\n\n int stat_b = gsl_sf_lngamma_sgn_e(b, &lg_b, &sgn_b);\n int stat_a = gsl_sf_lngamma_sgn_e(a, &lg_a, &sgn_a);\n\n if(stat_a == GSL_SUCCESS && stat_b == GSL_SUCCESS) {\n gsl_sf_result F;\n int stat_F = gsl_sf_hyperg_2F0_series_e(b-a, 1.0-a, 1.0/x, -1, &F);\n if(stat_F == GSL_SUCCESS && F.val != 0) {\n double lnx = log(x);\n double ln_term_val = (a-b)*lnx;\n double ln_term_err = 2.0 * GSL_DBL_EPSILON * (fabs(a) + fabs(b)) * fabs(lnx)\n + 2.0 * GSL_DBL_EPSILON * fabs(a-b);\n double ln_pre_val = lg_b.val - lg_a.val + ln_term_val + x;\n double ln_pre_err = lg_b.err + lg_a.err + ln_term_err + 2.0 * GSL_DBL_EPSILON * fabs(x);\n int stat_e = gsl_sf_exp_mult_err_e(ln_pre_val, ln_pre_err,\n sgn_a*sgn_b*F.val, F.err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_F);\n }\n else {\n result->val = 0.0;\n result->err = 0.0;\n return stat_F;\n }\n }\n else {\n DOMAIN_ERROR(result);\n }\n}\n\n\n/* Asymptotic result for x < 2b-4a, 2b-4a large.\n * [Abramowitz+Stegun, 13.5.21]\n *\n * assumes 0 <= x/(2b-4a) <= 1\n */\nstatic\nint\nhyperg_1F1_large2bm4a(const double a, const double b, const double x, gsl_sf_result * result)\n{\n double eta = 2.0*b - 4.0*a;\n double cos2th = x/eta;\n double sin2th = 1.0 - cos2th;\n double th = acos(sqrt(cos2th));\n double pre_h = 0.25*M_PI*M_PI*eta*eta*cos2th*sin2th;\n gsl_sf_result lg_b;\n int stat_lg = gsl_sf_lngamma_e(b, &lg_b);\n double t1 = 0.5*(1.0-b)*log(0.25*x*eta);\n double t2 = 0.25*log(pre_h);\n double lnpre_val = lg_b.val + 0.5*x + t1 - t2;\n double lnpre_err = lg_b.err + 2.0 * GSL_DBL_EPSILON * (fabs(0.5*x) + fabs(t1) + fabs(t2));\n double s1 = sin(a*M_PI);\n double s2 = sin(0.25*eta*(2.0*th - sin(2.0*th)) + 0.25*M_PI);\n double ser_val = s1 + s2;\n double ser_err = 2.0 * GSL_DBL_EPSILON * (fabs(s1) + fabs(s2));\n int stat_e = gsl_sf_exp_mult_err_e(lnpre_val, lnpre_err,\n ser_val, ser_err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_lg);\n}\n\n\n/* Luke's rational approximation.\n * See [Luke, Algorithms for the Computation of Mathematical Functions, p.182]\n *\n * Like the case of the 2F1 rational approximations, these are\n * probably guaranteed to converge for x < 0, barring gross\n * numerical instability in the pre-asymptotic regime.\n */\nstatic\nint\nhyperg_1F1_luke(const double a, const double c, const double xin,\n gsl_sf_result * result)\n{\n const double RECUR_BIG = 1.0e+50;\n const int nmax = 5000;\n int n = 3;\n const double x = -xin;\n const double x3 = x*x*x;\n const double t0 = a/c;\n const double t1 = (a+1.0)/(2.0*c);\n const double t2 = (a+2.0)/(2.0*(c+1.0));\n double F = 1.0;\n double prec;\n\n double Bnm3 = 1.0; /* B0 */\n double Bnm2 = 1.0 + t1 * x; /* B1 */\n double Bnm1 = 1.0 + t2 * x * (1.0 + t1/3.0 * x); /* B2 */\n \n double Anm3 = 1.0; /* A0 */\n double Anm2 = Bnm2 - t0 * x; /* A1 */\n double Anm1 = Bnm1 - t0*(1.0 + t2*x)*x + t0 * t1 * (c/(c+1.0)) * x*x; /* A2 */\n\n while(1) {\n double npam1 = n + a - 1;\n double npcm1 = n + c - 1;\n double npam2 = n + a - 2;\n double npcm2 = n + c - 2;\n double tnm1 = 2*n - 1;\n double tnm3 = 2*n - 3;\n double tnm5 = 2*n - 5;\n double F1 = (n-a-2) / (2*tnm3*npcm1);\n double F2 = (n+a)*npam1 / (4*tnm1*tnm3*npcm2*npcm1);\n double F3 = -npam2*npam1*(n-a-2) / (8*tnm3*tnm3*tnm5*(n+c-3)*npcm2*npcm1);\n double E = -npam1*(n-c-1) / (2*tnm3*npcm2*npcm1);\n\n double An = (1.0+F1*x)*Anm1 + (E + F2*x)*x*Anm2 + F3*x3*Anm3;\n double Bn = (1.0+F1*x)*Bnm1 + (E + F2*x)*x*Bnm2 + F3*x3*Bnm3;\n double r = An/Bn;\n\n prec = fabs((F - r)/F);\n F = r;\n\n if(prec < GSL_DBL_EPSILON || n > nmax) break;\n\n if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) {\n An /= RECUR_BIG;\n Bn /= RECUR_BIG;\n Anm1 /= RECUR_BIG;\n Bnm1 /= RECUR_BIG;\n Anm2 /= RECUR_BIG;\n Bnm2 /= RECUR_BIG;\n Anm3 /= RECUR_BIG;\n Bnm3 /= RECUR_BIG;\n }\n else if(fabs(An) < 1.0/RECUR_BIG || fabs(Bn) < 1.0/RECUR_BIG) {\n An *= RECUR_BIG;\n Bn *= RECUR_BIG;\n Anm1 *= RECUR_BIG;\n Bnm1 *= RECUR_BIG;\n Anm2 *= RECUR_BIG;\n Bnm2 *= RECUR_BIG;\n Anm3 *= RECUR_BIG;\n Bnm3 *= RECUR_BIG;\n }\n\n n++;\n Bnm3 = Bnm2;\n Bnm2 = Bnm1;\n Bnm1 = Bn;\n Anm3 = Anm2;\n Anm2 = Anm1;\n Anm1 = An;\n }\n\n result->val = F;\n result->err = 2.0 * fabs(F * prec);\n result->err += 2.0 * GSL_DBL_EPSILON * (n-1.0) * fabs(F);\n\n return GSL_SUCCESS;\n}\n\n\n/* Series for 1F1(1,b,x)\n * b > 0\n */\nstatic\nint\nhyperg_1F1_1_series(const double b, const double x, gsl_sf_result * result)\n{\n double sum_val = 1.0;\n double sum_err = 0.0;\n double term = 1.0;\n double n = 1.0;\n while(fabs(term/sum_val) > 2.0*GSL_DBL_EPSILON) {\n term *= x/(b+n-1);\n sum_val += term;\n sum_err += 2.0 * 4.0 * GSL_DBL_EPSILON * fabs(term);\n n += 1.0;\n }\n result->val = sum_val;\n result->err = sum_err;\n result->err += 2.0 * fabs(term);\n return GSL_SUCCESS;\n}\n\n\n/* 1F1(1,b,x)\n * b >= 1, b integer\n */\nstatic\nint\nhyperg_1F1_1_int(const int b, const double x, gsl_sf_result * result)\n{\n if(b < 1) {\n DOMAIN_ERROR(result);\n }\n else if(b == 1) {\n return gsl_sf_exp_e(x, result);\n }\n else if(b == 2) {\n return gsl_sf_exprel_e(x, result);\n }\n else if(b == 3) {\n return gsl_sf_exprel_2_e(x, result);\n }\n else {\n return gsl_sf_exprel_n_e(b-1, x, result);\n }\n}\n\n\n/* 1F1(1,b,x)\n * b >=1, b real\n *\n * checked OK: [GJ] Thu Oct 1 16:46:35 MDT 1998\n */\nstatic\nint\nhyperg_1F1_1(const double b, const double x, gsl_sf_result * result)\n{\n double ax = fabs(x);\n double ib = floor(b + 0.1);\n\n if(b < 1.0) {\n DOMAIN_ERROR(result);\n }\n else if(b == 1.0) {\n return gsl_sf_exp_e(x, result);\n }\n else if(b >= 1.4*ax) {\n return hyperg_1F1_1_series(b, x, result);\n }\n else if(fabs(b - ib) < _1F1_INT_THRESHOLD && ib < INT_MAX) {\n return hyperg_1F1_1_int((int)ib, x, result);\n }\n else if(x > 0.0) {\n if(x > 100.0 && b < 0.75*x) {\n return hyperg_1F1_asymp_posx(1.0, b, x, result);\n }\n else if(b < 1.0e+05) {\n /* Recurse backward on b, from a\n * chosen offset point. For x > 0,\n * which holds here, this should\n * be a stable direction.\n */\n const double off = ceil(1.4*x-b) + 1.0;\n double bp = b + off;\n gsl_sf_result M;\n int stat_s = hyperg_1F1_1_series(bp, x, &M);\n const double err_rat = M.err / fabs(M.val);\n while(bp > b+0.1) {\n /* M(1,b-1) = x/(b-1) M(1,b) + 1 */\n bp -= 1.0;\n M.val = 1.0 + x/bp * M.val;\n }\n result->val = M.val;\n result->err = err_rat * fabs(M.val);\n result->err += 2.0 * GSL_DBL_EPSILON * (fabs(off)+1.0) * fabs(M.val);\n return stat_s;\n }\n else {\n return hyperg_1F1_large2bm4a(1.0, b, x, result);\n }\n }\n else {\n /* x <= 0 and b not large compared to |x|\n */\n if(ax < 10.0 && b < 10.0) {\n return hyperg_1F1_1_series(b, x, result);\n }\n else if(ax >= 100.0 && GSL_MAX_DBL(fabs(2.0-b),1.0) < 0.99*ax) {\n return hyperg_1F1_asymp_negx(1.0, b, x, result);\n }\n else {\n return hyperg_1F1_luke(1.0, b, x, result);\n }\n }\n}\n\n\n/* 1F1(a,b,x)/Gamma(b) for b->0\n * [limit of Abramowitz+Stegun 13.3.7]\n */\nstatic\nint\nhyperg_1F1_renorm_b0(const double a, const double x, gsl_sf_result * result)\n{\n double eta = a*x;\n if(eta > 0.0) {\n double root_eta = sqrt(eta);\n gsl_sf_result I1_scaled;\n int stat_I = gsl_sf_bessel_I1_scaled_e(2.0*root_eta, &I1_scaled);\n if(I1_scaled.val <= 0.0) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_ERROR_SELECT_2(stat_I, GSL_EDOM);\n }\n else {\n const double lnr_val = 0.5*x + 0.5*log(eta) + fabs(x) + log(I1_scaled.val);\n const double lnr_err = GSL_DBL_EPSILON * (1.5*fabs(x) + 1.0) + fabs(I1_scaled.err/I1_scaled.val);\n return gsl_sf_exp_err_e(lnr_val, lnr_err, result);\n }\n }\n else if(eta == 0.0) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else {\n /* eta < 0 */\n double root_eta = sqrt(-eta);\n gsl_sf_result J1;\n int stat_J = gsl_sf_bessel_J1_e(2.0*root_eta, &J1);\n if(J1.val <= 0.0) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_ERROR_SELECT_2(stat_J, GSL_EDOM);\n }\n else {\n const double t1 = 0.5*x;\n const double t2 = 0.5*log(-eta);\n const double t3 = fabs(x);\n const double t4 = log(J1.val);\n const double lnr_val = t1 + t2 + t3 + t4;\n const double lnr_err = GSL_DBL_EPSILON * (1.5*fabs(x) + 1.0) + fabs(J1.err/J1.val);\n gsl_sf_result ex;\n int stat_e = gsl_sf_exp_err_e(lnr_val, lnr_err, &ex);\n result->val = -ex.val;\n result->err = ex.err;\n return stat_e;\n }\n }\n \n}\n\n\n/* 1F1'(a,b,x)/1F1(a,b,x)\n * Uses Gautschi's version of the CF.\n * [Gautschi, Math. Comp. 31, 994 (1977)]\n *\n * Supposedly this suffers from the \"anomalous convergence\"\n * problem when b < x. I have seen anomalous convergence\n * in several of the continued fractions associated with\n * 1F1(a,b,x). This particular CF formulation seems stable\n * for b > x. However, it does display a painful artifact\n * of the anomalous convergence; the convergence plateaus\n * unless b >>> x. For example, even for b=1000, x=1, this\n * method locks onto a ratio which is only good to about\n * 4 digits. Apparently the rest of the digits are hiding\n * way out on the plateau, but finite-precision lossage\n * means you will never get them.\n */\n#if 0\nstatic\nint\nhyperg_1F1_CF1_p(const double a, const double b, const double x, double * result)\n{\n const double RECUR_BIG = GSL_SQRT_DBL_MAX;\n const int maxiter = 5000;\n int n = 1;\n double Anm2 = 1.0;\n double Bnm2 = 0.0;\n double Anm1 = 0.0;\n double Bnm1 = 1.0;\n double a1 = 1.0;\n double b1 = 1.0;\n double An = b1*Anm1 + a1*Anm2;\n double Bn = b1*Bnm1 + a1*Bnm2;\n double an, bn;\n double fn = An/Bn;\n\n while(n < maxiter) {\n double old_fn;\n double del;\n n++;\n Anm2 = Anm1;\n Bnm2 = Bnm1;\n Anm1 = An;\n Bnm1 = Bn;\n an = (a+n)*x/((b-x+n-1)*(b-x+n));\n bn = 1.0;\n An = bn*Anm1 + an*Anm2;\n Bn = bn*Bnm1 + an*Bnm2;\n\n if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) {\n An /= RECUR_BIG;\n Bn /= RECUR_BIG;\n Anm1 /= RECUR_BIG;\n Bnm1 /= RECUR_BIG;\n Anm2 /= RECUR_BIG;\n Bnm2 /= RECUR_BIG;\n }\n\n old_fn = fn;\n fn = An/Bn;\n del = old_fn/fn;\n \n if(fabs(del - 1.0) < 10.0*GSL_DBL_EPSILON) break;\n }\n\n *result = a/(b-x) * fn;\n\n if(n == maxiter)\n GSL_ERROR (\"error\", GSL_EMAXITER);\n else\n return GSL_SUCCESS;\n}\n#endif /* 0 */\n\n\n/* 1F1'(a,b,x)/1F1(a,b,x)\n * Uses Gautschi's series transformation of the\n * continued fraction. This is apparently the best\n * method for getting this ratio in the stable region.\n * The convergence is monotone and supergeometric\n * when b > x.\n * Assumes a >= -1.\n */\nstatic\nint\nhyperg_1F1_CF1_p_ser(const double a, const double b, const double x, double * result)\n{\n if(a == 0.0) {\n *result = 0.0;\n return GSL_SUCCESS;\n }\n else {\n const int maxiter = 5000;\n double sum = 1.0;\n double pk = 1.0;\n double rhok = 0.0;\n int k;\n for(k=1; k RECUR_BIG || fabs(Bn) > RECUR_BIG) {\n An /= RECUR_BIG;\n Bn /= RECUR_BIG;\n Anm1 /= RECUR_BIG;\n Bnm1 /= RECUR_BIG;\n Anm2 /= RECUR_BIG;\n Bnm2 /= RECUR_BIG;\n }\n\n old_fn = fn;\n fn = An/Bn;\n del = old_fn/fn;\n \n if(fabs(del - 1.0) < 10.0*GSL_DBL_EPSILON) break;\n }\n\n *result = fn;\n if(n == maxiter)\n GSL_ERROR (\"error\", GSL_EMAXITER);\n else\n return GSL_SUCCESS;\n}\n#endif /* 0 */\n\n\n/* 1F1(a,b+1,x)/1F1(a,b,x)\n *\n * This seemed to suffer from \"anomalous convergence\".\n * However, I have no theory for this recurrence.\n */\n#if 0\nstatic\nint\nhyperg_1F1_CF1_b(const double a, const double b, const double x, double * result)\n{\n const double RECUR_BIG = GSL_SQRT_DBL_MAX;\n const int maxiter = 5000;\n int n = 1;\n double Anm2 = 1.0;\n double Bnm2 = 0.0;\n double Anm1 = 0.0;\n double Bnm1 = 1.0;\n double a1 = b + 1.0;\n double b1 = (b + 1.0) * (b - x);\n double An = b1*Anm1 + a1*Anm2;\n double Bn = b1*Bnm1 + a1*Bnm2;\n double an, bn;\n double fn = An/Bn;\n\n while(n < maxiter) {\n double old_fn;\n double del;\n n++;\n Anm2 = Anm1;\n Bnm2 = Bnm1;\n Anm1 = An;\n Bnm1 = Bn;\n an = (b + n) * (b + n - 1.0 - a) * x;\n bn = (b + n) * (b + n - 1.0 - x);\n An = bn*Anm1 + an*Anm2;\n Bn = bn*Bnm1 + an*Bnm2;\n\n if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) {\n An /= RECUR_BIG;\n Bn /= RECUR_BIG;\n Anm1 /= RECUR_BIG;\n Bnm1 /= RECUR_BIG;\n Anm2 /= RECUR_BIG;\n Bnm2 /= RECUR_BIG;\n }\n\n old_fn = fn;\n fn = An/Bn;\n del = old_fn/fn;\n \n if(fabs(del - 1.0) < 10.0*GSL_DBL_EPSILON) break;\n }\n\n *result = fn;\n if(n == maxiter)\n GSL_ERROR (\"error\", GSL_EMAXITER);\n else\n return GSL_SUCCESS;\n}\n#endif /* 0 */\n\n\n/* 1F1(a,b,x)\n * |a| <= 1, b > 0\n */\nstatic\nint\nhyperg_1F1_small_a_bgt0(const double a, const double b, const double x, gsl_sf_result * result)\n{\n const double bma = b-a;\n const double oma = 1.0-a;\n const double ap1mb = 1.0+a-b;\n const double abs_bma = fabs(bma);\n const double abs_oma = fabs(oma);\n const double abs_ap1mb = fabs(ap1mb);\n\n const double ax = fabs(x);\n\n if(a == 0.0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(a == 1.0) {\n return hyperg_1F1_1(b, x, result);\n }\n else if(a == -1.0) {\n result->val = 1.0 + a/b * x;\n result->err = GSL_DBL_EPSILON * (1.0 + fabs(a/b * x));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(b >= 1.4*ax) {\n return gsl_sf_hyperg_1F1_series_e(a, b, x, result);\n }\n else if(x > 0.0) {\n if(x > 100.0 && abs_bma*abs_oma < 0.5*x) {\n return hyperg_1F1_asymp_posx(a, b, x, result);\n }\n else if(b < 5.0e+06) {\n /* Recurse backward on b from\n * a suitably high point.\n */\n const double b_del = ceil(1.4*x-b) + 1.0;\n double bp = b + b_del;\n gsl_sf_result r_Mbp1;\n gsl_sf_result r_Mb;\n double Mbp1;\n double Mb;\n double Mbm1;\n int stat_0 = gsl_sf_hyperg_1F1_series_e(a, bp+1.0, x, &r_Mbp1);\n int stat_1 = gsl_sf_hyperg_1F1_series_e(a, bp, x, &r_Mb);\n const double err_rat = fabs(r_Mbp1.err/r_Mbp1.val) + fabs(r_Mb.err/r_Mb.val);\n Mbp1 = r_Mbp1.val;\n Mb = r_Mb.val;\n while(bp > b+0.1) {\n /* Do backward recursion. */\n Mbm1 = ((x+bp-1.0)*Mb - x*(bp-a)/bp*Mbp1)/(bp-1.0);\n bp -= 1.0;\n\tMbp1 = Mb;\n\tMb = Mbm1;\n }\n result->val = Mb;\n result->err = err_rat * (fabs(b_del)+1.0) * fabs(Mb);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(Mb);\n return GSL_ERROR_SELECT_2(stat_0, stat_1);\n }\n else {\n return hyperg_1F1_large2bm4a(a, b, x, result);\n }\n }\n else {\n /* x < 0 and b not large compared to |x|\n */\n if(ax < 10.0 && b < 10.0) {\n return gsl_sf_hyperg_1F1_series_e(a, b, x, result);\n }\n else if(ax >= 100.0 && GSL_MAX(abs_ap1mb,1.0) < 0.99*ax) {\n return hyperg_1F1_asymp_negx(a, b, x, result);\n }\n else {\n return hyperg_1F1_luke(a, b, x, result);\n }\n }\n}\n\n\n/* 1F1(b+eps,b,x)\n * |eps|<=1, b > 0\n */\nstatic\nint\nhyperg_1F1_beps_bgt0(const double eps, const double b, const double x, gsl_sf_result * result)\n{\n if(b > fabs(x) && fabs(eps) < GSL_SQRT_DBL_EPSILON) {\n /* If b-a is very small and x/b is not too large we can\n * use this explicit approximation.\n *\n * 1F1(b+eps,b,x) = exp(ax/b) (1 - eps x^2 (v2 + v3 x + ...) + ...)\n *\n * v2 = a/(2b^2(b+1))\n * v3 = a(b-2a)/(3b^3(b+1)(b+2))\n * ...\n *\n * See [Luke, Mathematical Functions and Their Approximations, p.292]\n *\n * This cannot be used for b near a negative integer or zero.\n * Also, if x/b is large the deviation from exp(x) behaviour grows.\n */\n double a = b + eps;\n gsl_sf_result exab;\n int stat_e = gsl_sf_exp_e(a*x/b, &exab);\n double v2 = a/(2.0*b*b*(b+1.0));\n double v3 = a*(b-2.0*a)/(3.0*b*b*b*(b+1.0)*(b+2.0));\n double v = v2 + v3 * x;\n double f = (1.0 - eps*x*x*v);\n result->val = exab.val * f;\n result->err = exab.err * fabs(f);\n result->err += fabs(exab.val) * GSL_DBL_EPSILON * (1.0 + fabs(eps*x*x*v));\n result->err += 4.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_e;\n }\n else {\n /* Otherwise use a Kummer transformation to reduce\n * it to the small a case.\n */\n gsl_sf_result Kummer_1F1;\n int stat_K = hyperg_1F1_small_a_bgt0(-eps, b, -x, &Kummer_1F1);\n if(Kummer_1F1.val != 0.0) {\n int stat_e = gsl_sf_exp_mult_err_e(x, 2.0*GSL_DBL_EPSILON*fabs(x),\n Kummer_1F1.val, Kummer_1F1.err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_K);\n }\n else {\n result->val = 0.0;\n result->err = 0.0;\n return stat_K;\n }\n }\n}\n\n\n/* 1F1(a,2a,x) = Gamma(a + 1/2) E(x) (|x|/4)^(-a+1/2) scaled_I(a-1/2,|x|/2)\n *\n * E(x) = exp(x) x > 0\n * = 1 x < 0\n *\n * a >= 1/2\n */\nstatic\nint\nhyperg_1F1_beq2a_pos(const double a, const double x, gsl_sf_result * result)\n{\n if(x == 0.0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else {\n gsl_sf_result I;\n int stat_I = gsl_sf_bessel_Inu_scaled_e(a-0.5, 0.5*fabs(x), &I);\n gsl_sf_result lg;\n int stat_g = gsl_sf_lngamma_e(a + 0.5, &lg);\n double ln_term = (0.5-a)*log(0.25*fabs(x));\n double lnpre_val = lg.val + GSL_MAX_DBL(x,0.0) + ln_term;\n double lnpre_err = lg.err + GSL_DBL_EPSILON * (fabs(ln_term) + fabs(x));\n int stat_e = gsl_sf_exp_mult_err_e(lnpre_val, lnpre_err,\n \t\t\t\t\t I.val, I.err,\n \t\t\t\t\t result);\n return GSL_ERROR_SELECT_3(stat_e, stat_g, stat_I);\n }\n}\n\n\n/* Determine middle parts of diagonal recursion along b=2a\n * from two endpoints, i.e.\n *\n * given: M(a,b) and M(a+1,b+2)\n * get: M(a+1,b+1) and M(a,b+1)\n */\n#if 0\ninline\nstatic\nint\nhyperg_1F1_diag_step(const double a, const double b, const double x,\n const double Mab, const double Map1bp2,\n double * Map1bp1, double * Mabp1)\n{\n if(a == b) {\n *Map1bp1 = Mab;\n *Mabp1 = Mab - x/(b+1.0) * Map1bp2;\n }\n else {\n *Map1bp1 = Mab - x * (a-b)/(b*(b+1.0)) * Map1bp2;\n *Mabp1 = (a * *Map1bp1 - b * Mab)/(a-b);\n }\n return GSL_SUCCESS;\n}\n#endif /* 0 */\n\n\n/* Determine endpoint of diagonal recursion.\n *\n * given: M(a,b) and M(a+1,b+2)\n * get: M(a+1,b) and M(a+1,b+1)\n */\n#if 0\ninline\nstatic\nint\nhyperg_1F1_diag_end_step(const double a, const double b, const double x,\n const double Mab, const double Map1bp2,\n double * Map1b, double * Map1bp1)\n{\n *Map1bp1 = Mab - x * (a-b)/(b*(b+1.0)) * Map1bp2;\n *Map1b = Mab + x/b * *Map1bp1;\n return GSL_SUCCESS;\n}\n#endif /* 0 */\n\n\n/* Handle the case of a and b both positive integers.\n * Assumes a > 0 and b > 0.\n */\nstatic\nint\nhyperg_1F1_ab_posint(const int a, const int b, const double x, gsl_sf_result * result)\n{\n double ax = fabs(x);\n\n if(a == b) {\n return gsl_sf_exp_e(x, result); /* 1F1(a,a,x) */\n }\n else if(a == 1) {\n return gsl_sf_exprel_n_e(b-1, x, result); /* 1F1(1,b,x) */\n }\n else if(b == a + 1) {\n gsl_sf_result K;\n int stat_K = gsl_sf_exprel_n_e(a, -x, &K); /* 1F1(1,1+a,-x) */\n int stat_e = gsl_sf_exp_mult_err_e(x, 2.0 * GSL_DBL_EPSILON * fabs(x),\n \t\t\t\t\t K.val, K.err,\n \t\t\t\t\t result);\n return GSL_ERROR_SELECT_2(stat_e, stat_K);\n }\n else if(a == b + 1) {\n gsl_sf_result ex;\n int stat_e = gsl_sf_exp_e(x, &ex);\n result->val = ex.val * (1.0 + x/b);\n result->err = ex.err * (1.0 + x/b);\n result->err += ex.val * GSL_DBL_EPSILON * (1.0 + fabs(x/b));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_e;\n }\n else if(a == b + 2) {\n gsl_sf_result ex;\n int stat_e = gsl_sf_exp_e(x, &ex);\n double poly = (1.0 + x/b*(2.0 + x/(b+1.0)));\n result->val = ex.val * poly;\n result->err = ex.err * fabs(poly);\n result->err += ex.val * GSL_DBL_EPSILON * (1.0 + fabs(x/b) * (2.0 + fabs(x/(b+1.0))));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_e;\n }\n else if(b == 2*a) {\n return hyperg_1F1_beq2a_pos(a, x, result); /* 1F1(a,2a,x) */\n }\n else if( ( b < 10 && a < 10 && ax < 5.0 )\n || ( b > a*ax )\n\t || ( b > a && ax < 5.0 )\n ) {\n return gsl_sf_hyperg_1F1_series_e(a, b, x, result);\n }\n else if(b > a && b >= 2*a + x) {\n /* Use the Gautschi CF series, then\n * recurse backward to a=0 for normalization.\n * This will work for either sign of x.\n */\n double rap;\n int stat_CF1 = hyperg_1F1_CF1_p_ser(a, b, x, &rap);\n double ra = 1.0 + x/a * rap;\n double Ma\t= GSL_SQRT_DBL_MIN;\n double Map1 = ra * Ma;\n double Mnp1 = Map1;\n double Mn\t= Ma;\n double Mnm1;\n int n;\n for(n=a; n>0; n--) {\n Mnm1 = (n * Mnp1 - (2*n-b+x) * Mn) / (b-n);\n Mnp1 = Mn;\n Mn = Mnm1;\n }\n result->val = Ma/Mn;\n result->err = 2.0 * GSL_DBL_EPSILON * (fabs(a) + 1.0) * fabs(Ma/Mn);\n return stat_CF1;\n }\n else if(b > a && b < 2*a + x && b > x) {\n /* Use the Gautschi series representation of\n * the continued fraction. Then recurse forward\n * to the a=b line for normalization. This will\n * work for either sign of x, although we do need\n * to check for b > x, for when x is positive.\n */\n double rap;\n int stat_CF1 = hyperg_1F1_CF1_p_ser(a, b, x, &rap);\n double ra = 1.0 + x/a * rap;\n gsl_sf_result ex;\n int stat_ex;\n\n double Ma = GSL_SQRT_DBL_MIN;\n double Map1 = ra * Ma;\n double Mnm1 = Ma;\n double Mn\t= Map1;\n double Mnp1;\n int n;\n for(n=a+1; nval = ex.val * Ma/Mn;\n result->err = ex.err * fabs(Ma/Mn);\n result->err += 4.0 * GSL_DBL_EPSILON * (fabs(b-a)+1.0) * fabs(result->val);\n return GSL_ERROR_SELECT_2(stat_ex, stat_CF1);\n }\n else if(x >= 0.0) {\n\n if(b < a) {\n /* The point b,b is below the b=2a+x line.\n * Forward recursion on a from b,b+1 is possible.\n * Note that a > b + 1 as well, since we already tried a = b + 1.\n */\n if(x + log(fabs(x/b)) < GSL_LOG_DBL_MAX-2.0) {\n double ex = exp(x);\n int n;\n double Mnm1 = ex;\t\t /* 1F1(b,b,x) */\n \tdouble Mn = ex * (1.0 + x/b); /* 1F1(b+1,b,x) */\n \tdouble Mnp1;\n for(n=b+1; nval = Mn;\n\tresult->err = (x + 1.0) * GSL_DBL_EPSILON * fabs(Mn);\n\tresult->err *= fabs(a-b)+1.0;\n return GSL_SUCCESS;\n }\n else {\n OVERFLOW_ERROR(result);\n }\n }\n else {\n /* b > a\n * b < 2a + x \n * b <= x (otherwise we would have finished above)\n *\n * Gautschi anomalous convergence region. However, we can\n * recurse forward all the way from a=0,1 because we are\n * always underneath the b=2a+x line.\n */\n gsl_sf_result r_Mn;\n double Mnm1 = 1.0; /* 1F1(0,b,x) */\n double Mn;\t /* 1F1(1,b,x) */\n double Mnp1;\n int n;\n gsl_sf_exprel_n_e(b-1, x, &r_Mn);\n Mn = r_Mn.val;\n for(n=1; nval = Mn;\n result->err = fabs(Mn) * (1.0 + fabs(a)) * fabs(r_Mn.err / r_Mn.val);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(Mn);\n return GSL_SUCCESS;\n }\n }\n else {\n /* x < 0\n * b < a (otherwise we would have tripped one of the above)\n */\n\n if(a <= 0.5*(b-x) || a >= -x) {\n /* Gautschi continued fraction is in the anomalous region,\n * so we must find another way. We recurse down in b,\n * from the a=b line.\n */\n double ex = exp(x);\n double Manp1 = ex;\n double Man = ex * (1.0 + x/(a-1.0));\n double Manm1;\n int n;\n for(n=a-1; n>b; n--) {\n Manm1 = (-n*(1-n-x)*Man - x*(n-a)*Manp1)/(n*(n-1.0));\n Manp1 = Man;\n Man = Manm1;\n }\n result->val = Man;\n result->err = (fabs(x) + 1.0) * GSL_DBL_EPSILON * fabs(Man);\n result->err *= fabs(b-a)+1.0;\n return GSL_SUCCESS;\n }\n else {\n /* Pick a0 such that b ~= 2a0 + x, then\n * recurse down in b from a0,a0 to determine\n * the values near the line b=2a+x. Then recurse\n * forward on a from a0.\n */\n int a0 = ceil(0.5*(b-x));\n double Ma0b; /* M(a0,b) */\n double Ma0bp1; /* M(a0,b+1) */\n double Ma0p1b; /* M(a0+1,b) */\n double Mnm1;\n double Mn;\n double Mnp1;\n int n;\n {\n double ex = exp(x);\n \tdouble Ma0np1 = ex;\n \tdouble Ma0n = ex * (1.0 + x/(a0-1.0));\n \tdouble Ma0nm1;\n \tfor(n=a0-1; n>b; n--) {\n \t Ma0nm1 = (-n*(1-n-x)*Ma0n - x*(n-a0)*Ma0np1)/(n*(n-1.0));\n \t Ma0np1 = Ma0n;\n \t Ma0n = Ma0nm1;\n \t}\n\tMa0bp1 = Ma0np1;\n \tMa0b = Ma0n;\n\tMa0p1b = (b*(a0+x)*Ma0b + x*(a0-b)*Ma0bp1)/(a0*b);\n }\n\n Mnm1 = Ma0b;\n Mn = Ma0p1b;\n for(n=a0+1; nval = Mn;\n result->err = (fabs(x) + 1.0) * GSL_DBL_EPSILON * fabs(Mn);\n result->err *= fabs(b-a)+1.0;\n return GSL_SUCCESS;\n }\n }\n}\n\n\n/* Evaluate a <= 0, a integer, cases directly. (Polynomial; Horner)\n * When the terms are all positive, this\n * must work. We will assume this here.\n */\nstatic\nint\nhyperg_1F1_a_negint_poly(const int a, const double b, const double x, gsl_sf_result * result)\n{\n if(a == 0) {\n result->val = 1.0;\n result->err = 1.0;\n return GSL_SUCCESS;\n }\n else {\n int N = -a;\n double poly = 1.0;\n int k;\n for(k=N-1; k>=0; k--) {\n double t = (a+k)/(b+k) * (x/(k+1));\n double r = t + 1.0/poly;\n if(r > 0.9*GSL_DBL_MAX/poly) {\n OVERFLOW_ERROR(result);\n }\n else {\n poly *= r; /* P_n = 1 + t_n P_{n-1} */\n }\n }\n result->val = poly;\n result->err = 2.0 * (sqrt(N) + 1.0) * GSL_DBL_EPSILON * fabs(poly);\n return GSL_SUCCESS;\n }\n}\n\n\n/* Evaluate negative integer a case by relation\n * to Laguerre polynomials. This is more general than\n * the direct polynomial evaluation, but is safe\n * for all values of x.\n *\n * 1F1(-n,b,x) = n!/(b)_n Laguerre[n,b-1,x]\n *\t = n B(b,n) Laguerre[n,b-1,x]\n *\n * assumes b is not a negative integer\n */\nstatic\nint\nhyperg_1F1_a_negint_lag(const int a, const double b, const double x, gsl_sf_result * result)\n{\n const int n = -a;\n\n gsl_sf_result lag;\n const int stat_l = gsl_sf_laguerre_n_e(n, b-1.0, x, &lag);\n if(b < 0.0) {\n gsl_sf_result lnfact;\n gsl_sf_result lng1;\n gsl_sf_result lng2;\n double s1, s2;\n const int stat_f = gsl_sf_lnfact_e(n, &lnfact);\n const int stat_g1 = gsl_sf_lngamma_sgn_e(b + n, &lng1, &s1);\n const int stat_g2 = gsl_sf_lngamma_sgn_e(b, &lng2, &s2);\n const double lnpre_val = lnfact.val - (lng1.val - lng2.val);\n const double lnpre_err = lnfact.err + lng1.err + lng2.err\n + 2.0 * GSL_DBL_EPSILON * fabs(lnpre_val);\n const int stat_e = gsl_sf_exp_mult_err_e(lnpre_val, lnpre_err,\n s1*s2*lag.val, lag.err,\n result);\n return GSL_ERROR_SELECT_5(stat_e, stat_l, stat_g1, stat_g2, stat_f);\n }\n else {\n gsl_sf_result lnbeta;\n gsl_sf_lnbeta_e(b, n, &lnbeta);\n if(fabs(lnbeta.val) < 0.1) {\n /* As we have noted, when B(x,y) is near 1,\n * evaluating log(B(x,y)) is not accurate.\n * Instead we evaluate B(x,y) directly.\n */\n const double ln_term_val = log(1.25*n);\n const double ln_term_err = 2.0 * GSL_DBL_EPSILON * ln_term_val;\n gsl_sf_result beta;\n int stat_b = gsl_sf_beta_e(b, n, &beta);\n int stat_e = gsl_sf_exp_mult_err_e(ln_term_val, ln_term_err,\n lag.val, lag.err,\n result);\n result->val *= beta.val/1.25;\n result->err *= beta.val/1.25;\n return GSL_ERROR_SELECT_3(stat_e, stat_l, stat_b);\n }\n else {\n /* B(x,y) was not near 1, so it is safe to use\n * the logarithmic values.\n */\n const double ln_n = log(n);\n const double ln_term_val = lnbeta.val + ln_n;\n const double ln_term_err = lnbeta.err + 2.0 * GSL_DBL_EPSILON * fabs(ln_n);\n int stat_e = gsl_sf_exp_mult_err_e(ln_term_val, ln_term_err,\n lag.val, lag.err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_l);\n }\n }\n}\n\n\n/* Handle negative integer a case for x > 0 and\n * generic b.\n *\n * Combine [Abramowitz+Stegun, 13.6.9 + 13.6.27]\n * M(-n,b,x) = (-1)^n / (b)_n U(-n,b,x) = n! / (b)_n Laguerre^(b-1)_n(x)\n */\n#if 0\nstatic\nint\nhyperg_1F1_a_negint_U(const int a, const double b, const double x, gsl_sf_result * result)\n{\n const int n = -a;\n const double sgn = ( GSL_IS_ODD(n) ? -1.0 : 1.0 );\n double sgpoch;\n gsl_sf_result lnpoch;\n gsl_sf_result U;\n const int stat_p = gsl_sf_lnpoch_sgn_e(b, n, &lnpoch, &sgpoch);\n const int stat_U = gsl_sf_hyperg_U_e(-n, b, x, &U);\n const int stat_e = gsl_sf_exp_mult_err_e(-lnpoch.val, lnpoch.err,\n \t\t\t\t\t sgn * sgpoch * U.val, U.err,\n \t\t\t\t\t result);\n return GSL_ERROR_SELECT_3(stat_e, stat_U, stat_p);\n}\n#endif\n\n\n/* Assumes a <= -1, b <= -1, and b <= a.\n */\nstatic\nint\nhyperg_1F1_ab_negint(const int a, const int b, const double x, gsl_sf_result * result)\n{\n if(x == 0.0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(x > 0.0) {\n return hyperg_1F1_a_negint_poly(a, b, x, result);\n }\n else {\n /* Apply a Kummer transformation to make x > 0 so\n * we can evaluate the polynomial safely. Of course,\n * this assumes b <= a, which must be true for\n * a<0 and b<0, since otherwise the thing is undefined.\n */\n gsl_sf_result K;\n int stat_K = hyperg_1F1_a_negint_poly(b-a, b, -x, &K);\n int stat_e = gsl_sf_exp_mult_err_e(x, 2.0 * GSL_DBL_EPSILON * fabs(x),\n \t\t\t\t\t K.val, K.err,\n \t\t\t\t\t result);\n return GSL_ERROR_SELECT_2(stat_e, stat_K);\n }\n}\n\n\n/* [Abramowitz+Stegun, 13.1.3]\n *\n * M(a,b,x) = Gamma(1+a-b)/Gamma(2-b) x^(1-b) *\n * { Gamma(b)/Gamma(a) M(1+a-b,2-b,x) - (b-1) U(1+a-b,2-b,x) }\n *\n * b not an integer >= 2\n * a-b not a negative integer\n */\nstatic\nint\nhyperg_1F1_U(const double a, const double b, const double x, gsl_sf_result * result)\n{\n const double bp = 2.0 - b;\n const double ap = a - b + 1.0;\n\n gsl_sf_result lg_ap, lg_bp;\n double sg_ap;\n int stat_lg0 = gsl_sf_lngamma_sgn_e(ap, &lg_ap, &sg_ap);\n int stat_lg1 = gsl_sf_lngamma_e(bp, &lg_bp);\n int stat_lg2 = GSL_ERROR_SELECT_2(stat_lg0, stat_lg1);\n double t1 = (bp-1.0) * log(x);\n double lnpre_val = lg_ap.val - lg_bp.val + t1;\n double lnpre_err = lg_ap.err + lg_bp.err + 2.0 * GSL_DBL_EPSILON * fabs(t1);\n\n gsl_sf_result lg_2mbp, lg_1papmbp;\n double sg_2mbp, sg_1papmbp;\n int stat_lg3 = gsl_sf_lngamma_sgn_e(2.0-bp, &lg_2mbp, &sg_2mbp);\n int stat_lg4 = gsl_sf_lngamma_sgn_e(1.0+ap-bp, &lg_1papmbp, &sg_1papmbp);\n int stat_lg5 = GSL_ERROR_SELECT_2(stat_lg3, stat_lg4);\n double lnc1_val = lg_2mbp.val - lg_1papmbp.val;\n double lnc1_err = lg_2mbp.err + lg_1papmbp.err\n + GSL_DBL_EPSILON * (fabs(lg_2mbp.val) + fabs(lg_1papmbp.val));\n\n gsl_sf_result M;\n gsl_sf_result_e10 U;\n int stat_F = gsl_sf_hyperg_1F1_e(ap, bp, x, &M);\n int stat_U = gsl_sf_hyperg_U_e10_e(ap, bp, x, &U);\n int stat_FU = GSL_ERROR_SELECT_2(stat_F, stat_U);\n\n gsl_sf_result_e10 term_M;\n int stat_e0 = gsl_sf_exp_mult_err_e10_e(lnc1_val, lnc1_err,\n sg_2mbp*sg_1papmbp*M.val, M.err,\n &term_M);\n\n const double ombp = 1.0 - bp;\n const double Uee_val = U.e10*M_LN10;\n const double Uee_err = 2.0 * GSL_DBL_EPSILON * fabs(Uee_val);\n const double Mee_val = term_M.e10*M_LN10;\n const double Mee_err = 2.0 * GSL_DBL_EPSILON * fabs(Mee_val);\n int stat_e1;\n\n /* Do a little dance with the exponential prefactors\n * to avoid overflows in intermediate results.\n */\n if(Uee_val > Mee_val) {\n const double factorM_val = exp(Mee_val-Uee_val);\n const double factorM_err = 2.0 * GSL_DBL_EPSILON * (fabs(Mee_val-Uee_val)+1.0) * factorM_val;\n const double inner_val = term_M.val*factorM_val - ombp*U.val;\n const double inner_err =\n term_M.err*factorM_val + fabs(ombp) * U.err\n + fabs(term_M.val) * factorM_err\n + GSL_DBL_EPSILON * (fabs(term_M.val*factorM_val) + fabs(ombp*U.val));\n stat_e1 = gsl_sf_exp_mult_err_e(lnpre_val+Uee_val, lnpre_err+Uee_err,\n sg_ap*inner_val, inner_err,\n result);\n }\n else {\n const double factorU_val = exp(Uee_val - Mee_val);\n const double factorU_err = 2.0 * GSL_DBL_EPSILON * (fabs(Mee_val-Uee_val)+1.0) * factorU_val;\n const double inner_val = term_M.val - ombp*factorU_val*U.val;\n const double inner_err =\n term_M.err + fabs(ombp*factorU_val*U.err)\n + fabs(ombp*factorU_err*U.val)\n + GSL_DBL_EPSILON * (fabs(term_M.val) + fabs(ombp*factorU_val*U.val));\n stat_e1 = gsl_sf_exp_mult_err_e(lnpre_val+Mee_val, lnpre_err+Mee_err,\n sg_ap*inner_val, inner_err,\n result);\n }\n\n return GSL_ERROR_SELECT_5(stat_e1, stat_e0, stat_FU, stat_lg5, stat_lg2);\n}\n\n\n/* Handle case of generic positive a, b.\n * Assumes b-a is not a negative integer.\n */\nstatic\nint\nhyperg_1F1_ab_pos(const double a, const double b,\n const double x,\n gsl_sf_result * result)\n{\n const double ax = fabs(x);\n\n if( ( b < 10.0 && a < 10.0 && ax < 5.0 )\n || ( b > a*ax )\n || ( b > a && ax < 5.0 )\n ) {\n return gsl_sf_hyperg_1F1_series_e(a, b, x, result);\n }\n else if( x < -100.0\n && GSL_MAX_DBL(fabs(a),1.0)*GSL_MAX_DBL(fabs(1.0+a-b),1.0) < 0.7*fabs(x)\n ) {\n /* Large negative x asymptotic.\n */\n return hyperg_1F1_asymp_negx(a, b, x, result);\n }\n else if( x > 100.0\n && GSL_MAX_DBL(fabs(b-a),1.0)*GSL_MAX_DBL(fabs(1.0-a),1.0) < 0.7*fabs(x)\n ) {\n /* Large positive x asymptotic.\n */\n return hyperg_1F1_asymp_posx(a, b, x, result);\n }\n else if(fabs(b-a) <= 1.0) {\n /* Directly handle b near a.\n */\n return hyperg_1F1_beps_bgt0(a-b, b, x, result); /* a = b + eps */\n }\n\n else if(b > a && b >= 2*a + x) {\n /* Use the Gautschi CF series, then\n * recurse backward to a near 0 for normalization.\n * This will work for either sign of x.\n */ \n double rap;\n int stat_CF1 = hyperg_1F1_CF1_p_ser(a, b, x, &rap);\n double ra = 1.0 + x/a * rap;\n\n double Ma\t= GSL_SQRT_DBL_MIN;\n double Map1 = ra * Ma;\n double Mnp1 = Map1;\n double Mn\t= Ma;\n double Mnm1;\n gsl_sf_result Mn_true;\n int stat_Mt;\n double n;\n for(n=a; n>0.5; n -= 1.0) {\n Mnm1 = (n * Mnp1 - (2.0*n-b+x) * Mn) / (b-n);\n Mnp1 = Mn;\n Mn = Mnm1;\n }\n\n stat_Mt = hyperg_1F1_small_a_bgt0(n, b, x, &Mn_true);\n\n result->val = (Ma/Mn) * Mn_true.val;\n result->err = fabs(Ma/Mn) * Mn_true.err;\n result->err += 2.0 * GSL_DBL_EPSILON * (fabs(a)+1.0) * fabs(result->val);\n return GSL_ERROR_SELECT_2(stat_Mt, stat_CF1);\n }\n else if(b > a && b < 2*a + x && b > x) {\n /* Use the Gautschi series representation of\n * the continued fraction. Then recurse forward\n * to near the a=b line for normalization. This will\n * work for either sign of x, although we do need\n * to check for b > x, which is relevant when x is positive.\n */\n gsl_sf_result Mn_true;\n int stat_Mt;\n double rap;\n int stat_CF1 = hyperg_1F1_CF1_p_ser(a, b, x, &rap);\n double ra = 1.0 + x/a * rap;\n double Ma\t= GSL_SQRT_DBL_MIN;\n double Mnm1 = Ma;\n double Mn\t= ra * Mnm1;\n double Mnp1;\n double n;\n for(n=a+1.0; nval = Ma/Mn * Mn_true.val;\n result->err = fabs(Ma/Mn) * Mn_true.err;\n result->err += 2.0 * GSL_DBL_EPSILON * (fabs(b-a)+1.0) * fabs(result->val);\n return GSL_ERROR_SELECT_2(stat_Mt, stat_CF1);\n }\n else if(x >= 0.0) {\n\n if(b < a) {\n /* Forward recursion on a from a=b+eps-1,b+eps.\n */\n double N = floor(a-b);\n double eps = a - b - N;\n gsl_sf_result r_M0;\n gsl_sf_result r_M1;\n int stat_0 = hyperg_1F1_beps_bgt0(eps-1.0, b, x, &r_M0);\n int stat_1 = hyperg_1F1_beps_bgt0(eps, b, x, &r_M1);\n double M0 = r_M0.val;\n double M1 = r_M1.val;\n\n double Mam1 = M0;\n double Ma = M1;\n double Map1;\n double ap;\n double start_pair = fabs(M0) + fabs(M1);\n double minim_pair = GSL_DBL_MAX;\n double pair_ratio;\n double rat_0 = fabs(r_M0.err/r_M0.val);\n double rat_1 = fabs(r_M1.err/r_M1.val);\n for(ap=b+eps; apval = Ma;\n result->err = 2.0 * (rat_0 + rat_1 + GSL_DBL_EPSILON) * (fabs(b-a)+1.0) * fabs(Ma);\n result->err += 2.0 * (rat_0 + rat_1) * pair_ratio*pair_ratio * fabs(Ma);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(Ma);\n return GSL_ERROR_SELECT_2(stat_0, stat_1);\n }\n else {\n /* b > a\n * b < 2a + x \n * b <= x\n *\n * Recurse forward on a from a=eps,eps+1.\n */\n double eps = a - floor(a);\n gsl_sf_result r_Mnm1;\n gsl_sf_result r_Mn;\n int stat_0 = hyperg_1F1_small_a_bgt0(eps, b, x, &r_Mnm1);\n int stat_1 = hyperg_1F1_small_a_bgt0(eps+1.0, b, x, &r_Mn);\n double Mnm1 = r_Mnm1.val;\n double Mn = r_Mn.val;\n double Mnp1;\n\n double n;\n double start_pair = fabs(Mn) + fabs(Mnm1);\n double minim_pair = GSL_DBL_MAX;\n double pair_ratio;\n double rat_0 = fabs(r_Mnm1.err/r_Mnm1.val);\n double rat_1 = fabs(r_Mn.err/r_Mn.val);\n for(n=eps+1.0; nval = Mn;\n result->err = 2.0 * (rat_0 + rat_1 + GSL_DBL_EPSILON) * (fabs(a)+1.0) * fabs(Mn);\n result->err += 2.0 * (rat_0 + rat_1) * pair_ratio*pair_ratio * fabs(Mn);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(Mn);\n return GSL_ERROR_SELECT_2(stat_0, stat_1);\n }\n }\n else {\n /* x < 0\n * b < a\n */\n\n if(a <= 0.5*(b-x) || a >= -x) {\n /* Recurse down in b, from near the a=b line, b=a+eps,a+eps-1.\n */\n double N = floor(a - b);\n double eps = 1.0 + N - a + b;\n gsl_sf_result r_Manp1;\n gsl_sf_result r_Man;\n int stat_0 = hyperg_1F1_beps_bgt0(-eps, a+eps, x, &r_Manp1);\n int stat_1 = hyperg_1F1_beps_bgt0(1.0-eps, a+eps-1.0, x, &r_Man);\n double Manp1 = r_Manp1.val;\n double Man = r_Man.val;\n double Manm1;\n\n double n;\n double start_pair = fabs(Manp1) + fabs(Man);\n double minim_pair = GSL_DBL_MAX;\n double pair_ratio;\n double rat_0 = fabs(r_Manp1.err/r_Manp1.val);\n double rat_1 = fabs(r_Man.err/r_Man.val);\n for(n=a+eps-1.0; n>b+0.1; n -= 1.0) {\n Manm1 = (-n*(1-n-x)*Man - x*(n-a)*Manp1)/(n*(n-1.0));\n Manp1 = Man;\n Man = Manm1;\n minim_pair = GSL_MIN_DBL(fabs(Manp1) + fabs(Man), minim_pair);\n }\n\n /* FIXME: this is a nasty little hack; there is some\n (transient?) instability in this recurrence for some\n\t values. I can tell when it happens, which is when\n\t this pair_ratio is large. But I do not know how to\n\t measure the error in terms of it. I guessed quadratic\n\t below, but it is probably worse than that.\n\t */\n pair_ratio = start_pair/minim_pair;\n result->val = Man;\n result->err = 2.0 * (rat_0 + rat_1 + GSL_DBL_EPSILON) * (fabs(b-a)+1.0) * fabs(Man);\n result->err *= pair_ratio*pair_ratio + 1.0;\n return GSL_ERROR_SELECT_2(stat_0, stat_1);\n }\n else {\n /* Pick a0 such that b ~= 2a0 + x, then\n * recurse down in b from a0,a0 to determine\n * the values near the line b=2a+x. Then recurse\n * forward on a from a0.\n */\n double epsa = a - floor(a);\n double a0 = floor(0.5*(b-x)) + epsa;\n double N = floor(a0 - b);\n double epsb = 1.0 + N - a0 + b;\n double Ma0b;\n double Ma0bp1;\n double Ma0p1b;\n int stat_a0;\n double Mnm1;\n double Mn;\n double Mnp1;\n double n;\n double err_rat;\n {\n \tgsl_sf_result r_Ma0np1;\n \tgsl_sf_result r_Ma0n;\n int stat_0 = hyperg_1F1_beps_bgt0(-epsb, a0+epsb, x, &r_Ma0np1);\n int stat_1 = hyperg_1F1_beps_bgt0(1.0-epsb, a0+epsb-1.0, x, &r_Ma0n);\n \tdouble Ma0np1 = r_Ma0np1.val;\n \tdouble Ma0n = r_Ma0n.val;\n \tdouble Ma0nm1;\n\n\terr_rat = fabs(r_Ma0np1.err/r_Ma0np1.val) + fabs(r_Ma0n.err/r_Ma0n.val);\n\n \tfor(n=a0+epsb-1.0; n>b+0.1; n -= 1.0) {\n \t Ma0nm1 = (-n*(1-n-x)*Ma0n - x*(n-a0)*Ma0np1)/(n*(n-1.0));\n Ma0np1 = Ma0n;\n Ma0n = Ma0nm1;\n }\n\tMa0bp1 = Ma0np1;\n Ma0b = Ma0n;\n\tMa0p1b = (b*(a0+x)*Ma0b+x*(a0-b)*Ma0bp1)/(a0*b); /* right-down hook */\n\tstat_a0 = GSL_ERROR_SELECT_2(stat_0, stat_1);\n }\n\n \n /* Initialise the recurrence correctly BJG */\n\n if (a0 >= a - 0.1)\n { \n Mn = Ma0b;\n }\n else if (a0 + 1>= a - 0.1)\n {\n Mn = Ma0p1b;\n }\n else\n {\n Mnm1 = Ma0b;\n Mn = Ma0p1b;\n\n for(n=a0+1.0; nval = Mn;\n result->err = (err_rat + GSL_DBL_EPSILON) * (fabs(b-a)+1.0) * fabs(Mn);\n return stat_a0;\n }\n }\n}\n\n\n/* Assumes b != integer\n * Assumes a != integer when x > 0\n * Assumes b-a != neg integer when x < 0\n */\nstatic\nint\nhyperg_1F1_ab_neg(const double a, const double b, const double x,\n gsl_sf_result * result)\n{\n const double bma = b - a;\n const double abs_x = fabs(x);\n const double abs_a = fabs(a);\n const double abs_b = fabs(b);\n const double size_a = GSL_MAX(abs_a, 1.0);\n const double size_b = GSL_MAX(abs_b, 1.0);\n const int bma_integer = ( bma - floor(bma+0.5) < _1F1_INT_THRESHOLD );\n\n if( (abs_a < 10.0 && abs_b < 10.0 && abs_x < 5.0)\n || (b > 0.8*GSL_MAX(fabs(a),1.0)*fabs(x))\n ) {\n return gsl_sf_hyperg_1F1_series_e(a, b, x, result);\n }\n else if( x > 0.0\n && size_b > size_a\n && size_a*log(M_E*x/size_b) < GSL_LOG_DBL_EPSILON+7.0\n ) {\n /* Series terms are positive definite up until\n * there is a sign change. But by then the\n * terms are small due to the last condition.\n */\n return gsl_sf_hyperg_1F1_series_e(a, b, x, result);\n }\n else if( (abs_x < 5.0 && fabs(bma) < 10.0 && abs_b < 10.0)\n || (b > 0.8*GSL_MAX_DBL(fabs(bma),1.0)*abs_x)\n ) {\n /* Use Kummer transformation to render series safe.\n */\n gsl_sf_result Kummer_1F1;\n int stat_K = gsl_sf_hyperg_1F1_series_e(bma, b, -x, &Kummer_1F1);\n int stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x),\n Kummer_1F1.val, Kummer_1F1.err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_K);\n }\n else if( x < -30.0\n && GSL_MAX_DBL(fabs(a),1.0)*GSL_MAX_DBL(fabs(1.0+a-b),1.0) < 0.99*fabs(x)\n ) {\n /* Large negative x asymptotic.\n * Note that we do not check if b-a is a negative integer.\n */\n return hyperg_1F1_asymp_negx(a, b, x, result);\n }\n else if( x > 100.0\n && GSL_MAX_DBL(fabs(bma),1.0)*GSL_MAX_DBL(fabs(1.0-a),1.0) < 0.99*fabs(x)\n ) {\n /* Large positive x asymptotic.\n * Note that we do not check if a is a negative integer.\n */\n return hyperg_1F1_asymp_posx(a, b, x, result);\n }\n else if(x > 0.0 && !(bma_integer && bma > 0.0)) {\n return hyperg_1F1_U(a, b, x, result);\n }\n else {\n /* FIXME: if all else fails, try the series... BJG */\n if (x < 0.0) {\n /* Apply Kummer Transformation */\n int status = gsl_sf_hyperg_1F1_series_e(b-a, b, -x, result);\n double K_factor = exp(x);\n result->val *= K_factor;\n result->err *= K_factor;\n return status;\n } else {\n int status = gsl_sf_hyperg_1F1_series_e(a, b, x, result);\n return status;\n }\n\n /* Sadness... */\n /* result->val = 0.0; */\n /* result->err = 0.0; */\n /* GSL_ERROR (\"error\", GSL_EUNIMPL); */\n }\n}\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_hyperg_1F1_int_e(const int a, const int b, const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x == 0.0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(a == b) {\n return gsl_sf_exp_e(x, result);\n }\n else if(b == 0) {\n DOMAIN_ERROR(result);\n }\n else if(a == 0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(b < 0 && (a < b || a > 0)) {\n /* Standard domain error due to singularity. */\n DOMAIN_ERROR(result);\n }\n else if(x > 100.0 && GSL_MAX_DBL(1.0,fabs(b-a))*GSL_MAX_DBL(1.0,fabs(1-a)) < 0.5 * x) {\n /* x -> +Inf asymptotic */\n return hyperg_1F1_asymp_posx(a, b, x, result);\n }\n else if(x < -100.0 && GSL_MAX_DBL(1.0,fabs(a))*GSL_MAX_DBL(1.0,fabs(1+a-b)) < 0.5 * fabs(x)) {\n /* x -> -Inf asymptotic */\n return hyperg_1F1_asymp_negx(a, b, x, result);\n }\n else if(a < 0 && b < 0) {\n return hyperg_1F1_ab_negint(a, b, x, result);\n }\n else if(a < 0 && b > 0) {\n /* Use Kummer to reduce it to the positive integer case.\n * Note that b > a, strictly, since we already trapped b = a.\n */\n gsl_sf_result Kummer_1F1;\n int stat_K = hyperg_1F1_ab_posint(b-a, b, -x, &Kummer_1F1);\n int stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x),\n Kummer_1F1.val, Kummer_1F1.err,\n result); \n return GSL_ERROR_SELECT_2(stat_e, stat_K);\n }\n else {\n /* a > 0 and b > 0 */\n return hyperg_1F1_ab_posint(a, b, x, result);\n }\n}\n\n\nint\ngsl_sf_hyperg_1F1_e(const double a, const double b, const double x,\n gsl_sf_result * result\n )\n{\n const double bma = b - a;\n const double rinta = floor(a + 0.5);\n const double rintb = floor(b + 0.5);\n const double rintbma = floor(bma + 0.5);\n const int a_integer = ( fabs(a-rinta) < _1F1_INT_THRESHOLD && rinta > INT_MIN && rinta < INT_MAX );\n const int b_integer = ( fabs(b-rintb) < _1F1_INT_THRESHOLD && rintb > INT_MIN && rintb < INT_MAX );\n const int bma_integer = ( fabs(bma-rintbma) < _1F1_INT_THRESHOLD && rintbma > INT_MIN && rintbma < INT_MAX );\n const int b_neg_integer = ( b < -0.1 && b_integer );\n const int a_neg_integer = ( a < -0.1 && a_integer );\n const int bma_neg_integer = ( bma < -0.1 && bma_integer );\n\n /* CHECK_POINTER(result) */\n\n if(x == 0.0) {\n /* Testing for this before testing a and b\n * is somewhat arbitrary. The result is that\n * we have 1F1(a,0,0) = 1.\n */\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(b == 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(a == 0.0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(a == b) {\n /* case: a==b; exp(x)\n * It's good to test exact equality now.\n * We also test approximate equality later.\n */\n return gsl_sf_exp_e(x, result);\n }\n else if(fabs(b) < _1F1_INT_THRESHOLD) {\n /* Note that neither a nor b is zero, since\n * we eliminated that with the above tests.\n */\n if(fabs(a) < _1F1_INT_THRESHOLD) {\n /* a and b near zero: 1 + a/b (exp(x)-1)\n */\n gsl_sf_result exm1;\n int stat_e = gsl_sf_expm1_e(x, &exm1);\n double sa = ( a > 0.0 ? 1.0 : -1.0 );\n double sb = ( b > 0.0 ? 1.0 : -1.0 );\n double lnab = log(fabs(a/b)); /* safe */\n gsl_sf_result hx;\n int stat_hx = gsl_sf_exp_mult_err_e(lnab, GSL_DBL_EPSILON * fabs(lnab),\n \t\t\t\t sa * sb * exm1.val, exm1.err,\n \t\t\t\t &hx);\n result->val = (hx.val == GSL_DBL_MAX ? hx.val : 1.0 + hx.val); /* FIXME: excessive paranoia ? what is DBL_MAX+1 ?*/\n result->err = hx.err;\n return GSL_ERROR_SELECT_2(stat_hx, stat_e);\n }\n else {\n /* b near zero and a not near zero\n */\n const double m_arg = 1.0/(0.5*b);\n gsl_sf_result F_renorm;\n int stat_F = hyperg_1F1_renorm_b0(a, x, &F_renorm);\n int stat_m = gsl_sf_multiply_err_e(m_arg, 2.0 * GSL_DBL_EPSILON * m_arg,\n 0.5*F_renorm.val, 0.5*F_renorm.err,\n\t\t\t\t result);\n return GSL_ERROR_SELECT_2(stat_m, stat_F);\n }\n }\n else if(a_integer && b_integer) {\n /* Check for reduction to the integer case.\n * Relies on the arbitrary \"near an integer\" test.\n */\n return gsl_sf_hyperg_1F1_int_e((int)rinta, (int)rintb, x, result);\n }\n else if(b_neg_integer && !(a_neg_integer && a > b)) {\n /* Standard domain error due to\n * uncancelled singularity.\n */\n DOMAIN_ERROR(result);\n }\n else if(a_neg_integer) {\n return hyperg_1F1_a_negint_lag((int)rinta, b, x, result);\n }\n else if(b > 0.0) {\n if(-1.0 <= a && a <= 1.0) {\n /* Handle small a explicitly.\n */\n return hyperg_1F1_small_a_bgt0(a, b, x, result);\n }\n else if(bma_neg_integer) {\n /* Catch this now, to avoid problems in the\n * generic evaluation code.\n */\n gsl_sf_result Kummer_1F1;\n int stat_K = hyperg_1F1_a_negint_lag((int)rintbma, b, -x, &Kummer_1F1);\n int stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x),\n \t\t\t\t Kummer_1F1.val, Kummer_1F1.err,\n \t\t\t\t result);\n return GSL_ERROR_SELECT_2(stat_e, stat_K);\n }\n else if(a < 0.0) {\n /* Use Kummer to reduce it to the generic positive case.\n * Note that b > a, strictly, since we already trapped b = a.\n * Also b-(b-a)=a, and a is not a negative integer here,\n * so the generic evaluation is safe.\n */\n gsl_sf_result Kummer_1F1;\n int stat_K = hyperg_1F1_ab_pos(b-a, b, -x, &Kummer_1F1);\n int stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x),\n \t\t\t\t Kummer_1F1.val, Kummer_1F1.err,\n \t\t\t\t result);\n return GSL_ERROR_SELECT_2(stat_e, stat_K);\n }\n else {\n /* a > 0.0 */\n return hyperg_1F1_ab_pos(a, b, x, result);\n }\n }\n else {\n /* b < 0.0 */\n\n if(bma_neg_integer && x < 0.0) {\n /* Handle this now to prevent problems\n * in the generic evaluation.\n */\n gsl_sf_result K;\n int stat_K;\n int stat_e;\n if(a < 0.0) {\n /* Kummer transformed version of safe polynomial.\n\t * The condition a < 0 is equivalent to b < b-a,\n\t * which is the condition required for the series\n\t * to be positive definite here.\n */\n stat_K = hyperg_1F1_a_negint_poly((int)rintbma, b, -x, &K);\n }\n else {\n /* Generic eval for negative integer a. */\n\tstat_K = hyperg_1F1_a_negint_lag((int)rintbma, b, -x, &K);\n }\n stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x),\n K.val, K.err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_K);\n }\n else if(a > 0.0) {\n /* Use Kummer to reduce it to the generic negative case.\n */\n gsl_sf_result K;\n int stat_K = hyperg_1F1_ab_neg(b-a, b, -x, &K);\n int stat_e = gsl_sf_exp_mult_err_e(x, GSL_DBL_EPSILON * fabs(x),\n \t\t\t\t K.val, K.err,\n \t\t\t\t result);\n return GSL_ERROR_SELECT_2(stat_e, stat_K);\n }\n else {\n return hyperg_1F1_ab_neg(a, b, x, result);\n }\n }\n}\n\n\n \n#if 0 \n /* Luke in the canonical case.\n */\n if(x < 0.0 && !a_neg_integer && !bma_neg_integer) {\n double prec;\n return hyperg_1F1_luke(a, b, x, result, &prec);\n }\n\n\n /* Luke with Kummer transformation.\n */\n if(x > 0.0 && !a_neg_integer && !bma_neg_integer) {\n double prec;\n double Kummer_1F1;\n double ex;\n int stat_F = hyperg_1F1_luke(b-a, b, -x, &Kummer_1F1, &prec);\n int stat_e = gsl_sf_exp_e(x, &ex);\n if(stat_F == GSL_SUCCESS && stat_e == GSL_SUCCESS) {\n double lnr = log(fabs(Kummer_1F1)) + x;\n if(lnr < GSL_LOG_DBL_MAX) {\n *result = ex * Kummer_1F1;\n\treturn GSL_SUCCESS;\n }\n else {\n *result = GSL_POSINF; \n\tGSL_ERROR (\"overflow\", GSL_EOVRFLW);\n }\n }\n else if(stat_F != GSL_SUCCESS) {\n *result = 0.0;\n return stat_F;\n }\n else {\n *result = 0.0;\n return stat_e;\n }\n }\n#endif\n\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_hyperg_1F1_int(const int m, const int n, double x)\n{\n EVAL_RESULT(gsl_sf_hyperg_1F1_int_e(m, n, x, &result));\n}\n\ndouble gsl_sf_hyperg_1F1(double a, double b, double x)\n{\n EVAL_RESULT(gsl_sf_hyperg_1F1_e(a, b, x, &result));\n}\n", "meta": {"hexsha": "c18fc705588837ec45f57a1bbe8522ad7558edf6", "size": 58010, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/hyperg_1F1.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/hyperg_1F1.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/hyperg_1F1.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": 29.1214859438, "max_line_length": 122, "alphanum_fraction": 0.5646440269, "num_tokens": 20566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5869522915184043}} {"text": "#include \n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n#define WORKSIZE 100000\n\nstatic double R8;\nstatic double r_tophat;\n\nstatic double AA, BB, CC;\nstatic double nu;\nstatic double Norm;\n\n\nstatic int NPowerTable;\n\nstatic struct pow_table\n{\n double logk, logD;\n}\n *PowerTable;\n\n\ndouble PowerSpec(double k)\n{\n double power = 0;\n\n switch (WhichSpectrum)\n {\n case 1:\n power = PowerSpec_EH(k);\n break;\n\n case 2:\n power = PowerSpec_Tabulated(k);\n break;\n\n default:\n power = PowerSpec_Efstathiou(k);\n break;\n }\n\n power *= pow(k, PrimordialIndex - 1.0);\n\n return power;\n}\n\n\nvoid read_power_table(void)\n{\n FILE *fd;\n char buf[500];\n double k, p;\n\n\n sprintf(buf, FileWithInputSpectrum);\n\n if(!(fd = fopen(buf, \"r\")))\n {\n printf(\"can't read input spectrum in file '%s' on task %d\\n\", buf, ThisTask);\n FatalError(17);\n }\n\n NPowerTable = 0;\n do\n {\n if(fscanf(fd, \" %lg %lg \", &k, &p) == 2)\n\n\tNPowerTable++;\n else\n\tbreak;\n }\n while(1);\n\n fclose(fd);\n\n\n if(ThisTask == 0)\n {\n printf(\"found %d rows in input spectrum table\\n\", NPowerTable);\n fflush(stdout);\n }\n\n\n PowerTable = malloc(NPowerTable * sizeof(struct pow_table));\n\n sprintf(buf, FileWithInputSpectrum);\n\n if(!(fd = fopen(buf, \"r\")))\n {\n printf(\"can't read input spectrum in file '%s' on task %d\\n\", buf, ThisTask);\n FatalError(18);\n }\n\n NPowerTable = 0;\n do\n {\n double p;\n\n if(fscanf(fd, \" %lg %lg \", &k, &p) == 2)\n\t{\n\t PowerTable[NPowerTable].logk = k;\n\t PowerTable[NPowerTable].logD = p;\n\t NPowerTable++;\n\t}\n else\n\tbreak;\n }\n while(1);\n\n fclose(fd);\n\n qsort(PowerTable, NPowerTable, sizeof(struct pow_table), compare_logk);\n}\n\nint compare_logk(const void *a, const void *b)\n{\n if(((struct pow_table *) a)->logk < (((struct pow_table *) b)->logk))\n return -1;\n\n if(((struct pow_table *) a)->logk > (((struct pow_table *) b)->logk))\n return +1;\n\n return 0;\n}\n\nvoid initialize_powerspectrum(void)\n{\n double res;\n\n InitTime = 1 / (1 + Redshift);\n\n AA = 6.4 / ShapeGamma * (3.085678e24 / UnitLength_in_cm);\n BB = 3.0 / ShapeGamma * (3.085678e24 / UnitLength_in_cm);\n CC = 1.7 / ShapeGamma * (3.085678e24 / UnitLength_in_cm);\n nu = 1.13;\n\n R8 = 8 * (3.085678e24 / UnitLength_in_cm);\t/* 8 Mpc/h */\n\n\n if(WhichSpectrum == 2)\n read_power_table();\n\n if(ReNormalizeInputSpectrum == 0 && WhichSpectrum == 2)\n {\n Norm = 1.0;\n /* tabulated file is already at the initial redshift */\n Dplus = 1.0;\n }\n else\n {\n Norm = 1.0;\n res = TopHatSigma2(R8);\n if(ThisTask == 0 && WhichSpectrum == 2)\n\tprintf(\"\\nNormalization of spectrum in file: Sigma8 = %g\\n\", sqrt(res));\n\n Norm = Sigma8 * Sigma8 / res;\n\n if(ThisTask == 0 && WhichSpectrum == 2)\n\tprintf(\"Normalization adjusted to Sigma8=%g (Normfac=%g)\\n\\n\", Sigma8, Norm);\n\n Dplus = GrowthFactor(InitTime, 1.0);\n }\n}\n\ndouble PowerSpec_Tabulated(double k)\n{\n double logk, logD, P, kold, u, dlogk, Delta2;\n int binlow, binhigh, binmid;\n\n kold = k;\n\n k *= (InputSpectrum_UnitLength_in_cm / UnitLength_in_cm);\t/* convert to h/Mpc */\n\n logk = log10(k);\n\n if(logk < PowerTable[0].logk || logk > PowerTable[NPowerTable - 1].logk)\n return 0;\n\n binlow = 0;\n binhigh = NPowerTable - 1;\n\n while(binhigh - binlow > 1)\n {\n binmid = (binhigh + binlow) / 2;\n if(logk < PowerTable[binmid].logk)\n\tbinhigh = binmid;\n else\n\tbinlow = binmid;\n }\n\n dlogk = PowerTable[binhigh].logk - PowerTable[binlow].logk;\n\n if(dlogk == 0)\n FatalError(777);\n\n u = (logk - PowerTable[binlow].logk) / dlogk;\n\n logD = (1 - u) * PowerTable[binlow].logD + u * PowerTable[binhigh].logD;\n\n Delta2 = pow(10.0, logD);\n\n P = Norm * Delta2 / (4 * M_PI * kold * kold * kold);\n\n return P;\n}\n\n\ndouble PowerSpec_Efstathiou(double k)\n{\n return Norm * k / pow(1 + pow(AA * k + pow(BB * k, 1.5) + CC * CC * k * k, nu), 2 / nu);\n}\n\ndouble PowerSpec_EH(double k)\t/* Eisenstein & Hu */\n{\n return Norm * k * pow(tk_eh(k), 2);\n}\n\n\ndouble tk_eh(double k)\t\t/* from Martin White */\n{\n double q, theta, ommh2, a, s, gamma, L0, C0;\n double tmp;\n double omegam, ombh2, hubble;\n\n /* other input parameters */\n hubble = HubbleParam;\n\n omegam = Omega;\n ombh2 = OmegaBaryon * HubbleParam * HubbleParam;\n\n if(OmegaBaryon == 0)\n ombh2 = 0.04 * HubbleParam * HubbleParam;\n\n k *= (3.085678e24 / UnitLength_in_cm);\t/* convert to h/Mpc */\n\n theta = 2.728 / 2.7;\n ommh2 = omegam * hubble * hubble;\n s = 44.5 * log(9.83 / ommh2) / sqrt(1. + 10. * exp(0.75 * log(ombh2))) * hubble;\n a = 1. - 0.328 * log(431. * ommh2) * ombh2 / ommh2\n + 0.380 * log(22.3 * ommh2) * (ombh2 / ommh2) * (ombh2 / ommh2);\n gamma = a + (1. - a) / (1. + exp(4 * log(0.43 * k * s)));\n gamma *= omegam * hubble;\n q = k * theta * theta / gamma;\n L0 = log(2. * exp(1.) + 1.8 * q);\n C0 = 14.2 + 731. / (1. + 62.5 * q);\n tmp = L0 / (L0 + C0 * q * q);\n return (tmp);\n}\n\n\n\ndouble TopHatSigma2(double R)\n{\n double result, abserr;\n gsl_integration_workspace *workspace;\n gsl_function F;\n\n workspace = gsl_integration_workspace_alloc(WORKSIZE);\n\n F.function = &sigma2_int;\n\n r_tophat = R;\n\n gsl_integration_qag(&F, 0, 500.0 * 1 / R,\n\t\t 0, 1.0e-4, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);\n\n gsl_integration_workspace_free(workspace);\n\n return result;\n\n /* note: 500/R is here chosen as (effectively) infinity integration boundary */\n}\n\n\ndouble sigma2_int(double k, void *param)\n{\n double kr, kr3, kr2, w, x;\n\n kr = r_tophat * k;\n kr2 = kr * kr;\n kr3 = kr2 * kr;\n\n if(kr < 1e-8)\n return 0;\n\n w = 3 * (sin(kr) / kr3 - cos(kr) / kr2);\n x = 4 * PI * k * k * w * w * PowerSpec(k);\n\n return x;\n}\n\n\ndouble GrowthFactor(double astart, double aend)\n{\n return growth(aend) / growth(astart);\n}\n\n\ndouble growth(double a)\n{\n double hubble_a;\n\n hubble_a = sqrt(Omega / (a * a * a) + (1 - Omega - OmegaLambda) / (a * a) + OmegaLambda);\n\n double result, abserr;\n gsl_integration_workspace *workspace;\n gsl_function F;\n\n workspace = gsl_integration_workspace_alloc(WORKSIZE);\n\n F.function = &growth_int;\n\n gsl_integration_qag(&F, 0, a, 0, 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);\n\n gsl_integration_workspace_free(workspace);\n\n return hubble_a * result;\n}\n\n\ndouble growth_int(double a, void *param)\n{\n return pow(a / (Omega + (1 - Omega - OmegaLambda) * a + OmegaLambda * a * a * a), 1.5);\n}\n\n\ndouble F_Omega(double a)\n{\n double omega_a;\n\n omega_a = Omega / (Omega + a * (1 - Omega - OmegaLambda) + a * a * a * OmegaLambda);\n\n return pow(omega_a, 0.6);\n}\n", "meta": {"hexsha": "7311d9d153167c269c463c9705b6cb8e64362e1a", "size": 6657, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/N-GenIC/power_debug.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/N-GenIC/power_debug.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/N-GenIC/power_debug.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6371681416, "max_line_length": 101, "alphanum_fraction": 0.6070301938, "num_tokens": 2292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.5869503025690826}} {"text": "// Sammlung verwendeter Funktionen\n#include \"global.h\"\n#include \"steppmethods.h\"\n#include \"targets.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"utility.h\"\n#include \n#include \n#include \n\n\n\n\n\n\n\n\ndouble Norm_Diff(double *vec1,double *vec2, int dim, int p) //berechnet norm von || vec1-vec2 ||_p\n{\n\tdouble result = 0.0d;\n\tdouble temp;\n\tif (p == 1)\n\t{\n\t\tfor (int i = 0; i < DIM; i++)\n\t\t{\n\t\t\tresult += fabs(vec1[i] - vec2[i]); \n\t\t}\n\t\treturn(result);\t\n\t}\n\tif (p == 2)\n\t{\n\t\tfor (int i = 0; i < DIM; i++)\n\t\t{\n\t\t\tresult += pow(vec1[i] - vec2[i],2.0); \n\t\t}\n\t\treturn(sqrt(result));\t\n\t}\n\tif (p == 0)\n\t{\n\t\tfor (int i = 0; i < DIM; i++)\n\t\t{\n\t\t\ttemp = fabs(vec1[i] - vec2[i]);\n\t\t\tif (result < temp)\n\t\t\t{\n\t\t\t\tresult = temp;\n\t\t\t} \n\t\t}\n\t\treturn(result);\t\n\t}\n\treturn (0.0f);\n}\n\n\nvoid Lattice_Setup(double **positions,int numbertoinf,int dim, double latticespacing) // puts coordinates into lattice matrix of dimension numbertoinf**dim, dim\n{\n\tprintf(\"setze Gitter auf \\n\");\n\tint m = -numbertoinf + 1;\n\tint l = -numbertoinf + 1;\n\tint count = 0;\n\twhile(count (numbertoinf - 1) ) // if over line, restart\n\t\t{\n\t\t\tm = -numbertoinf +1;\n\t\t\tl = l + 2; \n\t\t}\n\t\tpositions[count][0] = m * latticespacing/2;\n\t\tpositions[count][1] = l * latticespacing/2;\n\t\tm = m + 2;\n\t\tcount = count +1;\n\t}\n\tprintf(\"Gitter aufgesetzt \\n\");\n}\n\nint ipow(int base, int exp) // I^p for integer i\n{\n\tint result = 1;\n\tif(\t\t(base < 0)\\\n\t\t||\t(exp < 0))\n\t{\n\t\tprintf(\"wrong base or exponent, smaller zero!\\n\");\n\t\texit;\n\t}\n\twhile (exp)\n\t{\n\t\tif (exp & 1)\n\t\t\tresult *= base;\n\t\texp >>= 1;\n\t\tbase *= base;\n\t}\n\treturn result;\n}\n\nint Kahan_Sum(int N, double input[], double *ans){ // Add elements via Kahan summation, code is pretty much Wikipedia copy paste\n\tint i;\n\tdouble y,t,sum = 0.0d;\n double c = 0.0d; // A running compensation for lost low-order bits.\n for (i=0; i=0.0) sum += input[i];\n\t} \t\t\n\t*ans = sum + negsum;\n\treturn 0;\n}\n\nint Neumaier_Sum(int N, double input[N], double *ans){ // Add elements of input by Neumaier summation\n\tint i;\n\tdouble t,sum = input[0];\n double c = 0.0; // A running compensation for lost low-order bits.\n for (i=1; i=fabs(input[i]))\n \t{\n \tc += (sum - t) + input[i]; // If sum is bigger, low-order digits of input[i] are lost.\t\n } else\n {\n c += (input[i] - t) + sum; // Else low-order digits of sum are lost\n }\n sum = t;\n } // Next time around, the lost low part will be added to y in a fresh attempt. \n *ans = (sum + c); // Correction only applied once in the very end\n return 0;\n}\n\n\nvoid deleteSpaces(char src[], char dst[]){ // deletes spaces from string\n // src is supposed to be zero ended\n // dst is supposed to be large enough to hold src\n\tint s, d=0;\n\tfor (s=0; src[s] != 0; s++)\n\t\tif (src[s] != ' ') \n\t\t{\n\t\t\tdst[d] = src[s];\n\t\t\tif (dst[d] == ':') \n\t\t\t{\n\t\t\t\tdst[d] = '_';\n\t\t\t}\n\t\t\td++;\n\t\t}\n\t\t\n\t\tdst[d] = 0;\n\t}\n\n\nvoid vec_zero(double *v,int N){ // zero target vector of double\n\tint i;\n\tfor (i= 0 ; i < N; i++)\n\t{\n\t\tv[i] = 0.0;\t\n\t}\t\n\n}\nvoid vec_zero_i(int *v,int N){ // zero target vector of ints\n\tint i;\n\tfor (i= 0 ; i < N; i++)\n\t{\n\t\tv[i] = 0;\t\n\t}\t\n\n}\nvoid zero_Impuls(double *v)\n{ \t\t\t\t\t\t\t\t// zero target vector of momenta\n\tdouble P[OSSZI + 1];\n\tdouble sum;\n\tdouble OS = OSSZI * 1.0;\n\tfor (int j = 0; j < DIM; j++)\n\t{\t\n\t\tfor (int i = 0; i < OSSZI; i++)\n\t\t{\n\t\t\tP[i] = v[DIM + i * DIM + j]; \n\t\t}\n\t\tP[OSSZI] = v[j] * mass;\t\n\t\tSum_Method(OSSZI+1,P,&sum);\n\t\tfor (int i = 0; i < OSSZI; i++)\n\t\t{\n\t\t\tv[DIM + i * DIM + j] -= sum/( OS + 1.0); \n\t\t}\n\t\tv[j] -= sum/( OS + 1.0) /mass;\n\t}\t\n}\n\nint Update_Lattice_Position(int * pos, const double *vec, const double lattice_spacing){ // updatet Int-Vector pos when leaving square lattice cell\n\t\n\tint ret_val = 0;\t\t\t// return zero if no update neccessary, -1 if out of bounds\n\tfor (int j = 0; j< DIM; j++)\n\t{\n\t\tint trigger = 1;\n\t\twhile(trigger)\n\t\t{\n\t\t\tif (vec[j]< pos[j]*lattice_spacing - lattice_spacing/2.0)\t\n\t\t\t{\n\t\t\t\tpos[j]-=1;\n\t\t\t\ttrigger = 1;\n\t\t\t\tret_val = 1;\n\t\t\t}else \n\t\t\t{\n\t\t\t\ttrigger = 0;\n\t\t\t}\n\t\t\tif (vec[j]> pos[j]*lattice_spacing + lattice_spacing/2.0)\n\t\t\t{\n\t\t\t\tpos[j]+=1;\n\t\t\t\ttrigger = 1;\n\t\t\t\tret_val = 1;\n\t\t\t}else\n\t\t\t{\n\t\t\t\ttrigger = 0;\n\t\t\t}\n\t\t}\n\t}\n\tif ((abs(pos[0])> NUMBER_TO_INF) || (abs(pos[1])> NUMBER_TO_INF))\n\t{\n\t\tprintf(\" \\n particle out of bounds\");\n\t\tFLAG_DUMP_VALUE = 1;\t\t\t\t\t\t\t\t\t\t\t// error occured\n\t\treturn(-1);\n\t}\n\treturn(ret_val);\n}\n\n\nvoid VVerlet(int N, double *y, double **ans, double *t,\t\t\t\t\t\t\t// Velocity Verlet for Start y, return ans[LengthT][ORDER] to times T\n\t\t\t\tvoid (*derivmethod) (double *y, double *ans, double t, int N)){\n\tint i,j;\n\tfor(i=0; i< N; i++){\n\tans[0][i] = y[i]; \t\t\t\t// give initial vec to answer\n\t}\n\tdouble x[N/2], v[N/2], a[N/2], z[N];\n\tvec_zero(x,N/2);\n\tvec_zero(v,N/2);\n\tvec_zero(a,N/2);\n\tvec_zero(z,N);\n\tint current_index = 0;\n\tdouble current_t = t[current_index];\n\tderivmethod(y, z, current_t, N); \t\t\t\t// get first derivative\t\t\t\t\t\t\t\n\tfor (j = 0; j < DIM; j++ )\t\t\t\t\t\t// bring y-p Form to x-v-a\n\t{\n\t\tx[j] = y[j];\n\t\tv[j] = y[DIM + j]/mass;\n\t\ta[j] = z[DIM + j]/mass;\n\t\t#pragma omp parallel for\n\t\tfor (i= 0 ; i < OSSZI; i++)\n\t\t{\n\t\t\t\t\tx[DIM + j + i*DIM] = y[2*DIM + j + i * 2*DIM];\n\t\t\t\t\tv[DIM + j + i*DIM] = y[3*DIM + j + i * 2*DIM]/massq[i];\n\t\t\t\t\ta[DIM + j + i*DIM] = z[3*DIM + j + i * 2*DIM]/massq[i];\n\t\t}\n\t}\n\n\twhile(current_index < LENGTH_T-1)\n\t{\n\t\twhile(fabs(current_t - t[current_index + 1])> MAXSTEPSIZE)\n\t\t{ \t//integrate till space till next time smaller than stepsize\n\t\t\tStepper_Method(N, x, v, a, ¤t_t, derivmethod);\n\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t// get to y-Form\n\t\tcurrent_index = current_index +1;\n\t\tfor (j = 0; j < DIM; j++ )\n\t\t{\n\t\t\tans[current_index][DIM + j] = mass * v[j];\n\t\t\tans[current_index][j] \t = x[j];\n\t\t\t#pragma omp parallel for \n\t\t\tfor (i= 0 ; i < OSSZI; i++)\n\t\t\t{\n\t\t\t\t\t\tans[current_index][2*DIM + j + i * 2*DIM] = x[DIM +j+ i*DIM];\n\t\t\t\t\t\tans[current_index][3*DIM + j + i * 2*DIM] = v[DIM +j+ i*DIM] * massq[i]; // übergib SChritt an antwort\n\t\t\t}\n\t\t}\t\t\n\t}\n\n} \n\nvoid VVerlet_parallel(const int N, const double *y, double **ans, double *t,\t\t\t\t\t\t\t// Velocity Verlet for Start y, return ans[LengthT][ORDER] to times T\n\t\t\t\tvoid (*derivmethod) (double *y, double *ans, double t, int N)){\n\tint i,j;\n\tfor(i=0; i< N; i++){\n\tans[0][i] = y[i]; \t\t\t\t// give initial vec to answer\n\t}\n\tTARGET_FLAG = 1;\n\tdouble x[N/2], v[N/2], a[N/2], z[N];\n\tvec_zero(x,N/2);\n\tvec_zero(v,N/2);\n\tvec_zero(a,N/2);\n\tvec_zero(z,N);\n\tint current_index = 0;\n\tdouble current_t = t[current_index];\n\tderivmethod(y, z, current_t, N); \t\t\t\t\t\t// giv f'\n\tint steps_in_intervall = 0;\t\t\t\t\t\t// counts steps done in intervall t, t+ dt\n\tint max_steps_in_intervall = 100000;\t\t\t// after X steps, assume error occured\n\tfor (j = 0; j < DIM; j++ )\t\t\t\t\t\t// y-p --> x-v-a form\n\t{\n\t\tx[j] = y[j];\n\t\tVIRTUAL_X[j] = x[j];\n\t\tv[j] = y[DIM + j]/mass;\n\t\tVIRTUAL_V[j] = v[j];\n\t\ta[j] = z[DIM + j]/mass;\n\t}\n\n\t#pragma omp parallel for \n\tfor (i= 0 ; i < OSSZI; i++)\n\t{\n\t\tfor (j = 0; j < DIM; j++ )\n\t\t{\n\t\t\tx[DIM + j + i*DIM] = y[2*DIM + j + i * 2*DIM];\n\t\t\tv[DIM + j + i*DIM] = y[3*DIM + j + i * 2*DIM]/massq[i];\n\t\t\ta[DIM + j + i*DIM] = z[3*DIM + j + i * 2*DIM]/massq[i];\n\t\t}\n\t}\n\tLASTSTEPSIZE = MAXSTEPSIZE;\n\twhile(current_index < LENGTH_T-1)\n\t{\n\t\twhile(fabs(current_t - t[current_index + 1])> MAXSTEPSIZE)\t\t\t//integrate till space till next time smaller than stepsize\n\t\t{ \t\n\t\t\tStepper_Method(N, x, v, a, ¤t_t, derivmethod);\n\t\t\tsteps_in_intervall++;\n\t\t\tif(steps_in_intervall > max_steps_in_intervall)\n\t\t\t{\n\t\t\t\tFLAG_DUMP_VALUE = 1;\t\t\t\t\t\t\t\t\t\t// too many steps, error occured\n\t\t\t\tprintf(\"too many steps taken to advance one time point \\n\");\n\t\t\t}\n\t\t\tif (FLAG_DUMP_VALUE) \t\t\t\t\t\t\t\t\t\t\t// if error occured somewhere leave calculation\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tsteps_in_intervall = 0; \t\t\t\t// reset stepcount\t\t\t\t\t\t\t\t\n\t\tcurrent_index = current_index +1;\t\t// get back to y-form\n\t\tfor (j = 0; j < DIM; j++ )\n\t\t{\n\t\t\tif(VIRTUAL_FLAG)\n\t\t\t{\n\t\t\t\tans[current_index][DIM + j] = mass * VIRTUAL_V[j];\n\t\t\t\tans[current_index][j] \t = VIRTUAL_X[j];\n\t\t\t}else\n\t\t\t{\n\t\t\t\tans[current_index][DIM + j] = mass * v[j];\n\t\t\t\tans[current_index][j] \t = x[j];\n\t\t\t}\n\t\t}\n\t\t#pragma omp parallel for \n\t\tfor (i= 0 ; i < OSSZI; i++)\n\t\t{\n\t\t\tfor (j = 0; j < DIM; j++ )\n\t\t\t{\n\t\t\t\tans[current_index][2*DIM + j + i * 2*DIM] = x[DIM +j+ i*DIM];\n\t\t\t\tans[current_index][3*DIM + j + i * 2*DIM] = v[DIM +j+ i*DIM] * massq[i] ; // give step to answer\n\t\t\t}\n\t\t}\t\t\n\t}\n\tif (TARGET_FLAG)\t\t// if no contact, give simulation length as contact time\n\t{\n\t\ttime_first_contact += TIME_END;\n\t\tTARGET_FLAG = 0;\n\t}\n} \n\nvoid VVerlet_parallel_burn(const int N, const double *y, double **ans, double *t,\t\t\t\t\t\t\t// Velocity Verlet für Start y, Ausgabe ans[LengthT][ORDER] zu Zeiten T\n\t\t\t\tvoid (*derivmethod) (double *y, double *ans, double t, int N))\n// always involes free particle for burning samples\n{\n\tint i,j;\n\tfor(i=0; i< N; i++){\n\tans[0][i] = y[i]; \t\t\t\t// übergib startvektor an antwort\n\t}\n\tTARGET_FLAG = 1;\n\tdouble x[N/2], v[N/2], a[N/2], z[N];\n\tvec_zero(x,N/2);\n\tvec_zero(v,N/2);\n\tvec_zero(a,N/2);\n\tvec_zero(z,N);\n\tint current_index = 0;\n\tdouble current_t = t[current_index];\n\tderivmethod(y, z, current_t, N); \t\t\t\t// übergib erste Ableitung\n\t// bringe aus y-p y Form auf x-v-a\n\tfor (j = 0; j < DIM; j++ )\n\t{\n\t\tx[j] = y[j];\n\t\tv[j] = y[DIM + j]/mass;\n\t\ta[j] = z[DIM + j]/mass;\n\t}\n\t#pragma omp parallel for \n\tfor (i= 0 ; i < OSSZI; i++)\n\t{\n\t\tfor (j = 0; j < DIM; j++ )\n\t\t{\n\t\t\tx[DIM + j + i*DIM] = y[2*DIM + j + i * 2*DIM];\n\t\t\tv[DIM + j + i*DIM] = y[3*DIM + j + i * 2*DIM]/massq[i];\n\t\t\ta[DIM + j + i*DIM] = z[3*DIM + j + i * 2*DIM]/massq[i];\n\t\t}\n\t}\n\t\n\n\twhile(current_index < LENGTH_T-1)\n\t{\n\t\twhile(fabs(current_t - t[current_index + 1])> MAXSTEPSIZE)\n\t\t{ \t//integriere bis abstand zu nächstem t kleiner schrittweite\n\t\t\tVVerlet_Step_deriv(N, x, v, a, ¤t_t, derivmethod);\n\t\t\t//printf (\"%fx %ft \\n\", x[1], current_t);\n\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t// rechne wieder auf y-Form\n\t\tcurrent_index = current_index +1;\n\t\tfor (j = 0; j < DIM; j++ )\n\t\t{\n\t\t\tans[current_index][DIM + j] = mass * v[j];\n\t\t\tans[current_index][j] \t = x[j];\n\t\t}\n\t\t#pragma omp parallel for \n\t\tfor (i= 0 ; i < OSSZI; i++)\n\t\t{\n\t\t\tfor (j = 0; j < DIM; j++ )\n\t\t\t{\n\t\t\t\tans[current_index][2*DIM + j + i * 2*DIM] = x[DIM +j+ i*DIM];\n\t\t\t\tans[current_index][3*DIM + j + i * 2*DIM] = v[DIM +j+ i*DIM] * massq[i]; // übergib SChritt an antwort\n\t\t\t}\n\t\t}\t\t\n\t}\n\tif (TARGET_FLAG)\t\t// FAlls kein erstkontakt addiere gesamtzeit\n\t{\n\t\ttime_first_contact += TIME_END;\n\t\tTARGET_FLAG = 0;\n\t}\n} \n\n\n\n\n\nvoid Bath_Setup(double *y, char *inputlabel, gsl_rng * r){\n\tint a,b,i;\n\tdouble u,P[OSSZI], sum=0.0;\n\n\tif (strcmp(inputlabel,\"ZWANZIG\")==0)\n\t{\n\t\tfor (b = 0; b < DIM; b++)\n\t\t{\n\t\t\ty[b] = 0.0;\t\t\t\t\t//massives particle seperatly\n\t\t\ty[DIM+b] = 0.0;\n\t\t\tfor (a = 0; a < OSSZI; a++)\n\t\t\t{\n\t\t\t\tu = gsl_ran_gaussian(r, 1.0);\n\t\t\t\ty[2*DIM + a * 2*DIM + b] = sqrt(KBOLTZ * TEMP / massq[a]) / ommega[a] * u; \t//q = (k*T/m)^0.5/ommega * N(0,1)\n\t\t\t\tu = gsl_ran_gaussian(r, 1.0);\n\t\t\t\ty[3*DIM + a * 2*DIM + b] = sqrt(KBOLTZ * TEMP * massq[a]) * u;\t\t\t//p_q = (k*T*m)^0.5 * N(0,1)\n\t\t\t}\n\t\t}\n\t\treturn;\t\n\t}\n\tif (strcmp(inputlabel,\"ZWANZIG_THERMALIZED\")==0)\n\t{\n\t\tfor (b = 0; b < DIM; b++)\n\t\t{\n\t\t\ty[b] = 0.0;\t\t\t\t\t//massives particle seperatly\n\t\t\tu = gsl_ran_gaussian(r, 1.0);\n\t\t\ty[DIM+b] = sqrt(KBOLTZ * TEMP * mass) * u;\t\t\t//p_q = (k*T*m)^0.5 * N(0,1)\n\t\t\tfor (a = 0; a < OSSZI; a++)\n\t\t\t{\n\t\t\t\tu = gsl_ran_gaussian(r, 1.0);\n\t\t\t\ty[2*DIM + a * 2*DIM + b] = sqrt(KBOLTZ * TEMP / massq[a]) / ommega[a] * u; \t//q = (k*T/m)^0.5/ommega * N(0,1)\n\t\t\t\tu = gsl_ran_gaussian(r, 1.0);\n\t\t\t\ty[3*DIM + a * 2*DIM + b] = sqrt(KBOLTZ * TEMP * massq[a]) * u;\t\t\t//p_q = (k*T*m)^0.5 * N(0,1)\n\t\t\t}\n\t\t}\n\t\treturn;\t\n\t}\n\tprintf(\"FALSCHES BADLABEL\");\n\texit(1);\n}\n\nvoid Ommega_Setup(gsl_rng * r)\n{\n\n \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// draw uniformly nonrandom\n\tdouble nr_osszillators = 1.0 * OSSZI; \t\t\t\t\t// cast Osszi to double\n\tdouble higher_cutoff = 1.0/(0.5 * TIME_STEPS); \t\t\t//cleanly resolve smallest steps\n\tdouble lower_cutoff = 1.0/(1.6 * TIME_END); \t\t\t//cleanly resolve till end time\n\n\n\thigher_cutoff = 5.0* pow( (GAMMA/mass), 1.0/(2.0-ALPHA));\n\tlower_cutoff = 5E-5; \n\tdouble ommega_step = (higher_cutoff - lower_cutoff)/(nr_osszillators);\t\t\t\n\tfor (int i = 0; i < OSSZI; i++)\n\t{\n\t\tommega[i] = lower_cutoff + i * ommega_step;\n\t}\n\tprintf(\"\\nnonrandom bath \");\n\tprintf (\"Ommega_Max = %1.3e \", ommega[OSSZI-1] );\n\tprintf (\"Ommega_Min = %1.3e\\n\", ommega[0] );\n}\n\nvoid Gamma_Setup(double *gamma){ \t\t\t\t\t\t//Set coupling for Exponent Alpha so that MSD s^2 prop to\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t//t^ALPHA, ALPHA = 1 (classical diff) seperately\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// put constants in gamma\n\tint i;\n\tdouble TOL = 1e-3;\n\tdouble nr_osz = (double) OSSZI;\n\tdouble delta_ommega = ommega[1]-ommega[0];\n\tif (! (KUPF_BINARY))\n\t{\n\t\tif (fabs(ALPHA-1.0)TOL){\n\t\t\tfor(i = 0; i < OSSZI; i++)\n\t\t\t{\n\t\t\t\tgamma[i] = sqrt(GAMMA) * pow(ommega[i], 0.5 + ALPHA * 0.5)\\\n\t\t\t\t* sqrt( 2/sqrt(M_PI * 2) * sin(M_PI * ALPHA/2.0) * gsl_sf_gamma(1 - ALPHA)) * sqrt(delta_ommega);\n\t\t\t}\n\t\t}\n\t\tif (OUTPUT_FLAG)\n\t\t{\n\t\t\tprintf(\"Konstanten aufgesetzt für Alpha = %f \\n \" , ALPHA);\n\t\t}\n\t}else\n\t{\n\t\tif (fabs(ALPHA-1.0)] [CEED_DIR=]\n//\n// Sample runs:\n// Sequential:\n//\n// ./area -problem cube -degree 3 -dm_refine 2\n// ./area -problem sphere -degree 3 -dm_refine 2\n//\n// In parallel:\n//\n// mpiexec -n 4 ./area -problem cube -degree 3 -dm_refine 2\n// mpiexec -n 4 ./area -problem sphere -degree 3 -dm_refine 2\n//\n// The above example runs use 2 levels of refinement for the mesh.\n// Use -dm_refine k, for k levels of uniform refinement.\n//\n//TESTARGS -ceed {ceed_resource} -test -degree 3 -dm_refine 1\n\n/// @file\n/// libCEED example using the mass operator to compute a cube or a cubed-sphere surface area using PETSc with DMPlex\nstatic const char help[] =\n \"Compute surface area of a cube or a cubed-sphere using DMPlex in PETSc\\n\";\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"area.h\"\n#include \"include/areaproblemdata.h\"\n#include \"include/petscutils.h\"\n#include \"include/petscversion.h\"\n#include \"include/matops.h\"\n#include \"include/structs.h\"\n#include \"include/libceedsetup.h\"\n\n#if PETSC_VERSION_LT(3,12,0)\n#ifdef PETSC_HAVE_CUDA\n#include \n// Note: With PETSc prior to version 3.12.0, providing the source path to\n// include 'cublas_v2.h' will be needed to use 'petsccuda.h'.\n#endif\n#endif\n\n#ifndef M_PI\n# define M_PI 3.14159265358979323846\n#endif\n\nint main(int argc, char **argv) {\n PetscInt ierr;\n MPI_Comm comm;\n char filename[PETSC_MAX_PATH_LEN],\n ceed_resource[PETSC_MAX_PATH_LEN] = \"/cpu/self\";\n PetscInt l_size, g_size, xl_size,\n q_extra = 1, // default number of extra quadrature points\n num_comp_x = 3, // number of components of 3D physical coordinates\n num_comp_u = 1, // dimension of field to which apply mass operator\n topo_dim = 2, // topological dimension of manifold\n degree = 3; // default degree for finite element bases\n PetscBool read_mesh = PETSC_FALSE,\n test_mode = PETSC_FALSE,\n simplex = PETSC_FALSE;\n Vec U, U_loc, V, V_loc;\n DM dm;\n UserO user;\n Ceed ceed;\n CeedData ceed_data;\n ProblemType problem_choice;\n VecType vec_type;\n PetscMemType mem_type;\n\n ierr = PetscInitialize(&argc, &argv, NULL, help);\n if (ierr) return ierr;\n comm = PETSC_COMM_WORLD;\n\n // Read command line options\n ierr = PetscOptionsBegin(comm, NULL, \"CEED surface area problem with PETSc\",\n NULL);\n CHKERRQ(ierr);\n problem_choice = SPHERE;\n ierr = PetscOptionsEnum(\"-problem\",\n \"Problem to solve\", NULL,\n problem_types, (PetscEnum)problem_choice,\n (PetscEnum *)&problem_choice,\n NULL); CHKERRQ(ierr);\n ierr = PetscOptionsInt(\"-q_extra\", \"Number of extra quadrature points\",\n NULL, q_extra, &q_extra, NULL); CHKERRQ(ierr);\n ierr = PetscOptionsString(\"-ceed\", \"CEED resource specifier\",\n NULL, ceed_resource, ceed_resource,\n sizeof(ceed_resource), NULL); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-test\",\n \"Testing mode (do not print unless error is large)\",\n NULL, test_mode, &test_mode, NULL); CHKERRQ(ierr);\n ierr = PetscOptionsString(\"-mesh\", \"Read mesh from file\", NULL,\n filename, filename, sizeof(filename), &read_mesh);\n CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-simplex\", \"Use simplices, or tensor product cells\",\n NULL, simplex, &simplex, NULL); CHKERRQ(ierr);\n ierr = PetscOptionsInt(\"-degree\", \"Polynomial degree of tensor product basis\",\n NULL, degree, °ree, NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n // Setup DM\n if (read_mesh) {\n ierr = DMPlexCreateFromFile(PETSC_COMM_WORLD, filename, NULL, PETSC_TRUE,\n &dm);\n CHKERRQ(ierr);\n } else {\n // Create the mesh as a 0-refined sphere. This will create a cubic surface, not a box\n ierr = DMPlexCreateSphereMesh(PETSC_COMM_WORLD, topo_dim, simplex, 1., &dm);\n CHKERRQ(ierr);\n // Set the object name\n ierr = PetscObjectSetName((PetscObject)dm, problem_types[problem_choice]);\n CHKERRQ(ierr);\n // Distribute mesh over processes\n {\n DM dm_dist = NULL;\n PetscPartitioner part;\n\n ierr = DMPlexGetPartitioner(dm, &part); CHKERRQ(ierr);\n ierr = PetscPartitionerSetFromOptions(part); CHKERRQ(ierr);\n ierr = DMPlexDistribute(dm, 0, NULL, &dm_dist); CHKERRQ(ierr);\n if (dm_dist) {\n ierr = DMDestroy(&dm); CHKERRQ(ierr);\n dm = dm_dist;\n }\n }\n // Refine DMPlex with uniform refinement using runtime option -dm_refine\n ierr = DMPlexSetRefinementUniform(dm, PETSC_TRUE); CHKERRQ(ierr);\n ierr = DMSetFromOptions(dm); CHKERRQ(ierr);\n if (problem_choice == SPHERE) {\n ierr = ProjectToUnitSphere(dm); CHKERRQ(ierr);\n }\n // View DMPlex via runtime option\n ierr = DMViewFromOptions(dm, NULL, \"-dm_view\"); CHKERRQ(ierr);\n }\n\n // Create DM\n ierr = SetupDMByDegree(dm, degree, num_comp_u, topo_dim, false,\n (BCFunction)NULL);\n CHKERRQ(ierr);\n\n // Create vectors\n ierr = DMCreateGlobalVector(dm, &U); CHKERRQ(ierr);\n ierr = VecGetLocalSize(U, &l_size); CHKERRQ(ierr);\n ierr = VecGetSize(U, &g_size); CHKERRQ(ierr);\n ierr = DMCreateLocalVector(dm, &U_loc); CHKERRQ(ierr);\n ierr = VecGetSize(U_loc, &xl_size); CHKERRQ(ierr);\n ierr = VecDuplicate(U, &V); CHKERRQ(ierr);\n ierr = VecDuplicate(U_loc, &V_loc); CHKERRQ(ierr);\n\n // Setup user structure\n ierr = PetscMalloc1(1, &user); CHKERRQ(ierr);\n\n // Set up libCEED\n CeedInit(ceed_resource, &ceed);\n CeedMemType mem_type_backend;\n CeedGetPreferredMemType(ceed, &mem_type_backend);\n\n ierr = DMGetVecType(dm, &vec_type); CHKERRQ(ierr);\n if (!vec_type) { // Not yet set by user -dm_vec_type\n switch (mem_type_backend) {\n case CEED_MEM_HOST: vec_type = VECSTANDARD; break;\n case CEED_MEM_DEVICE: {\n const char *resolved;\n CeedGetResource(ceed, &resolved);\n if (strstr(resolved, \"/gpu/cuda\")) vec_type = VECCUDA;\n else if (strstr(resolved, \"/gpu/hip/occa\"))\n vec_type = VECSTANDARD; // https://github.com/CEED/libCEED/issues/678\n else if (strstr(resolved, \"/gpu/hip\")) vec_type = VECHIP;\n else vec_type = VECSTANDARD;\n }\n }\n ierr = DMSetVecType(dm, vec_type); CHKERRQ(ierr);\n }\n\n // Print summary\n if (!test_mode) {\n PetscInt P = degree + 1, Q = P + q_extra;\n const char *used_resource;\n CeedGetResource(ceed, &used_resource);\n ierr = PetscPrintf(comm,\n \"\\n-- libCEED + PETSc Surface Area of a Manifold --\\n\"\n \" libCEED:\\n\"\n \" libCEED Backend : %s\\n\"\n \" libCEED Backend MemType : %s\\n\"\n \" Mesh:\\n\"\n \" Number of 1D Basis Nodes (p) : %d\\n\"\n \" Number of 1D Quadrature Points (q) : %d\\n\"\n \" Global nodes : %D\\n\"\n \" DoF per node : %D\\n\"\n \" Global DoFs : %D\\n\",\n used_resource, CeedMemTypes[mem_type_backend], P, Q,\n g_size/num_comp_u, num_comp_u, g_size); CHKERRQ(ierr);\n }\n\n // Setup libCEED's objects and apply setup operator\n ierr = PetscMalloc1(1, &ceed_data); CHKERRQ(ierr);\n ierr = SetupLibceedByDegree(dm, ceed, degree, topo_dim, q_extra, num_comp_x,\n num_comp_u, g_size, xl_size,\n problem_options[problem_choice], ceed_data,\n false, (CeedVector)NULL, (CeedVector *)NULL);\n CHKERRQ(ierr);\n\n // Setup output vector\n PetscScalar *v;\n ierr = VecZeroEntries(V_loc); CHKERRQ(ierr);\n ierr = VecGetArrayAndMemType(V_loc, &v, &mem_type); CHKERRQ(ierr);\n CeedVectorSetArray(ceed_data->y_ceed, MemTypeP2C(mem_type), CEED_USE_POINTER,\n v);\n\n // Compute the mesh volume using the mass operator: area = 1^T \\cdot M \\cdot 1\n if (!test_mode) {\n ierr = PetscPrintf(comm,\n \"Computing the mesh area using the formula: area = 1^T M 1\\n\");\n CHKERRQ(ierr);\n }\n\n // Initialize u with ones\n CeedVectorSetValue(ceed_data->x_ceed, 1.0);\n\n // Apply the mass operator: 'u' -> 'v'\n CeedOperatorApply(ceed_data->op_apply, ceed_data->x_ceed, ceed_data->y_ceed,\n CEED_REQUEST_IMMEDIATE);\n\n // Gather output vector\n CeedVectorTakeArray(ceed_data->y_ceed, CEED_MEM_HOST, NULL);\n ierr = VecRestoreArrayAndMemType(V_loc, &v); CHKERRQ(ierr);\n ierr = VecZeroEntries(V); CHKERRQ(ierr);\n ierr = DMLocalToGlobalBegin(dm, V_loc, ADD_VALUES, V); CHKERRQ(ierr);\n ierr = DMLocalToGlobalEnd(dm, V_loc, ADD_VALUES, V); CHKERRQ(ierr);\n\n // Compute and print the sum of the entries of 'v' giving the mesh surface area\n PetscScalar area;\n ierr = VecSum(V, &area); CHKERRQ(ierr);\n\n // Compute the exact surface area and print the result\n CeedScalar exact_surface_area = 4 * M_PI;\n if (problem_choice == CUBE) {\n PetscScalar l = 1.0/PetscSqrtReal(3.0); // half edge of the cube\n exact_surface_area = 6 * (2*l) * (2*l);\n }\n\n PetscReal error = fabs(area - exact_surface_area);\n PetscReal tol = 5e-6;\n if (!test_mode || error > tol) {\n ierr = PetscPrintf(comm, \"Exact mesh surface area : % .14g\\n\",\n exact_surface_area);\n CHKERRQ(ierr);\n ierr = PetscPrintf(comm, \"Computed mesh surface area : % .14g\\n\", area);\n CHKERRQ(ierr);\n ierr = PetscPrintf(comm, \"Area error : % .14g\\n\", error);\n CHKERRQ(ierr);\n }\n\n // Cleanup\n ierr = DMDestroy(&dm); CHKERRQ(ierr);\n ierr = VecDestroy(&U); CHKERRQ(ierr);\n ierr = VecDestroy(&U_loc); CHKERRQ(ierr);\n ierr = VecDestroy(&V); CHKERRQ(ierr);\n ierr = VecDestroy(&V_loc); CHKERRQ(ierr);\n ierr = PetscFree(user); CHKERRQ(ierr);\n ierr = CeedDataDestroy(0, ceed_data); CHKERRQ(ierr);\n CeedDestroy(&ceed);\n return PetscFinalize();\n}\n", "meta": {"hexsha": "bb8f925bfc4fbaf8799ffafa8f0ca27d9525c77d", "size": 11577, "ext": "c", "lang": "C", "max_stars_repo_path": "examples/petsc/area.c", "max_stars_repo_name": "wence-/libCEED", "max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "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": "examples/petsc/area.c", "max_issues_repo_name": "wence-/libCEED", "max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "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": "examples/petsc/area.c", "max_forks_repo_name": "wence-/libCEED", "max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "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": 39.3775510204, "max_line_length": 116, "alphanum_fraction": 0.6368662002, "num_tokens": 3030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.5864804707303932}} {"text": "//popGen stuff for Next Gen Sequencing Data\n\n#include \"pgSummaryStats.h\"\n#include \n#include \n#include \n#include \n#include \"vector.h\"\n#include \n#include \n#include \n#include \n\n//Sampling Probability stuff\n\n\n//prob_i returns the probability under SNM of a snp freq i\ndouble prob_i(int i, int n){\n\tdouble tmp;\n\ttmp = 1.0 / (double) i;\n\treturn(tmp/ a1f(n));\n}\n\n\ndouble prob_km(int k, int m, int n){\n\tdouble sum = 0.0;\n\tint i;\n\tdouble tmpFreq;\n\t\n\tfor(i=1;isize1; i++){\n\t\tweightSum = 0.0;\n\t\ttmpTheta = 0.0;\n\t\tfor(j = 1; j < i; j++){\n\t\t\t//size i freq j\n\t\t\ttmpTheta += gsl_matrix_get(sfsCount, i, j) * j * gsl_matrix_get(weightMat,i,j);\n\t\t\tweightSum += gsl_matrix_get(weightMat,i,j);\n\t\t}\n\t\tif(weightSum > 0){ theta += tmpTheta / weightSum; }\n\t}\n\treturn(theta);\n}\n\ndouble achazSFSCorrected(gsl_matrix *sfsCount, gsl_matrix *weightMat,int nPool){\n\tint i, j;\n\tdouble theta = 0.0;\n\tdouble weightSum, tmpTheta;\n\t\n\t//rows = sampleSizes\n\tfor(i = 2; i < sfsCount->size1; i++){\n\t\tweightSum = 0.0;\n\t\ttmpTheta = 0.0;\n\t\tfor(j = 1; j < i; j++){\n\t\t\t//size i freq j\n\t\t\ttmpTheta += gsl_matrix_get(sfsCount, i, j) * gsl_matrix_get(weightMat,i,j) * (1.0/prob_km(j,i,nPool));\n\t\t\tweightSum += gsl_matrix_get(weightMat,i,j);\n\t\t}\n\t\tif(weightSum > 0){ \n\t\t\n\t\t\ttheta += tmpTheta / weightSum / a1f(nPool); \n\t\t}\n\t}\n\treturn(theta);\n}\n\n\n// fillPiWeights -- returns the weight matrix for theta_pi\nvoid fillPiWeights(gsl_matrix *weightMat, int minFreq){\n\tint i, j;\n\tgsl_matrix_set_zero(weightMat);\n\tfor(i=minFreq+1; i < weightMat->size1; i++){\n\t\tfor(j=minFreq;jsize1; i++){\n\t\tfor(j=minFreq;jsize1; i++){\n\t\tfor(j=minFreq;j\n#include \n#include \n#include \n#include \n\n#ifdef __APPLE__\n\n#include \n\n#define set_num_threads(x) openblas_set_num_threads(x)\n#define get_num_threads() openblas_get_num_threads()\n#else\n#include \n#define set_num_threads(x) mkl_set_num_threads(x)\n#define get_num_threads() mkl_get_num_threads()\n#endif\n\n\ndouble norm_inf_mat_Y11(double *X, int n, int extra);\n\nint main(int argc, char **argv) {\n\n int n, i, j;\n char *filename = NULL;\n double tolerance = 1e-8;\n int option = 0;\n int threads_num = 1;\n while ((option = getopt(argc, argv, \"t:f:\")) != -1) {\n switch (option) {\n case 'f':\n filename = optarg;\n break;\n case 't':\n threads_num = atoi(optarg);\n break;\n default:\n printf(\"Usage: mexp -f string \\n\");\n return 0;\n }\n }\n if (filename == NULL) {\n printf(\"Usage: mexp -t num_threads -f string \\n\");\n return 0;\n }\n\n double *A = NULL, *R = NULL, *B = NULL, *W = NULL;\n double *x, *r, *p, *w;\n FILE *file = fopen(filename, \"rb\");\n if (!file) {\n printf(\"Unable to open file!\");\n return 0;\n }\n\n fread(&n, sizeof(int), 1, file);\n A = (double *) malloc((n + 1) * (n + 1) * sizeof(double));\n R = (double *) malloc((n + 1) * (n + 1) * sizeof(double));\n B = (double *) malloc((n + 1) * sizeof(double));\n W = (double *) malloc(n * sizeof(double));\n x = (double *) malloc(n * sizeof(double));\n r = (double *) malloc(n * sizeof(double));\n p = (double *) malloc(n * sizeof(double));\n w = (double *) malloc(n * sizeof(double));\n\n printf(\"set_threads_num:%d\\t\", threads_num++);\n\n fseek(file, 0, SEEK_SET);\n fread(&n, sizeof(int), 1, file);\n\n //fseek(file, sizeof(int), SEEK_SET);\n memset(A, 0, sizeof(double) * (n + 1) * (n + 1));\n memset(R, 0, sizeof(double) * (n + 1) * (n + 1));\n for (i = 0; i < n; ++i) {\n fread(A + i * (n + 1), sizeof(double), (size_t) n, file);\n }\n memset(B, 0, sizeof(double) * (n + 1));\n fread(B, sizeof(double), (size_t) n, file);\n\n set_num_threads(threads_num);\n omp_set_num_threads(threads_num);\n\n cblas_dcopy(n, B, 1, A + n, n + 1);\n\n double omp_time = omp_get_wtime();\n double lambda = norm_inf_mat_Y11(A, n, 1);\n\n //init Y matrix\n for (i = 0; i < n; ++i) {\n double *A_T = A + i * (n + 1);\n#pragma omp parallel for\n for (j = 0; j < n; ++j) {\n A_T[j] = -A_T[j] / lambda;\n }\n }\n#pragma omp parallel for\n for (i = 0; i < (n + 1) * (n + 1); i += n + 2) {\n A[i] += 1;\n }\n#pragma omp parallel for\n for (i = n; i < (n + 1) * n; i += n + 1) {\n A[i] /= lambda;\n }\n#pragma omp parallel for\n for (i = 0; i < n; ++i) {\n double *A_T = A + n * (n + 1);\n A_T[i] = 0.0;\n }\n A[(n + 1) * (n + 1)] = 1.0;\n\n\n //loop\n double a, b, *T;\n size_t index;\n int itern = 0;\n while (1) {\n a = norm_inf_mat_Y11(A, n, 1);\n index = cblas_idamax(n, A + n, n + 1);\n b = A[(index + 1) * (n + 1) - 1];\n if (a / b < tolerance)\n break;\n else {\n //R = A*A\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n + 1, n + 1,\n n + 1, 1.0, A, n + 1, A, n + 1, 0.0, R, n + 1);\n T = A;\n A = R;\n R = T;\n itern++;\n }\n }\n\n omp_time = omp_get_wtime() - omp_time;\n\n cblas_dcopy(n, A + n, n + 1, B, 1);\n\n /*\n * check result\n */\n for (i = 0; i < n; ++i) {\n if (fabs(B[i] - 1) > 1e-3) {\n printf(\"MEXP ERR %f\\t\", B[i]);\n break;\n }\n }\n printf(\"mexp_iter:%d\\t\", itern);\n printf(\"omp_time:%f\\t\", omp_time);\n\n\n fseek(file, 0, SEEK_SET);\n fread(&n, sizeof(int), 1, file);\n\n fread(A, sizeof(double), (size_t) (n * n), file);\n memset(B, 0, sizeof(double) * (n + 1));\n fread(B, sizeof(double), (size_t) n, file);\n#pragma omp parallel for\n for (i = 0; i < n; ++i) {\n W[i] = 1.0;\n //B[i] /= A[i*(n+1)];\n //cblas_dscal(n,1/A[i*(n+1)],A+i*n,1);\n }\n\n omp_time = omp_get_wtime();\n int iteration = 0;\n\n double alpha, beta, rho_new = 0.0, rho_old;\n memset(x, 0, sizeof(double) * n);\n cblas_dcopy(n, B, 1, r, 1); //r <- B\n\n rho_new = cblas_ddot(n, r, 1, r, 1);\n double w_norm2 = sqrt(rho_new);\n while (1) {\n if (sqrt(rho_new) / w_norm2 < tolerance) {\n break;\n }\n iteration++;\n if (iteration == 1) {\n cblas_dcopy(n, r, 1, p, 1); //p <- r\n } else {\n beta = rho_new / rho_old;\n cblas_dscal(n, beta, p, 1); // p <- beta * p\n cblas_daxpy(n, 1.0, r, 1, p, 1); // p <- r + pcd\n }\n cblas_dsymv(CblasRowMajor, CblasUpper, n, 1.0, A, n, p, 1, 0.0, w, 1);\n alpha = rho_new / cblas_ddot(n, p, 1, w, 1);\n cblas_daxpy(n, alpha, p, 1, x, 1);\n cblas_daxpy(n, -alpha, w, 1, r, 1); // r = r - alpha* w\n rho_old = rho_new;\n rho_new = cblas_ddot(n, r, 1, r, 1); //rho_new = r' dot r;\n }\n\n printf(\"cg_it: %d\\t\", iteration);\n printf(\"cg_omp_time: %f\", omp_get_wtime() - omp_time);\n\n /*\n * check result\n */\n for (i = 0; i < n; ++i) {\n if (fabs(x[i] - 1) > 1e-3) {\n printf(\" CG ERR %f\\t\", x[i]);\n break;\n }\n }\n printf(\"\\n\");\n\n free(A);\n free(B);\n free(W);\n free(R);\n free(x);\n free(r);\n free(p);\n free(w);\n fclose(file);\n}\n\ndouble norm_inf_mat_Y11(double *X, int n, int extra) {\n double lambda = 0.0, lambda_t;\n int i;\n for (i = 0; i < n; ++i) {\n lambda_t = cblas_dasum(n, X + (i * (n + extra)), 1);\n if (lambda_t > lambda)\n lambda = lambda_t;\n }\n return lambda;\n}\n", "meta": {"hexsha": "e71626977a87940e5f54b2684de94b590b295f91", "size": 5888, "ext": "c", "lang": "C", "max_stars_repo_path": "openmp/openmp_all.c", "max_stars_repo_name": "baishuai/MEXP", "max_stars_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openmp/openmp_all.c", "max_issues_repo_name": "baishuai/MEXP", "max_issues_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openmp/openmp_all.c", "max_forks_repo_name": "baishuai/MEXP", "max_forks_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0530973451, "max_line_length": 80, "alphanum_fraction": 0.476392663, "num_tokens": 2018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.585875572954995}} {"text": "/* linalg/qrpt.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#define REAL double\n\n#include \"givens.c\"\n#include \"apply_givens.c\"\n\n/* Factorise a general M x N matrix A into\n *\n * A P = Q R\n *\n * where Q is orthogonal (M x M) and R is upper triangular (M x N).\n * When A is rank deficient, r = rank(A) < n, then the permutation is\n * used to ensure that the lower n - r rows of R are zero and the first\n * r columns of Q form an orthonormal basis for A.\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 * P: column j of P is column k of the identity matrix, where k =\n * permutation->data[j]\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. See LAPACK's\n * dgeqpf.f for details.\n * \n */\n\nint\ngsl_linalg_QRPT_decomp (gsl_matrix * A, gsl_vector * tau, gsl_permutation * p, int *signum, gsl_vector * norm)\n{\n const size_t M = A->size1;\n const size_t N = A->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 (p->size != N)\n {\n GSL_ERROR (\"permutation size must be N\", GSL_EBADLEN);\n }\n else if (norm->size != N)\n {\n GSL_ERROR (\"norm size must be N\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n *signum = 1;\n\n gsl_permutation_init (p); /* set to identity */\n\n /* Compute column norms and store in workspace */\n\n for (i = 0; i < N; i++)\n {\n gsl_vector_view c = gsl_matrix_column (A, i);\n double x = gsl_blas_dnrm2 (&c.vector);\n gsl_vector_set (norm, i, x);\n }\n\n for (i = 0; i < GSL_MIN (M, N); i++)\n {\n /* Bring the column of largest norm into the pivot position */\n\n double max_norm = gsl_vector_get(norm, i);\n size_t j, kmax = i;\n\n for (j = i + 1; j < N; j++)\n {\n double x = gsl_vector_get (norm, j);\n\n if (x > max_norm)\n {\n max_norm = x;\n kmax = j;\n }\n }\n\n if (kmax != i)\n {\n gsl_matrix_swap_columns (A, i, kmax);\n gsl_permutation_swap (p, i, kmax);\n gsl_vector_swap_elements(norm,i,kmax);\n\n (*signum) = -(*signum);\n }\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 {\n gsl_vector_view c_full = gsl_matrix_column (A, i);\n gsl_vector_view c = gsl_vector_subvector (&c_full.vector, \n i, M - i);\n double tau_i = gsl_linalg_householder_transform (&c.vector);\n\n gsl_vector_set (tau, i, tau_i);\n\n /* Apply the transformation to the remaining columns */\n\n if (i + 1 < N)\n {\n gsl_matrix_view m = gsl_matrix_submatrix (A, i, i + 1, M - i, N - (i+1));\n\n gsl_linalg_householder_hm (tau_i, &c.vector, &m.matrix);\n }\n }\n\n /* Update the norms of the remaining columns too */\n\n if (i + 1 < M) \n {\n for (j = i + 1; j < N; j++)\n {\n double x = gsl_vector_get (norm, j);\n\n if (x > 0.0)\n {\n double y = 0;\n double temp= gsl_matrix_get (A, i, j) / x;\n \n if (fabs (temp) >= 1)\n y = 0.0;\n else\n y = x * sqrt (1 - temp * temp);\n \n /* recompute norm to prevent loss of accuracy */\n\n if (fabs (y / x) < sqrt (20.0) * GSL_SQRT_DBL_EPSILON)\n {\n gsl_vector_view c_full = gsl_matrix_column (A, j);\n gsl_vector_view c = \n gsl_vector_subvector(&c_full.vector,\n i+1, M - (i+1));\n y = gsl_blas_dnrm2 (&c.vector);\n }\n \n gsl_vector_set (norm, j, y);\n }\n }\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_QRPT_decomp2 (const gsl_matrix * A, gsl_matrix * q, gsl_matrix * r, gsl_vector * tau, gsl_permutation * p, int *signum, gsl_vector * norm)\n{\n const size_t M = A->size1;\n const size_t N = A->size2;\n\n if (q->size1 != M || q->size2 !=M) \n {\n GSL_ERROR (\"q must be M x M\", GSL_EBADLEN);\n }\n else if (r->size1 != M || r->size2 !=N)\n {\n GSL_ERROR (\"r must be M x N\", GSL_EBADLEN);\n }\n else 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 (p->size != N)\n {\n GSL_ERROR (\"permutation size must be N\", GSL_EBADLEN);\n }\n else if (norm->size != N)\n {\n GSL_ERROR (\"norm size must be N\", GSL_EBADLEN);\n }\n\n gsl_matrix_memcpy (r, A);\n\n gsl_linalg_QRPT_decomp (r, tau, p, signum, norm);\n\n /* FIXME: aliased arguments depends on behavior of unpack routine! */\n\n gsl_linalg_QR_unpack (r, tau, q, r);\n\n return GSL_SUCCESS;\n}\n\n\n/* Solves the system A x = b using the Q R P^T factorisation,\n\n R z = Q^T b\n\n x = P z;\n\n to obtain x. Based on SLATEC code. */\n\nint\ngsl_linalg_QRPT_solve (const gsl_matrix * QR,\n const gsl_vector * tau,\n const gsl_permutation * p,\n const gsl_vector * b,\n gsl_vector * 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 != p->size)\n {\n GSL_ERROR (\"matrix size must match permutation size\", GSL_EBADLEN);\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 gsl_vector_memcpy (x, b);\n\n gsl_linalg_QRPT_svx (QR, tau, p, x);\n \n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_QRPT_svx (const gsl_matrix * QR,\n const gsl_vector * tau,\n const gsl_permutation * p,\n gsl_vector * 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 != p->size)\n {\n GSL_ERROR (\"matrix size must match permutation 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 /* compute sol = Q^T b */\n\n gsl_linalg_QR_QTvec (QR, tau, x);\n\n /* Solve R x = sol, storing x inplace in sol */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);\n\n gsl_permute_vector_inverse (p, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_QRPT_QRsolve (const gsl_matrix * Q, const gsl_matrix * R,\n const gsl_permutation * p,\n const gsl_vector * b,\n gsl_vector * x)\n{\n if (Q->size1 != Q->size2 || R->size1 != R->size2)\n {\n return GSL_ENOTSQR;\n }\n else if (Q->size1 != p->size || Q->size1 != R->size1\n || Q->size1 != b->size)\n {\n return GSL_EBADLEN;\n }\n else\n {\n /* compute b' = Q^T b */\n\n gsl_blas_dgemv (CblasTrans, 1.0, Q, b, 0.0, x);\n\n /* Solve R x = b', storing x inplace */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, R, x);\n\n /* Apply permutation to solution in place */\n\n gsl_permute_vector_inverse (p, x);\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_QRPT_Rsolve (const gsl_matrix * QR,\n const gsl_permutation * p,\n const gsl_vector * b,\n gsl_vector * 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 x size\", GSL_EBADLEN);\n }\n else if (p->size != x->size)\n {\n GSL_ERROR (\"permutation size must match x size\", GSL_EBADLEN);\n }\n else\n {\n /* Copy x <- b */\n\n gsl_vector_memcpy (x, b);\n\n /* Solve R x = b, storing x inplace */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);\n\n gsl_permute_vector_inverse (p, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_QRPT_Rsvx (const gsl_matrix * QR,\n const gsl_permutation * p,\n gsl_vector * x)\n{\n if (QR->size1 != QR->size2)\n {\n GSL_ERROR (\"QR matrix must be square\", GSL_ENOTSQR);\n }\n else if (QR->size2 != x->size)\n {\n GSL_ERROR (\"matrix size must match x size\", GSL_EBADLEN);\n }\n else if (p->size != x->size)\n {\n GSL_ERROR (\"permutation size must match x size\", GSL_EBADLEN);\n }\n else\n {\n /* Solve R x = b, storing x inplace */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);\n\n gsl_permute_vector_inverse (p, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\n\n/* Update a Q R P^T factorisation for A P= Q R , A' = A + u v^T,\n\n Q' R' P^-1 = QR P^-1 + u v^T\n = Q (R + Q^T u v^T P ) P^-1\n = Q (R + w v^T P) P^-1\n\n where w = Q^T u.\n\n Algorithm from Golub and Van Loan, \"Matrix Computations\", Section\n 12.5 (Updating Matrix Factorizations, Rank-One Changes) */\n\nint\ngsl_linalg_QRPT_update (gsl_matrix * Q, gsl_matrix * R,\n const gsl_permutation * p,\n gsl_vector * w, const gsl_vector * v)\n{\n if (Q->size1 != Q->size2 || R->size1 != R->size2)\n {\n return GSL_ENOTSQR;\n }\n else if (R->size1 != Q->size2 || v->size != Q->size2 || w->size != Q->size2)\n {\n return GSL_EBADLEN;\n }\n else\n {\n size_t j, k;\n const size_t M = Q->size1;\n const size_t N = Q->size2;\n double w0;\n\n /* Apply Given's rotations to reduce w to (|w|, 0, 0, ... , 0) \n\n J_1^T .... J_(n-1)^T w = +/- |w| e_1\n\n simultaneously applied to R, H = J_1^T ... J^T_(n-1) R\n so that H is upper Hessenberg. (12.5.2) */\n\n for (k = N - 1; k > 0; k--)\n {\n double c, s;\n double wk = gsl_vector_get (w, k);\n double wkm1 = gsl_vector_get (w, k - 1);\n\n create_givens (wkm1, wk, &c, &s);\n apply_givens_vec (w, k - 1, k, c, s);\n apply_givens_qr (M, N, Q, R, k - 1, k, c, s);\n }\n\n w0 = gsl_vector_get (w, 0);\n\n /* Add in w v^T (Equation 12.5.3) */\n\n for (j = 0; j < N; j++)\n {\n double r0j = gsl_matrix_get (R, 0, j);\n size_t p_j = gsl_permutation_get (p, j);\n double vj = gsl_vector_get (v, p_j);\n gsl_matrix_set (R, 0, j, r0j + w0 * vj);\n }\n\n /* Apply Givens transformations R' = G_(n-1)^T ... G_1^T H \n Equation 12.5.4 */\n\n for (k = 1; k < N; k++)\n {\n double c, s;\n double diag = gsl_matrix_get (R, k - 1, k - 1);\n double offdiag = gsl_matrix_get (R, k, k - 1);\n\n create_givens (diag, offdiag, &c, &s);\n apply_givens_qr (M, N, Q, R, k - 1, k, c, s);\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "ac38547a5a6d013ce3f0a0e558bf6081c0c0dee0", "size": 12843, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/linalg/qrpt.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/linalg/qrpt.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/linalg/qrpt.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 26.3716632444, "max_line_length": 149, "alphanum_fraction": 0.5265903605, "num_tokens": 3693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5858214954899273}} {"text": "#include \n#include \n#include \n\n#define NRAND 1000000\n\n#define HIST_SIZE 25\n#define HIST_MIN 0\n#define HIST_MAX (HIST_SIZE - 1)\n\nint hist[HIST_SIZE];\n\nint main (void)\n{\n\tconst gsl_rng_type * T;\n\tgsl_rng * r;\n\tdouble mu = 2.0;\n\n\t/* create a generator chosen by the \n\t environment variable GSL_RNG_TYPE */\n\tgsl_rng_env_setup();\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc (T);\n\n\tprintf(\"Distribution with mean of %f\\n\", mu);\n\n\t/* print N random variates chosen from \n\t the poisson distribution with mean \n\t parameter mu */\n\tfor (int i = 0; i < NRAND; i++) {\n\t\t/* unsigned int k = gsl_ran_poisson(r, mu) + 10; */\n\t\tunsigned int k = gsl_ran_gaussian(r, mu) + 10;\n\t\tif (HIST_MIN <= k && k <= HIST_MAX) {\n\t\t\thist[k]++;\n\t\t} else {\n\t\t\tprintf (\"outside history range: %u\\n\", k);\n\t\t}\n\t}\n\n\tfor (int i = 0; i < HIST_SIZE; i++) {\n\t\tprintf(\"[%d] \", i);\n\t\tfor (int j = 0; j < hist[i] / (NRAND / 100); j++) {\n\t\t\tputchar('*');\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\tgsl_rng_free (r);\n\treturn 0;\n}\n\n", "meta": {"hexsha": "41675ef51e82f39ff8c000c7e6e90db2c7370315", "size": 1012, "ext": "c", "lang": "C", "max_stars_repo_path": "cpp/rand-distributions/gsl.c", "max_stars_repo_name": "Rugang/scraps", "max_stars_repo_head_hexsha": "5c93bc84de32a7b8011258c0371f2a132ace3f5f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-04-19T16:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T18:16:06.000Z", "max_issues_repo_path": "cpp/rand-distributions/gsl.c", "max_issues_repo_name": "Rugang/scraps", "max_issues_repo_head_hexsha": "5c93bc84de32a7b8011258c0371f2a132ace3f5f", "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": "cpp/rand-distributions/gsl.c", "max_forks_repo_name": "Rugang/scraps", "max_forks_repo_head_hexsha": "5c93bc84de32a7b8011258c0371f2a132ace3f5f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2015-04-07T07:28:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T18:31:08.000Z", "avg_line_length": 19.4615384615, "max_line_length": 53, "alphanum_fraction": 0.6126482213, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5855895591049873}} {"text": "#include \n#include \n#include \n\n#include \n#include \n\n#include \"ccl.h\"\n\n/* BCM correction */\n// See Schneider & Teyssier (2015) for details of the model.\ndouble ccl_bcm_model_fka(ccl_cosmology * cosmo, double k, double a, int *status) {\n double fkz;\n double b0;\n double bfunc, bfunc4;\n double kg;\n double gf,scomp;\n double kh;\n double z;\n\n z = 1./a - 1.;\n kh = k / cosmo->params.h;\n b0 = 0.105*cosmo->params.bcm_log10Mc - 1.27;\n bfunc = b0 / (1. + pow(z/2.3, 2.5));\n bfunc4 = (1-bfunc) * (1-bfunc) * (1-bfunc) * (1-bfunc);\n kg = 0.7 * bfunc4 * pow(cosmo->params.bcm_etab, -1.6);\n gf = bfunc / (1 + pow(kh/kg, 3.)) + 1. - bfunc; //k in h/Mpc\n scomp = 1 + (kh / cosmo->params.bcm_ks) * (kh / cosmo->params.bcm_ks); //k in h/Mpc\n fkz = gf * scomp;\n return fkz;\n}\n\n\nvoid ccl_bcm_correct(ccl_cosmology *cosmo, ccl_f2d_t *psp, int *status)\n{\n size_t nk, na;\n double *x, *z, *y2d=NULL;\n\n //Find lk array\n if(psp->fk != NULL) {\n nk = psp->fk->size;\n x = psp->fk->x;\n }\n else {\n nk = psp->fka->interp_object.xsize;\n x = psp->fka->xarr;\n }\n\n //Find a array\n if(psp->fa != NULL) {\n na = psp->fa->size;\n z = psp->fa->x;\n }\n else {\n na = psp->fka->interp_object.ysize;\n z = psp->fka->yarr;\n }\n\n //Allocate pka array\n y2d = malloc(nk * na * sizeof(double));\n if (y2d == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_bcm.c: ccl_bcm_correct(): \"\n \"memory allocation\\n\");\n }\n\n if (*status == 0) {\n for (int j = 0; jis_log)\n y2d[j*nk + i] = log(pk*fbcm);\n else\n y2d[j*nk + i] = pk*fbcm;\n }\n }\n }\n }\n\n if (*status == 0) {\n gsl_spline2d *fka = gsl_spline2d_alloc(gsl_interp2d_bicubic, nk, na);\n\n if (fka == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_bcm.c: ccl_bcm_correct(): \"\n \"memory allocation\\n\");\n }\n if(*status == 0) {\n int spstatus = gsl_spline2d_init(fka, x, z, y2d, nk, na);\n if(spstatus) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_bcm.c: ccl_bcm_correct(): \"\n \"Error initializing spline\\n\");\n }\n }\n if(*status == 0) {\n if(psp->fa != NULL)\n gsl_spline_free(psp->fa);\n if(psp->fk != NULL)\n gsl_spline_free(psp->fk);\n if(psp->fka != NULL)\n gsl_spline2d_free(psp->fka);\n psp->fka = fka;\n psp->is_factorizable = 0;\n psp->is_k_constant = 0;\n psp->is_a_constant = 0;\n }\n else\n gsl_spline2d_free(fka);\n }\n\n free(y2d);\n}\n", "meta": {"hexsha": "b442cfe194715fbd2d053de07754b47f0f4052b1", "size": 3083, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_bcm.c", "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_issues_repo_path": "src/ccl_bcm.c", "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 703.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_forks_repo_path": "src/ccl_bcm.c", "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "avg_line_length": 25.9075630252, "max_line_length": 85, "alphanum_fraction": 0.5235160558, "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.585152375702795}} {"text": "#include \n#include \"2d_array.h\"\n#include \"const.h\"\n#include \"misc.h\"\n#include \"utilities.h\"\n#include \n#include \n#include \n\n/******************************************************************************\nMODULE: rmse_from_square_root_mean\n\nPURPOSE: simulate matlab calculate rmse from square root mean\n\nRETURN VALUE:\nType = void\nValue Description\n----- -----------\n\n\nHISTORY:\nDate Programmer Reason\n-------- --------------- -------------------------------------\n5/28/2019 Su Ye Original Development\n\n******************************************************************************/\nvoid rmse_from_square_root_mean\n(\n float **array, /* I: input array */\n float fit_cft, /* I: input fit_cft value */\n int dim1_index, /* I: dimension 1 index in input array */\n int dim2_len, /* I: dimension 2 length */\n float *rmse /* O: output rmse */\n)\n{\n int i;\n float sum = 0.0;\n\n for (i = 0; i < dim2_len; i++)\n {\n sum += (array[dim1_index][i] - fit_cft) *\n (array[dim1_index][i] - fit_cft);\n }\n *rmse = sqrt(sum / dim2_len);\n}\n\n/******************************************************************************\nMODULE: dofit\n\nPURPOSE: Declare data type and allocate memory and do multiple linear robust\n fit used for auto_robust_fit\n\nRETURN VALUE: None\n\nHISTORY:\nDate Programmer Reason\n-------- --------------- -------------------------------------\n5/28/2019 Su Ye Original Development\n\nNOTES:\n******************************************************************************/\nvoid dofit(const gsl_multifit_robust_type *T,\n const gsl_matrix *X, const gsl_vector *y,\n gsl_vector *c, gsl_matrix *cov)\n{\n gsl_multifit_robust_workspace * work\n = gsl_multifit_robust_alloc (T, X->size1, X->size2);\n gsl_multifit_robust (X, y, c, cov, work);\n gsl_multifit_robust_free (work);\n work = NULL;\n}\n\nvoid dofit_linear(const gsl_matrix *X, const gsl_vector *y,\n gsl_vector *c, gsl_matrix *cov)\n{\n double chisq;\n gsl_multifit_linear_workspace * work\n = gsl_multifit_linear_alloc ( X->size1, X->size2);\n gsl_multifit_linear(X, y, c, cov, &chisq,work);\n gsl_multifit_linear_free (work);\n // work = NULL; // SY 03242019\n}\n\n/******************************************************************************\nMODULE: auto_robust_fit\n\nPURPOSE: Robust fit for one band\n\nRETURN VALUE: None\n\nHISTORY:\nDate Programmer Reason\n-------- --------------- -------------------------------------\n5/28/2019 Su Ye Original Development\n\nNOTES:\n******************************************************************************/\nvoid auto_robust_fit\n(\n float **clrx,\n float **clry,\n int nums,\n int start,\n int band_index,\n float *coefs\n)\n{\n int i, j;\n const int p = 2; /* linear fit */\n gsl_matrix *x, *cov;\n gsl_vector *y, *c;\n\n /******************************************************************/\n /* */\n /* Defines the inputs/outputs for robust fitting */\n /* */\n /******************************************************************/\n\n x = gsl_matrix_alloc (nums, p);\n y = gsl_vector_alloc (nums);\n\n c = gsl_vector_alloc (p);\n cov = gsl_matrix_alloc (p, p);\n\n /******************************************************************/\n /* */\n /* construct design matrix x for linear fit */\n /* */\n /******************************************************************/\n\n for (i = 0; i < nums; ++i)\n {\n for (j = 0; j < p; j++)\n {\n if (j == 0)\n {\n gsl_matrix_set (x, i, j, 1.0);\n }\n else\n {\n gsl_matrix_set (x, i, j, (double)clrx[i][j-1]);\n }\n }\n gsl_vector_set(y,i,(double)clry[band_index][i+start]);\n }\n\n /******************************************************************/\n /* */\n /* perform robust fit */\n /* */\n /******************************************************************/\n\n dofit(gsl_multifit_robust_bisquare, x, y, c, cov);\n\n for (j = 0; j < (int)c->size; j++)\n {\n coefs[j] = gsl_vector_get(c, j);\n }\n\n /******************************************************************/\n /* */\n /* Free the memories */\n /* */\n /******************************************************************/\n\n gsl_matrix_free (x);\n x = NULL;\n gsl_vector_free (y);\n y = NULL;\n gsl_vector_free (c);\n c = NULL;\n gsl_matrix_free (cov);\n cov = NULL;\n}\n\n\n/******************************************************************************\nMODULE: auto_mask\n\nPURPOSE: Multitemporal cloud, cloud shadow, & snow masks (global version)\n\nRETURN VALUE:\nType = int\nERROR error out due to memory allocation\nSUCCESS no error encounted\n\nHISTORY:\nDate Programmer Reason\n-------- --------------- -------------------------------------\n05282019 Su Ye\n\nNOTES:\n******************************************************************************/\nint auto_mask\n(\n int *clrx,\n float **clry,\n int start,\n int end,\n float years,\n float t_b1,\n float t_b2,\n float n_t,\n int *bl_ids\n)\n{\n char FUNC_NAME[] = \"auto_mask\";\n int i;\n float **x;\n float pred_b2, pred_b4;\n int nums;\n float coefs[ROBUST_COEFFS];\n float coefs2[ROBUST_COEFFS];\n\n nums = end - start + 1;\n /* Allocate memory */\n x = (float **)allocate_2d_array(nums, ROBUST_COEFFS - 1, sizeof(float));\n if (x == NULL)\n {\n RETURN_ERROR(\"ERROR allocating x memory\", FUNC_NAME, ERROR);\n }\n\n for (i = 0; i < nums; i++)\n {\n x[i][0] = (float)clrx[i+start];\n }\n\n /******************************************************************/\n /* */\n /* Do robust fitting for band 2 */\n /* */\n /******************************************************************/\n\n auto_robust_fit(x, clry, nums, start, 1, coefs);\n\n /******************************************************************/\n /* */\n /* Do robust fitting for band 4 */\n /* */\n /******************************************************************/\n\n auto_robust_fit(x, clry, nums, start, 3, coefs2);\n\n /******************************************************************/\n /* */\n /* predict band 2 and band 4 refs, bl_ids value of 0 is clear and */\n /* 1 otherwise */\n /* */\n /******************************************************************/\n\n for (i = 0; i < nums; i++)\n {\n pred_b2 = coefs[0] + coefs[1] * (float)clrx[i+start];\n pred_b4 = coefs2[0] + coefs2[1] * (float)clrx[i+start];\n if (((clry[1][i+start]-pred_b2) > (n_t * t_b1)) ||\n ((clry[3][i+start]-pred_b4) < -(n_t * t_b2)))\n {\n bl_ids[i] = 1;\n }\n else\n {\n bl_ids[i] = 0;\n }\n }\n\n /* Free allocated memory */\n if (free_2d_array ((void **) x) != SUCCESS)\n {\n RETURN_ERROR (\"Freeing memory: x\\n\", FUNC_NAME, ERROR);\n }\n\n return (SUCCESS);\n}\n\n/******************************************************************************\nMODULE: adjust_median_variogram\n\nPURPOSE: calculate absolute variogram for auto_mask\n\nRETURN VALUE:\nType = void\nValue Description\n----- -----------\n\n\nHISTORY:\nDate Programmer Reason\n-------- --------------- -------------------------------------\n28/05/2019 Su Ye Original Development\n\nNOTES:\n******************************************************************************/\nint adjust_median_variogram\n(\n int *clrx, /* I: dates */\n float **array, /* I: input array */\n int dim1_len, /* I: dimension 1 length in input array */\n int dim2_start, /* I: dimension 2 start index */\n int dim2_end, /* I: dimension 2 end index */\n float *date_vario, /* O: outputted median variogran for dates */\n float *max_neighdate_diff, /* O: maximum difference for two neighbor times */\n float *output_array /* O: output array */\n)\n{\n int i, j; /* loop indecies */\n float *var; /* pointer for allocation variable memory */\n int dim2_len = dim2_end - dim2_start + 1; /* perhaps should get defined */\n char FUNC_NAME[] = \"adjust_median_variogram\"; /* for error messages */\n int max_freq;\n int m;\n\n// for (i = 0; i < dim2_len; i++)\n// {\n// for (j = 0; j < TOTAL_IMAGE_BANDS; j++)\n// {\n// printf(\"%f\\n\", (float)array[j][i]);\n// }\n\n// }\n\n if (dim2_len == 1)\n {\n for (i = 0; i < dim1_len; i++)\n {\n output_array[i] = array[i][dim2_start];\n *date_vario = clrx[dim2_start];\n return (SUCCESS);\n }\n }\n\n var = malloc((dim2_len-1) * sizeof(float));\n if (var == NULL)\n {\n RETURN_ERROR (\"Allocating var memory\", FUNC_NAME, ERROR);\n }\n\n for (j = dim2_start; j < dim2_end; j++)\n {\n var[j] = abs(clrx[j+1] - clrx[j]);\n }\n quick_sort_float(var, dim2_start, dim2_end-1);\n m = (dim2_len-1) / 2;\n if ((dim2_len-1) % 2 == 0)\n {\n\n *date_vario = (var[m-1] + var[m]) / 2.0;\n }\n else\n *date_vario = var[m];\n\n *max_neighdate_diff = var[dim2_len-2];\n\n\n\n for (i = 0; i < dim1_len; i++)\n {\n for (j = dim2_start; j < dim2_end; j++)\n {\n var[j] = abs(array[i][j+1] - array[i][j]);\n //printf(\"%d var for band %d: %f\\n\", j, i+1, (float)var[j]);\n\n }\n quick_sort_float(var, dim2_start, dim2_end-1);\n// for (j = 0; j < dim2_end; j++)\n// {\n// printf(\"%f\\n\", var[j]);\n// }\n m = (dim2_len-1) / 2;\n if ((dim2_len-1) % 2 == 0)\n {\n //printf(\"%f\\n\", var[m-1]);\n //printf(\"%f\\n\", var[m]);\n output_array[i] = (var[m-1] + var[m]) / 2.0;\n }\n else\n output_array[i] = var[m];\n\n }\n\n free(var);\n\n\n return (SUCCESS);\n}\n\n\n/******************************************************************************\n *\nMODULE: single_median_variogram\nPURPOSE: calculate absolute variogram for a single band\n\nRETURN VALUE:\nType = void\nValue Description\n----- -----------\n\n\nHISTORY:\nDate Programmer Reason\n-------- --------------- -------------------------------------\n22/06/2019 Su Ye Original Development\n\nNOTES:\n******************************************************************************/\nint single_median_variogram\n(\n short int *array, /* I: input array */\n int i_start,\n int i_end,\n short int *variogram,\n short int *mediam_value /* O: outputted mediam value */\n)\n{\n int j, m; /* loop indecies */\n char FUNC_NAME[] = \"single_median_variogram\"; /* for error messages */\n short int *var; /* pointer for allocation variable memory */\n int obs_num;\n int var_count = 0;\n short int *array_cpy;\n\n obs_num = i_end - i_start + 1;\n\n// for (j = 0; j < obs_num; j++)\n// {\n// printf(\"%i\\n\", array[j]);\n\n// }\n\n if (obs_num == 1)\n {\n *variogram = 0;\n *mediam_value = array[0];\n return (SUCCESS);\n\n }\n\n var = malloc((obs_num-1) * sizeof(short int));\n if (var == NULL)\n {\n RETURN_ERROR (\"Allocating var memory\", FUNC_NAME, ERROR);\n }\n\n array_cpy = malloc(obs_num * sizeof(short int));\n if (array_cpy == NULL)\n {\n RETURN_ERROR (\"Allocating array_cpy memory\", FUNC_NAME, ERROR);\n }\n\n\n for (j = i_start; j < i_end; j++)\n {\n var[j] = (short int)abs(array[j+1] - array[j]);\n //printf(\"%d var for band %d: %f\\n\", j, i+1, (float)var[j]);\n\n }\n\n for (j = i_start; j < i_end+1; j++)\n {\n array_cpy[j] = array[j];\n //printf(\"%d var for band %d: %f\\n\", j, i+1, (float)var[j]);\n\n }\n quick_sort_shortint(var, 0, obs_num-2);\n// for (j = 0; j < obs_num-1; j++)\n// {\n// printf(\"%d\\n\", var[j]);\n// }\n\n /* compute variogram */\n m = (obs_num-1) / 2;\n if ((obs_num-1) % 2 == 0)\n {\n *variogram = (short int) ((var[m-1] + var[m]) / 2.0);\n }\n else\n *variogram = var[m];\n\n\n /* compute mediam value */\n quick_sort_shortint(array_cpy, i_start, i_end);\n// for (j = 0; j < obs_num; j++)\n// {\n// printf(\"%d\\n\", array_cpy[j]);\n// }\n\n m = obs_num / 2;\n if (obs_num % 2 == 0)\n {\n *mediam_value = (short int)((array_cpy[m-1] + array_cpy[m]) / 2.0);\n }\n else\n *mediam_value = array_cpy[m];\n\n\n free(var);\n free(array_cpy);\n\n return (SUCCESS);\n}\n\n\n/******************************************************************************\n *\nMODULE: single_median_variogram\nPURPOSE: calculate absolute variogram for a single band\n\nRETURN VALUE:\nType = void\nValue Description\n----- -----------\n\n\nHISTORY:\nDate Programmer Reason\n-------- --------------- -------------------------------------\n22/06/2019 Su Ye Original Development\n\nNOTES:\n******************************************************************************/\nint single_median_quantile\n(\n short int *array, /* I: input array */\n int i_start,\n int i_end,\n short int *quantile, /* O: outputted quantile value */\n short int *mediam_value\n)\n{\n int j, m; /* loop indecies */\n char FUNC_NAME[] = \"single_median_quantile\"; /* for error messages */\n short int *var; /* pointer for allocation variable memory */\n int obs_num;\n int var_count = 0;\n short int *array_cpy;\n\n obs_num = i_end - i_start + 1;\n\n// for (j = 0; j < obs_num; j++)\n// {\n// printf(\"%i\\n\", array[j]);\n\n// }\n\n if (obs_num == 1)\n {\n *mediam_value = array[0];\n *quantile = array[0];\n return (SUCCESS);\n\n }\n\n var = malloc((obs_num-1) * sizeof(short int));\n if (var == NULL)\n {\n RETURN_ERROR (\"Allocating var memory\", FUNC_NAME, ERROR);\n }\n\n array_cpy = malloc(obs_num * sizeof(short int));\n if (array_cpy == NULL)\n {\n RETURN_ERROR (\"Allocating array_cpy memory\", FUNC_NAME, ERROR);\n }\n\n\n\n\n for (j = i_start; j < i_end+1; j++)\n {\n array_cpy[j] = array[j];\n //printf(\"%d var for band %d: %f\\n\", j, i+1, (float)var[j]);\n\n }\n\n\n /* compute mediam value */\n quick_sort_shortint(array_cpy, i_start, i_end);\n// for (j = 0; j < obs_num; j++)\n// {\n// printf(\"%d\\n\", array_cpy[j]);\n// }\n\n m = obs_num / 2;\n if (obs_num % 2 == 0)\n {\n *mediam_value = (short int)((array_cpy[m-1] + array_cpy[m]) / 2.0);\n }\n else\n *mediam_value = array_cpy[m];\n\n *quantile = array_cpy[obs_num / 4];\n\n free(var);\n free(array_cpy);\n\n return (SUCCESS);\n}\n/******************************************************************************\n *\nMODULE: single_mean_rmse\nPURPOSE: calculate absolute variogram for a single band\n\nRETURN VALUE:\nType = void\nValue Description\n----- -----------\n\n\nHISTORY:\nDate Programmer Reason\n-------- --------------- -------------------------------------\n22/06/2019 Su Ye Original Development\n\nNOTES:\n******************************************************************************/\nint single_mean_rmse\n(\n short int *array, /* I: input array */\n int i_start,\n int i_end,\n float *rmse,\n float *mean /* O: outputted mediam value */\n)\n{\n int j, m; /* loop indecies */\n char FUNC_NAME[] = \"single_mean_rse\"; /* for error messages */\n short int *var; /* pointer for allocation variable memory */\n int obs_num;\n int sum = 0;\n int rmse_sum = 0;\n\n obs_num = i_end - i_start + 1;\n\n// for (j = 0; j < obs_num; j++)\n// {\n// printf(\"%i\\n\", array[j]);\n\n// }\n\n if (obs_num == 1)\n {\n *rmse = 0;\n *mean = array[0];\n return (SUCCESS);\n\n }\n\n var = malloc((obs_num-1) * sizeof(short int));\n if (var == NULL)\n {\n RETURN_ERROR (\"Allocating var memory\", FUNC_NAME, ERROR);\n }\n\n\n for (j = i_start; j < i_end + 1; j++)\n {\n sum = sum + (int)array[j];\n }\n\n *mean = (float)((float)sum / (float)obs_num);\n\n for (j = i_start; j < i_end + 1; j++)\n {\n rmse_sum = rmse_sum + (array[j] - *mean) * (array[j] - *mean);\n }\n\n *rmse = (float)sqrt((double)rmse_sum/(double)obs_num);\n return (SUCCESS);\n}\n\n\n/******************************************************************************\nMODULE: linear_fit_centerdate\n\nPURPOSE: Robust fit for one band\n\nRETURN VALUE: None\n\nHISTORY:\nDate Programmer Reason\n-------- --------------- -------------------------------------\n5/31/2019 Su Ye Original Development\n\nNOTES:\n******************************************************************************/\nvoid linear_fit_centerdate\n(\n int *clrx,\n float **clry,\n int nums,\n int start,\n int center_date,\n int i_col,\n short int **composites,\n int bweighted,\n float *C0,\n float *C1\n)\n{\n char FUNC_NAME[] = \"linear_fit_centerdate\";\n double c0;\n double c1;\n double cov00;\n double cov01;\n double cov11;\n double sumsq;\n int i;\n double* x;\n double* y_b1;\n double* y_b2;\n double* y_b3;\n double* y_b4;\n double* w;\n float coefs[ROBUST_COEFFS];\n float** x_t;\n\n\n x = (double*)malloc(nums * sizeof(double));\n if (x == NULL)\n {\n RETURN_ERROR(\"ERROR allocating x memory\", FUNC_NAME, FAILURE);\n }\n\n y_b1 = (double*)malloc(nums * sizeof(double));\n if (y_b1 == NULL)\n {\n RETURN_ERROR(\"ERROR allocating y_b1 memory\", FUNC_NAME, FAILURE);\n }\n\n y_b2 = (double*)malloc(nums * sizeof(double));\n if (y_b2 == NULL)\n {\n RETURN_ERROR(\"ERROR allocating y_b2 memory\", FUNC_NAME, FAILURE);\n }\n\n y_b3 = (double*)malloc(nums * sizeof(double));\n if (y_b3 == NULL)\n {\n RETURN_ERROR(\"ERROR allocating y_b3 memory\", FUNC_NAME, FAILURE);\n }\n\n y_b4 = (double*)malloc(nums * sizeof(double));\n if (y_b4 == NULL)\n {\n RETURN_ERROR(\"ERROR allocating y_b4 memory\", FUNC_NAME, FAILURE);\n }\n\n w = (double*)malloc(nums * sizeof(double));\n if (w == NULL)\n {\n RETURN_ERROR(\"ERROR allocating y_b4 memory\", FUNC_NAME, FAILURE);\n }\n\n x_t = (float **)allocate_2d_array(nums, ROBUST_COEFFS - 1, sizeof(float));\n if (x_t == NULL)\n {\n RETURN_ERROR(\"ERROR allocating x_t memory\", FUNC_NAME, ERROR);\n }\n\n for (i = 0; i < nums; i++)\n {\n x_t[i][0] = (float)clrx[i+start];\n }\n\n\n /******************************************************************/\n /* */\n /* Defines the inputs/outputs for robust fitting */\n /* */\n /******************************************************************/\n\n\n\n\n /******************************************************************/\n /* */\n /* construct design matrix x for linear fit */\n /* */\n /******************************************************************/\n\n for (i = 0; i < nums; ++i)\n {\n x[i] = (double)clrx[i];\n y_b1[i] = (double)clry[0][i];\n y_b2[i] = (double)clry[1][i];\n y_b3[i] = (double)clry[2][i];\n y_b4[i] = (double)clry[3][i];\n\n }\n\n /******************************************************************/\n /* */\n /* perform robust fit */\n /* */\n /******************************************************************/\n\n if (bweighted == TRUE)\n {\n /* create hot weights */\n for (i = 0; i < nums; ++i)\n {\n w[i] = (double)1/(abs(y_b1[i] - 0.5 * y_b3[i]));\n }\n\n gsl_fit_wlinear (x, 1, w, 1, y_b1, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n composites[0][i_col] = (short int)(c0 + c1 * center_date);\n C0[0] = (float)c0;\n C1[0] = (float)c1;\n\n gsl_fit_wlinear (x, 1, w, 1, y_b2, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n composites[1][i_col] = (short int)(c0 + c1 * center_date);\n C0[1] = (float)c0;\n C1[1] = (float)c1;\n\n gsl_fit_wlinear (x, 1, w, 1, y_b3, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n composites[2][i_col] = (short int)(c0 + c1 * center_date);\n C0[2] = (float)c0;\n C1[2] = (float)c1;\n\n gsl_fit_wlinear (x, 1, w, 1, y_b4, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n composites[3][i_col] = (short int)(c0 + c1 * center_date);\n C0[3] = (float)c0;\n C1[3] = (float)c1;\n }\n else\n {\n /* OLS*/\n// gsl_fit_linear (x, 1, y_b1, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n// composites[0][i_col] = (short int)(c0 + c1 * center_date);\n// C0[0] = (float)c0;\n// C1[0] = (float)c1;\n\n// gsl_fit_linear (x, 1, y_b2, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n// composites[1][i_col] = (short int)(c0 + c1 * center_date);\n// C0[1] = (float)c0;\n// C1[1] = (float)c1;\n\n// gsl_fit_linear (x, 1, y_b3, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n// composites[2][i_col] = (short int)(c0 + c1 * center_date);\n// C0[2] = (float)c0;\n// C1[2] = (float)c1;\n\n// gsl_fit_linear (x, 1, y_b4, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n// composites[3][i_col] = (short int)(c0 + c1 * center_date);\n// C0[3] = (float)c0;\n// C1[3] = (float)c1;\n /* robust regression */\n for(i = 0; i < TOTAL_IMAGE_BANDS; i++)\n {\n auto_robust_fit(x_t, clry, nums, start, i, coefs);\n composites[i][i_col] = (short int)(coefs[0] + coefs[1] * center_date);\n C0[i] = (float)coefs[0];\n C1[i] = (float)coefs[1];\n\n }\n }\n\n\n\n\n\n\n /******************************************************************/\n /* */\n /* Free the memories */\n /* */\n /******************************************************************/\n\n free (x);\n free (y_b1);\n free (y_b2);\n free (y_b3);\n free (y_b4);\n free (w);\n /* Free allocated memory */\n if (free_2d_array ((void **) x_t) != SUCCESS)\n {\n RETURN_ERROR (\"Freeing memory: x_t\\n\", FUNC_NAME, ERROR);\n }\n\n}\n\n/******************************************************************************\nMODULE: median_filter\n\nPURPOSE: calculate mediam filtering for three buf scanline\n\nRETURN VALUE: None\n\nHISTORY:\nDate Programmer Reason\n-------- --------------- -------------------------------------\n6/12/2019 Su Ye Original Development\n\nNOTES:\n******************************************************************************/\nint median_filter\n(\n short int **buf1,\n short int **buf2,\n short int **buf3,\n short int **buf,\n int *valid_datecount_scanline, /* I: the number of valid dates */\n int num_scenes,\n int n_cols\n)\n{\n int i, b, j;\n short int window[9];\n\n for(i = 0; i < n_cols; i++)\n {\n for(j = 0; j < valid_datecount_scanline[i]; j++)\n {\n if(i==0)\n {\n for(b = 0; b < TOTAL_IMAGE_BANDS; b++)\n {\n window[0] = buf1[b][i * num_scenes + j];\n window[1] = buf1[b][i * num_scenes + j];\n window[2] = buf1[b][(i+1) * num_scenes + j];\n window[3] = buf2[b][i * num_scenes + j];\n window[4] = buf2[b][i * num_scenes + j];\n window[5] = buf2[b][(i+1) * num_scenes + j];\n window[6] = buf3[b][i * num_scenes + j];\n window[7] = buf3[b][i * num_scenes + j];\n window[8] = buf3[b][(i+1) * num_scenes + j];\n\n quick_sort_shortint(window, 0, 8);\n\n buf[b][i * num_scenes + j] = window[4];\n\n }\n }\n else if (i == n_cols - 1)\n {\n for(b = 0; b < TOTAL_IMAGE_BANDS; b++)\n {\n window[0] = buf1[b][(i-1) * num_scenes + j];\n window[1] = buf1[b][i * num_scenes + j];\n window[2] = buf1[b][i * num_scenes + j];\n window[3] = buf2[b][(i-1) * num_scenes + j];\n window[4] = buf2[b][i * num_scenes + j];\n window[5] = buf2[b][i * num_scenes + j];\n window[6] = buf3[b][(i-1) * num_scenes + j];\n window[7] = buf3[b][i * num_scenes + j];\n window[8] = buf3[b][i * num_scenes + j];\n\n quick_sort_shortint(window, 0, 8);\n\n buf[b][i * num_scenes + j] = window[4];\n\n }\n }\n else\n {\n for(b = 0; b < TOTAL_IMAGE_BANDS; b++)\n {\n window[0] = buf1[b][(i-1) * num_scenes + j];\n window[1] = buf1[b][i * num_scenes + j];\n window[2] = buf1[b][(i+1) * num_scenes + j];\n window[3] = buf2[b][(i-1) * num_scenes + j];\n window[4] = buf2[b][i * num_scenes + j];\n window[5] = buf2[b][(i+1) * num_scenes + j];\n window[6] = buf3[b][(i-1) * num_scenes + j];\n window[7] = buf3[b][i * num_scenes + j];\n window[8] = buf3[b][(i+1) * num_scenes + j];\n\n quick_sort_shortint(window, 0, 8);\n\n buf[b][i * num_scenes + j] = window[4];\n\n }\n }\n\n }\n\n }\n\n\n}\n", "meta": {"hexsha": "86d7e538d4942d6e30588011910625cb03fe0249", "size": 28013, "ext": "c", "lang": "C", "max_stars_repo_path": "C/AFMapTSComposite/misc.c", "max_stars_repo_name": "agroimpacts/imager", "max_stars_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T18:48:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T18:48:12.000Z", "max_issues_repo_path": "C/AFMapTSComposite/misc.c", "max_issues_repo_name": "agroimpacts/imager", "max_issues_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "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": "C/AFMapTSComposite/misc.c", "max_forks_repo_name": "agroimpacts/imager", "max_forks_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "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": 28.5555555556, "max_line_length": 94, "alphanum_fraction": 0.3956377396, "num_tokens": 6952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5851523740163523}} {"text": "//\n// lu2lib.c\n//\n// J. Makino\n// Time-stamp: <2019-05-06 22:08:30 makino>\n#include \n#include \n#include \n#include \n#ifndef NOBLAS\n#ifdef MKL\n#include \n#else\n#include \n#endif\n#endif\n#ifdef USEGDR\n#include \"gdrdgemm.h\"\n#endif\n\n#define FTYPE double\n#include \ntypedef double v2df __attribute__((vector_size(16)));\ntypedef union {v2df v; double s[2];}v2u;\n\n#ifndef USEGDR\nvoid gdrsetboardid(int boardid)\n{}\n#endif\n\n\nvoid matmul2_host(int n,\n\t\t FTYPE a[n][n],\n\t\t FTYPE b[n][n],\n\t\t FTYPE c[n][n])\n\n{\n int i, j, k;\n for(i=0;i m) iend = m;\n\t//\tfprintf(stderr, \"m, i, ifirst, iend = %d %d %d %d\\n\", m, ii, ifirst, iend);\n\tif (ifirst < m){\n\t matmul_for_nk8_0(n1, a[ifirst], n2, b, n3, c[ifirst], iend-ifirst, n);\n\t}\n }\n\t\n}\n\nvoid matmul_for_nk16_0(int n1, double a[][n1],\n\t\t\t int n2, double b[][n2],\n\t\t\t int n3, double c[][n3],\n\t\t\t int m,\n\t\t\t int n)\n{\n int i;\n int mm=64;\n for(i=0;im) mm=m-i;\n\tmatmul_for_nk8_0(n1, (double(*)[]) (a[i]), n2, b,\n\t\t\t n3, (double(*)[]) (c[i]), mm, 16);\n\tmatmul_for_nk8_0(n1, (double(*)[]) (&a[i][8]), n2,(double(*)[])(b[8]),\n\t\t\t n3, (double(*)[]) (c[i]), mm, 16);\n }\n \n}\nvoid matmul_for_nk16(int n1, double a[][n1],\n\t\t\t int n2, double b[][n2],\n\t\t\t int n3, double c[][n3],\n\t\t\t int m,\n\t\t\t int n)\n{\n if (m < 64){\n\tmatmul_for_nk16_0c(n1, a, n2, b, n3, c, m, n);\n\treturn;\n }\n int ii;\n int dm = (m+63)/64;\n dm*= 16;\n#pragma omp parallel for private(ii)\t schedule(static)\n for(ii=0;ii<4;ii++){\n\tint ifirst, iend;\n\tifirst = ii*dm;\n\tiend = ifirst+dm;\n\tif (iend > m) iend = m;\n\t//\tfprintf(stderr, \"m, i, ifirst, iend = %d %d %d %d\\n\", m, ii, ifirst, iend);\n\tif (ifirst < m){\n\t matmul_for_nk16_0c(n1, a[ifirst], n2, b, n3, c[ifirst], iend-ifirst, n);\n\t}\n }\n\t\n}\n\nvoid matmul_for_nk32(int n1, double a[][n1],\n\t\t\t int n2, double b[][n2],\n\t\t\t int n3, double c[][n3],\n\t\t\t int m,\n\t\t\t int n)\n{\n int ii;\n int dm = (m+127)/128;\n dm*= 32;\n#pragma omp parallel for private(ii)\t schedule(static)\n for(ii=0;ii<4;ii++){\n\tint ifirst, iend;\n\tifirst = ii*dm;\n\tiend = ifirst+dm;\n\tif (iend > m) iend = m;\n\t//\tfprintf(stderr, \"m, i, ifirst, iend = %d %d %d %d\\n\", m, ii, ifirst, iend);\n\tif (ifirst < m){\n\t matmul_for_nk32_0(n1, a[ifirst], n2, b, n3, c[ifirst], iend-ifirst, n);\n\t}\n }\n\t\n}\n\n\nvoid matmul_for_small_nk_7(int n1, double a[][n1],\n\t\t\t int n2, double b[][n2],\n\t\t\t int n3, double c[][n3],\n\t\t\t int m,\n\t\t\t int kk,\n\t\t\t int n)\n{\n\n int i,j;\n int nh = n/2;\n register int k;\n double bcopy[n][kk];\n v2df bcopy2[nh][kk];\n v2df acopy[kk];\n v2df acopy2[kk];\n double *acp = (double*) acopy;\n double *acp2 = (double*) acopy2;\n unsigned long bpcount, apcount, dotcount;\n if (kk == 8){\n\tmatmul_for_nk8(n1, a, n2, b, n3, c, m, n);\n\treturn;\n }\n BEGIN_TSC;\n bpcount= apcount= dotcount=0;\n // BEGIN_TSC;\n for(k=0;k= 512){\n\tget_cputime(&t0,&t1);\n }\n BEGIN_TSC;\n BEGIN_TIMER(timer);\n#ifdef USEGDR\n if ((k>512) || ((k==512) && ((n>=1024)||(m>=1024)))){\n\t// if (k>=2048){\n\tmygdrdgemm(m, n, k, alpha, a, na, b, nb, beta, c, nc);\n }else{\n\tif ((k<=16) && (alpha == -1.0) && (beta == 1.0)){\n\t matmul_for_small_nk(na, a, nb, b, nc, c, m, n, k);\n\t}else{\n\t \n\t cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,\n\t\t\t m,n, k, alpha, a, na, b, nb, beta, c, nc);\n\t}\n }\n#else\n#ifdef GEMMTEST\n mytestdgemm(m, n, k, na, nb, nc,alpha, a, b, beta, c);\n#else\n cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,\n\t m,n, k, alpha, a, na, b, nb, beta, c, nc);\n#endif \n#endif\t\n // cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,\n //\t\t m,n, k, alpha, a, na, b, nb, beta, c, nc);\n if (k==2048){\n\tEND_TIMER(timer,31,((double)(m))*n*k*2);\n\tEND_TSC(t,14);\n }else if (k==1024){\n\tEND_TIMER(timer,32,((double)(m))*n*k*2);\n\tEND_TSC(t,15);\n }else if (k==512){\n\tEND_TIMER(timer,33,((double)(m))*n*k*2);\n\tEND_TSC(t,17);\n }else{\n\tEND_TIMER(timer,34,((double)(m))*n*k*2);\n\tEND_TSC(t,18);\n }\n\t\n if (k>= 512){\n\tget_cputime(&t0,&t1);\n\tdprintf(10,\"dgemm M=%d N=%d K=%d time=%10.4g %g Gflops\\n\",\n\t\tm,n,k,t0, ((double)m)*n*k*2/t0/1e9);\n }\n}\n\n\nvoid reset_gdr(int m, double a[][m], int nb, double awork[][nb], int n)\n{\n#ifdef USEGDR \n double aw2[nb][nb];\n if (nb < 2048){\n\tfprintf(stderr,\"reset_gdr nb = %d <2048 not supported\\n\", nb);\n\texit(-1);\n }\n gdr_check_and_restart(a, awork, aw2);\n \n int i,j;\n dprintf(9,\"reset_gdr clear awork\\n\");\n for (i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define RESOLUTION 28 // bmp image 28*28\n#define LINE_LEN (RESOLUTION * RESOLUTION * 4) // All the pixel data stored within a line\n#define DATA_NUM_WITHOUT_LABEL (RESOLUTION * RESOLUTION) // Data length without label\n#define DATA_NUM_WITH_LABEL ((RESOLUTION * RESOLUTION) + 1) // For training, the first number is label, so +1\n#define HIDDEN_NODE 250 // node number in hidden layer\n#define OUTPUT_NODE 10 // output node number\n#define LEARN_RATE 0.1\n#define TRAIN_SET_SIZE 5000 \n#define TEST_SET_SIZE 1000\n#define EPOCH 8 \n\n#define SIGMOID(x) (1.0 / (1.0 + (pow(M_E, -x))))\n#define NOR_DIS_DEV(x) (pow(x, -0.5)) // For generating init weight\n\nFILE* openfile(char* file_name);\nvoid read_parse(FILE* fp, int input_data[], int* label, char* mode);\ngsl_matrix* scale_input(int input_data[]);\ngsl_matrix* vectorize_target(int label);\ngsl_matrix* init_weight(int row, int col);\ndouble get_output_error(gsl_matrix* target, gsl_matrix* output, gsl_matrix* output_error);\nvoid training(gsl_matrix* better_input, gsl_matrix* target, gsl_matrix* input_weight, gsl_matrix* hidden_weight, gsl_matrix* hidden_x, gsl_matrix* hidden_o, gsl_matrix* output_o, gsl_matrix* output_x, gsl_matrix* output_error, gsl_matrix* hidden_error, double* error);\nvoid store_weight(gsl_matrix* input_weight, gsl_matrix* hidden_weight);\nvoid load_weight(gsl_matrix* input_weight, gsl_matrix* hidden_weight);\nint recognize(gsl_matrix* better_input, gsl_matrix* input_weight, gsl_matrix* hidden_weight, gsl_matrix* hidden_x, gsl_matrix* hidden_o, gsl_matrix* output_x, gsl_matrix* output_o);\n\nint main(int argc, char **argv)\n{\n\tint label;\n\tdouble error;\n\tdouble error_acc = 0.0;\n\tchar* file_name;\n\tchar* mode;\n\tFILE* fp;\n\tint input_data[DATA_NUM_WITHOUT_LABEL];\n\tgsl_matrix* better_input;\n\tgsl_matrix* target;\n\tgsl_matrix* output_error = gsl_matrix_alloc(OUTPUT_NODE, 1);\n\tgsl_matrix* hidden_error = gsl_matrix_alloc(HIDDEN_NODE, 1);\n\tgsl_matrix* output_x = gsl_matrix_alloc(OUTPUT_NODE, 1);\n\tgsl_matrix* output_o = gsl_matrix_alloc(OUTPUT_NODE, 1);\n gsl_matrix* hidden_x = gsl_matrix_alloc(HIDDEN_NODE, 1);\n gsl_matrix* hidden_o = gsl_matrix_alloc(HIDDEN_NODE, 1);\n\tgsl_matrix* input_weight;\n\tgsl_matrix* hidden_weight;\n\n\tif(argc < 3){\n\t\tfprintf(stderr, \"Usage: %s [-t(raining), -r(cognizing), -e(poch)] [file_name]\\n\", argv[0]);\n\t\texit(EXIT_FAILURE);\n\t}else{\n\t\tmode = argv[1];\n\t\tfile_name = argv[2];\n\t}\n\n\tfp = openfile(file_name);\n\n\tif(!strcmp(mode, \"-t\")){\n\t\t//training\n\t\tinput_weight = init_weight(HIDDEN_NODE, DATA_NUM_WITHOUT_LABEL); // initiate the input-hidden weight\n \thidden_weight = init_weight(OUTPUT_NODE, HIDDEN_NODE); // initiate the hidden-output weight\n\n \tint training_times = 0;\n \tputs(\"Training started\\n\");\n for (int i = 0; i < EPOCH; i++){\n\n\t\t\tdo{\n\t\t\t\tread_parse(fp, input_data, &label, mode);\n\t\t\t\tbetter_input = scale_input(input_data);\n\t\t\t\ttarget = vectorize_target(label);\n\t\t\t\ttraining(better_input, target, input_weight, hidden_weight, hidden_x, hidden_o, output_o, output_x, output_error, hidden_error, &error);\n\t\t\t\ttraining_times++;\n error_acc += error;\n\n\t\t\t}while(training_times < TRAIN_SET_SIZE);\n\t\t\t\n\t\t\trewind(fp); // back to the start of the input file, start epoch\n\t\t\tif(i == 0){\n\t\t\t\tprintf(\"In the first training, Accumulative Error = %f\\n\", error_acc);\n\t\t\t\tputs(\"========Start Epoch=========\");\n\t\t\t}else{\n\t\t\t\tprintf(\"Epoch %d, Accumulative Error = %f\\n\", i, error_acc);\n\t\t\t}\n\t\t\terror_acc = 0.0;\n training_times = 0;\n\n }\n\t\t\n gsl_matrix_free(better_input), gsl_matrix_free(target), gsl_matrix_free(output_error), gsl_matrix_free(hidden_error), gsl_matrix_free(output_x), gsl_matrix_free(output_o);\n gsl_matrix_free(hidden_x), gsl_matrix_free(hidden_o);\n\n store_weight(input_weight, hidden_weight);\n puts(\"Training weight has been stored!\");\n gsl_matrix_free(input_weight), gsl_matrix_free(hidden_weight);\n\n\t}\n\t\n\n\tif(!strcmp(mode, \"-r\")){\n\t\tinput_weight = gsl_matrix_alloc(HIDDEN_NODE, DATA_NUM_WITHOUT_LABEL);\n\t\thidden_weight = gsl_matrix_alloc(OUTPUT_NODE, HIDDEN_NODE);\n\n\t\tload_weight(input_weight, hidden_weight);\n\n\t\tint test_times = 0;\n\t\tint wrong_times = 0;\n\t\tint anwser;\n\n\t\tdo{\n read_parse(fp, input_data, &label, mode);\n\t\t\tbetter_input = scale_input(input_data);\n\t\t\tanwser = recognize(better_input, input_weight, hidden_weight, hidden_x, hidden_o, output_x, output_o);\n\n\t\t\tprintf(\"Label: %d, Guess: %d\\n\", label, anwser);\n\n\t\t\tif(anwser != label) wrong_times++;\n\n\t\t\ttest_times++;\n\n\t\t}while(test_times < TEST_SET_SIZE);\n\t\tprintf(\"Performance: %2f\\n\", (1 - ((float)wrong_times/(float)test_times)) * 100);\n\t\tgsl_matrix_free(better_input), gsl_matrix_free(target), gsl_matrix_free(output_error), gsl_matrix_free(hidden_error), gsl_matrix_free(output_x), gsl_matrix_free(output_o);\n\t\tgsl_matrix_free(hidden_x), gsl_matrix_free(hidden_o);\n\t\tgsl_matrix_free(input_weight), gsl_matrix_free(hidden_weight);\n\n\t}\n fclose(fp);\n\t\treturn 0;\n}\n\nFILE* openfile(char* file_name)\n{\n\tFILE* fp;\n\tif(!(fp = fopen(file_name, \"r\")))\n\t\tfprintf(stderr, \"Can't open the file\\n\");\n\treturn fp;\n}\n\nvoid read_parse(FILE* fp, int input_data[], int* label, char* mode)\n{\n\tchar line[LINE_LEN];\n\tchar temp;\n\tint line_c = 0;\n\tint input_c = 0;\n\tchar* token;\n\n\twhile((temp = fgetc(fp)) != '\\n'){\n if(temp == EOF) break;\n line[line_c++] = temp;\n\t}\n line[line_c] = '\\0';\n line_c = 0;\n\tif(!strcmp(mode, \"-t\")){\n\t\ttoken = strtok(line, \",\");\n\t\t*label = atoi(token);\n\t\twhile(token != NULL){\n\t\t\ttoken = strtok(NULL, \",\");\n\t\t\tif(token == NULL) break;\n\t\t\tinput_data[input_c++] = atoi(token);\n\t\t}\n\n\t}\n\tif(!strcmp(mode, \"-r\")){\n\t\ttoken = strtok(line, \",\");\n\t\t*label = atoi(token);\n\t\twhile(token != NULL){\n\t\t\ttoken = strtok(NULL, \",\");\n\t\t\tif(token == NULL) break;\n\t\t\tinput_data[input_c++] = atoi(token);\n\t\t}\n\t}\n}\n\ngsl_matrix* scale_input(int input_data[])\n{\n gsl_matrix* better_input = gsl_matrix_alloc(DATA_NUM_WITHOUT_LABEL, 1);\n\tfor(int i = 0; i < DATA_NUM_WITHOUT_LABEL; i++){\n\t\tgsl_matrix_set(better_input, i, 0, ((double)input_data[i]/255.0*0.99)+0.01);\n\t}\n return better_input;\n}\n\ngsl_matrix* vectorize_target(int label)\n{\n\tgsl_matrix* target = gsl_matrix_alloc(10, 1);\n\n\tfor(int i = 0; i < 10; i++){\n\t\tif(i == label){\n\t\t\tgsl_matrix_set(target, i, 0, 0.99);\n\t\t}else{\n\t\t\tgsl_matrix_set(target, i, 0, 0.01);\n\t\t}\n\t}\n\n\treturn target;\n}\n\ngsl_matrix* init_weight(int row, int col)\n{\n gsl_matrix* input_weight = gsl_matrix_alloc(row, col);\n\n const gsl_rng_type * T;\n gsl_rng * r;\n double sigma = NOR_DIS_DEV(col);\n r = gsl_rng_alloc (gsl_rng_mt19937);\n for(int i = 0; i < row; i++){\n\n for(int j = 0; j < col; j++){\n gsl_matrix_set(input_weight, i, j, gsl_ran_gaussian(r, sigma));\n }\n }\n gsl_rng_free(r);\n return input_weight;\n}\n\ndouble get_output_error(gsl_matrix* target, gsl_matrix* output, gsl_matrix* output_error)\n{\n\tdouble error = 0.0;\n\tfor (int i = 0; i < OUTPUT_NODE; i++){\n\t\tgsl_matrix_set(output_error, i, 0, (gsl_matrix_get(target, i, 0) - gsl_matrix_get(output, i, 0)));\n\t}\n\n\tfor (int i = 0; i < OUTPUT_NODE; i++){\n\t\terror += pow(gsl_matrix_get(output_error, i, 0), 2);\n\t}\n\n\treturn error;\n}\n\nvoid training(gsl_matrix* better_input, gsl_matrix* target, gsl_matrix* input_weight, gsl_matrix* hidden_weight, gsl_matrix* hidden_x, gsl_matrix* hidden_o, gsl_matrix* output_o, gsl_matrix* output_x, gsl_matrix* output_error, gsl_matrix* hidden_error, double* error)\n{\n\tgsl_matrix* delta_hidden_weight = gsl_matrix_alloc(OUTPUT_NODE, HIDDEN_NODE);\n\tgsl_matrix* delta_input_weight = gsl_matrix_alloc(HIDDEN_NODE, DATA_NUM_WITHOUT_LABEL);\n\tgsl_matrix* temp_hidden = gsl_matrix_alloc(OUTPUT_NODE, 1);\n\tgsl_matrix* temp_input = gsl_matrix_alloc(HIDDEN_NODE, 1);\n\n\t gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, input_weight, better_input, 0.0, hidden_x); // X = W*I\n\t for(int i = 0; i < HIDDEN_NODE; i++){\n\t \tgsl_matrix_set(hidden_o, i, 0, SIGMOID(gsl_matrix_get(hidden_x, i, 0)));\n\t }\n\n\t gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, hidden_weight, hidden_o, 0.0, output_x);\n\t for(int i = 0; i < OUTPUT_NODE; i++){\n\t \tgsl_matrix_set(output_o, i, 0, SIGMOID(gsl_matrix_get(output_x, i, 0)));\n\t }\n\n\t *error = get_output_error(target, output_o, output_error);\n\t gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, hidden_weight, output_error, 0.0, hidden_error); // Error hidden\n\n\t for(int i = 0; i < OUTPUT_NODE; i++){\n\t \tgsl_matrix_set(temp_hidden, i, 0, (LEARN_RATE * gsl_matrix_get(output_error, i, 0) * gsl_matrix_get(output_o, i, 0) * (1.0 - gsl_matrix_get(output_o, i, 0))));\n\t }\n\t gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, temp_hidden, hidden_o, 0.0, delta_hidden_weight);\n\n\t for(int i = 0; i < HIDDEN_NODE; i++){\n\t \tgsl_matrix_set(temp_input, i, 0, (LEARN_RATE * gsl_matrix_get(hidden_error, i, 0) * gsl_matrix_get(hidden_o, i, 0) * (1.0 - gsl_matrix_get(hidden_error, i, 0))));\n\t }\n\t gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, temp_input, better_input, 0.0, delta_input_weight);\n\n\t gsl_matrix_add(hidden_weight, delta_hidden_weight);\n\t gsl_matrix_add(input_weight, delta_input_weight);\n\n\n\t gsl_matrix_free(delta_input_weight);\n\t gsl_matrix_free(delta_hidden_weight);\n\t gsl_matrix_free(temp_input);\n\t gsl_matrix_free(temp_hidden);\n\n}\n\nvoid store_weight(gsl_matrix* input_weight, gsl_matrix* hidden_weight)\n{\n\tFILE* fp = fopen(\"Good_Weight\", \"w+\");\n\n\tfor(int i = 0; i < HIDDEN_NODE; i++){\n\t\tfor(int j = 0; j < DATA_NUM_WITHOUT_LABEL; j++){\n\n\t\t\tfprintf(fp, \"%f,\", gsl_matrix_get(input_weight, i, j));\n\t\t}\n\t}\n\n\tfseek(fp, -1, SEEK_CUR);\n\tfputc('\\n', fp);\n\n\tfor(int i = 0; i < OUTPUT_NODE; i++){\n\t\tfor(int j = 0; j < HIDDEN_NODE; j++){\n\n\t\t\tfprintf(fp, \"%f,\", gsl_matrix_get(hidden_weight, i, j));\n\t\t}\n\t}\n\tfseek(fp, -1, SEEK_CUR);\n\tfputc('\\n', fp);\n\n\tfclose(fp);\n}\n\nvoid load_weight(gsl_matrix* input_weight, gsl_matrix* hidden_weight)\n{\n\tFILE* fp = fopen(\"Good_Weight\", \"r\");\n\tchar num_temp[20];\n\tdouble array[HIDDEN_NODE*DATA_NUM_WITHOUT_LABEL];\n\tchar c;\n\tint j = 0, k;\n\n\tif(fp == NULL){\n\t\tfprintf(stderr, \"No Good_Weight here, Please training first\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\twhile((c = fgetc(fp)) != '\\n'){\n\n\t\tif(c == ','){\n\t\t\tk = 0;\n\t\t\tarray[j++] = atof(num_temp);\n\t\t\tbzero(num_temp, sizeof(num_temp));\n\t\t\tcontinue;\n\t\t}\n\t\tnum_temp[k++] = c;\n\t}\n\n\tarray[j] = atof(num_temp);\n\n\tj = 0;\n\n\tfor(int n = 0; n < HIDDEN_NODE; n++){\n\t\tfor(int m = 0; m < DATA_NUM_WITHOUT_LABEL; m++){\n\t\t\tgsl_matrix_set(input_weight, n, m, array[j++]);\n\t\t}\n\t}\n\n\tj = 0;\n\tk = 0;\n\twhile((c = fgetc(fp)) != '\\n'){\n\n\t\tif(c == ','){\n\t\t\tk = 0;\n\t\t\tarray[j++] = atof(num_temp);\n\t\t\tbzero(num_temp, sizeof(num_temp));\n\t\t\tcontinue;\n\t\t}\n\t\tnum_temp[k++] = c;\n\t}\n\n\tarray[j] = atof(num_temp);\n\n\tj = 0;\n\n\tfor(int n = 0; n < OUTPUT_NODE; n++){\n\t\tfor(int m = 0; m < HIDDEN_NODE; m++){\n\t\t\tgsl_matrix_set(hidden_weight, n, m, array[j++]);\n\t\t}\n\t}\n\n\tfclose(fp);\n}\n\nint recognize(gsl_matrix* better_input, gsl_matrix* input_weight, gsl_matrix* hidden_weight, gsl_matrix* hidden_x, gsl_matrix* hidden_o, gsl_matrix* output_x, gsl_matrix* output_o)\n{\n\tsize_t row, col;\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, input_weight, better_input, 0.0, hidden_x); // X = W*I\n\t for(int i = 0; i < HIDDEN_NODE; i++){\n\t \tgsl_matrix_set(hidden_o, i, 0, SIGMOID(gsl_matrix_get(hidden_x, i, 0)));\n\t }\n\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, hidden_weight, hidden_o, 0.0, output_x);\n\t for(int i = 0; i < OUTPUT_NODE; i++){\n\t \tgsl_matrix_set(output_o, i, 0, SIGMOID(gsl_matrix_get(output_x, i, 0)));\n\t }\n\n\t gsl_matrix_max_index(output_o, &row, &col);\n\n\t return (int)row;\n}\n", "meta": {"hexsha": "383408d22bc1028a7d480ffe9283a15dbfaa90c2", "size": 11696, "ext": "c", "lang": "C", "max_stars_repo_path": "num_r.c", "max_stars_repo_name": "lochuan/number_recognization", "max_stars_repo_head_hexsha": "66a5faefb1e4d74e35cccdf6711e4b9fad48686e", "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": "num_r.c", "max_issues_repo_name": "lochuan/number_recognization", "max_issues_repo_head_hexsha": "66a5faefb1e4d74e35cccdf6711e4b9fad48686e", "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": "num_r.c", "max_forks_repo_name": "lochuan/number_recognization", "max_forks_repo_head_hexsha": "66a5faefb1e4d74e35cccdf6711e4b9fad48686e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6178010471, "max_line_length": 268, "alphanum_fraction": 0.6895519836, "num_tokens": 3467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.584718208708442}} {"text": "#include \n#include \n\n#include \n#include \n#include \n\nint\nmain()\n{\n const gsl_interp2d_type *T = gsl_interp2d_bilinear;\n const size_t N = 100; /* number of points to interpolate */\n const double xa[] = { 0.0, 1.0 }; /* define unit square */\n const double ya[] = { 0.0, 1.0 };\n const size_t nx = sizeof(xa) / sizeof(double); /* x grid points */\n const size_t ny = sizeof(ya) / sizeof(double); /* y grid points */\n double *za = malloc(nx * ny * sizeof(double));\n gsl_spline2d *spline = gsl_spline2d_alloc(T, nx, ny);\n gsl_interp_accel *xacc = gsl_interp_accel_alloc();\n gsl_interp_accel *yacc = gsl_interp_accel_alloc();\n size_t i, j;\n\n /* set z grid values */\n gsl_spline2d_set(spline, za, 0, 0, 0.0);\n gsl_spline2d_set(spline, za, 0, 1, 1.0);\n gsl_spline2d_set(spline, za, 1, 1, 0.5);\n gsl_spline2d_set(spline, za, 1, 0, 1.0);\n\n /* initialize interpolation */\n gsl_spline2d_init(spline, xa, ya, za, nx, ny);\n\n /* interpolate N values in x and y and print out grid for plotting */\n for (i = 0; i < N; ++i)\n {\n double xi = i / (N - 1.0);\n\n for (j = 0; j < N; ++j)\n {\n double yj = j / (N - 1.0);\n double zij = gsl_spline2d_eval(spline, xi, yj, xacc, yacc);\n\n printf(\"%f %f %f\\n\", xi, yj, zij);\n }\n printf(\"\\n\");\n }\n\n gsl_spline2d_free(spline);\n gsl_interp_accel_free(xacc);\n gsl_interp_accel_free(yacc);\n free(za);\n\n return 0;\n}\n", "meta": {"hexsha": "3777c1075ced82acae519a34ce2b120898af1e4b", "size": 1498, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/interp2d.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/interp2d.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/interp2d.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.7407407407, "max_line_length": 73, "alphanum_fraction": 0.6094793057, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5845392735052091}} {"text": "#include \n#include \n#include \n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n//PowerSphericalPotentialwCutoff\n//3 arguments: amp, alpha, rc\ndouble mass(double r2,double alpha, double rc){\n return 2. * M_PI * pow ( rc , 3. - alpha ) * ( gsl_sf_gamma ( 1.5 - 0.5 * alpha ) - gsl_sf_gamma_inc ( 1.5 - 0.5 * alpha , r2 / rc / rc ) );\n}\ndouble PowerSphericalPotentialwCutoffEval(double R,double Z, double phi,\n\t\t\t\t\t double t,\n\t\t\t\t\t struct potentialArg * potentialArgs){\n double * args= potentialArgs->args;\n //Get args\n double amp= *args++;\n double alpha= *args++;\n double rc= *args;\n //Radius\n double r2= R*R+Z*Z;\n double r= sqrt(r2);\n return amp * 2. * M_PI * pow(rc,3.-alpha) / r * ( r / rc * ( gsl_sf_gamma ( 1. - 0.5 * alpha ) - gsl_sf_gamma_inc ( 1. - 0.5 * alpha , r2 / rc / rc ) ) - ( gsl_sf_gamma ( 1.5 - 0.5 * alpha ) - gsl_sf_gamma_inc ( 1.5 - 0.5 * alpha , r2 / rc / rc) ) );\n}\ndouble PowerSphericalPotentialwCutoffRforce(double R,double Z, double phi,\n\t\t\t\t\t double t,\n\t\t\t\t\t struct potentialArg * potentialArgs){\n double * args= potentialArgs->args;\n //Get args\n double amp= *args++;\n double alpha= *args++;\n double rc= *args;\n //Radius\n double r2= R*R+Z*Z;\n //Calculate Rforce\n return - amp * mass (r2,alpha,rc) * R / pow(r2,1.5);\n}\ndouble PowerSphericalPotentialwCutoffPlanarRforce(double R,double phi,\n\t\t\t\t\t\t double t,\n\t\t\t\t\t\t struct potentialArg * potentialArgs){\n double * args= potentialArgs->args;\n //Get args\n double amp= *args++;\n double alpha= *args++;\n double rc= *args;\n //Radius\n double r2= R*R;\n //Calculate Rforce\n return - amp * mass (r2,alpha,rc) / r2;\n}\ndouble PowerSphericalPotentialwCutoffzforce(double R,double Z,double phi,\n\t\t\t\t\t double t,\n\t\t\t\t\t struct potentialArg * potentialArgs){\n double * args= potentialArgs->args;\n //Get args\n double amp= *args++;\n double alpha= *args++;\n double rc= *args;\n //Radius\n double r2= R*R+Z*Z;\n //Calculate Rforce\n return - amp * mass (r2,alpha,rc) * Z / pow(r2,1.5);\n}\ndouble PowerSphericalPotentialwCutoffPlanarR2deriv(double R,double phi,\n\t\t\t\t\t\t double t,\n\t\t\t\t\t\t struct potentialArg * potentialArgs){\n double * args= potentialArgs->args;\n //Get args\n double amp= *args++;\n double alpha= *args++;\n double rc= *args;\n //Radius\n double r2= R*R;\n //Calculate R2deriv\n return amp * ( 4. * M_PI * pow(r2,- 0.5 * alpha) * exp(-r2/rc/rc) - 2. * mass(r2,alpha,rc)/pow(r2,1.5) );\n}\n", "meta": {"hexsha": "bde397ba7c46536f49201f62750d49f9567aefe6", "size": 2462, "ext": "c", "lang": "C", "max_stars_repo_path": "galpy/potential/potential_c_ext/PowerSphericalPotentialwCutoff.c", "max_stars_repo_name": "turnergarrow/galpy", "max_stars_repo_head_hexsha": "7132eddbf2dab491fe137790e31eacdc604b0534", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-28T08:54:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-28T08:54:38.000Z", "max_issues_repo_path": "galpy/potential/potential_c_ext/PowerSphericalPotentialwCutoff.c", "max_issues_repo_name": "BurcuAkbulut/galpy", "max_issues_repo_head_hexsha": "cabb42bef3b4f88a2f593cdb123452cd41451db3", "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": "galpy/potential/potential_c_ext/PowerSphericalPotentialwCutoff.c", "max_forks_repo_name": "BurcuAkbulut/galpy", "max_forks_repo_head_hexsha": "cabb42bef3b4f88a2f593cdb123452cd41451db3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-30T06:14:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T06:14:31.000Z", "avg_line_length": 31.974025974, "max_line_length": 252, "alphanum_fraction": 0.6413484972, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5843500376943401}} {"text": "/* gsl_sf_hermite.h\r\n * \r\n * Copyright (C) 2011-2014 Konrad Griessinger\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/*----------------------------------------------------------------------*\r\n * (konradg(at)gmx.net) *\r\n *----------------------------------------------------------------------*/\r\n\r\n#ifndef __GSL_SF_HERMITE_H__\r\n#define __GSL_SF_HERMITE_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\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\nGSL_FUN int gsl_sf_hermite_prob_e(const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_prob(const int n, const double x);\r\nGSL_FUN int gsl_sf_hermite_prob_deriv_e(const int m, const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_prob_deriv(const int m, const int n, const double x);\r\nGSL_FUN int gsl_sf_hermite_e(const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite(const int n, const double x);\r\nGSL_FUN int gsl_sf_hermite_deriv_e(const int m, const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_deriv(const int m, const int n, const double x);\r\nGSL_FUN int gsl_sf_hermite_func_e(const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_func(const int n, const double x);\r\nGSL_FUN int gsl_sf_hermite_func_fast_e(const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_func_fast(const int n, const double x);\r\nGSL_FUN int gsl_sf_hermite_prob_array(const int nmax, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_prob_array_deriv(const int m, const int nmax, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_prob_deriv_array(const int mmax, const int n, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_prob_series_e(const int n, const double x, const double * a, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_prob_series(const int n, const double x, const double * a);\r\nGSL_FUN int gsl_sf_hermite_array(const int nmax, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_array_deriv(const int m, const int nmax, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_deriv_array(const int mmax, const int n, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_series_e(const int n, const double x, const double * a, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_series(const int n, const double x, const double * a);\r\nGSL_FUN int gsl_sf_hermite_func_array(const int nmax, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_func_series_e(const int n, const double x, const double * a, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_func_series(const int n, const double x, const double * a);\r\nGSL_FUN int gsl_sf_hermite_func_der_e(const int m, const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_func_der(const int m, const int n, const double x);\r\nGSL_FUN int gsl_sf_hermite_prob_zero_e(const int n, const int s, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_prob_zero(const int n, const int s);\r\nGSL_FUN int gsl_sf_hermite_zero_e(const int n, const int s, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_zero(const int n, const int s);\r\nGSL_FUN int gsl_sf_hermite_func_zero_e(const int n, const int s, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_func_zero(const int n, const int s);\r\n\r\n#ifndef GSL_DISABLE_DEPRECATED\r\n\r\nGSL_FUN int gsl_sf_hermite_phys_e(const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_phys(const int n, const double x);\r\nGSL_FUN int gsl_sf_hermite_phys_der_e(const int m, const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_phys_der(const int m, const int n, const double x);\r\nGSL_FUN int gsl_sf_hermite_phys_array(const int nmax, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_phys_series_e(const int n, const double x, const double * a, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_phys_series(const int n, const double x, const double * a);\r\nGSL_FUN int gsl_sf_hermite_phys_array_der(const int m, const int nmax, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_phys_der_array(const int mmax, const int n, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_phys_zero_e(const int n, const int s, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_phys_zero(const int n, const int s);\r\n\r\nGSL_FUN int gsl_sf_hermite_prob_array_der(const int m, const int nmax, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_prob_der_array(const int mmax, const int n, const double x, double * result_array);\r\nGSL_FUN int gsl_sf_hermite_prob_der_e(const int m, const int n, const double x, gsl_sf_result * result);\r\nGSL_FUN double gsl_sf_hermite_prob_der(const int m, const int n, const double x);\r\n\r\n#endif /* !GSL_DISABLE_DEPRECATED */\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_SF_HERMITE_H__ */\r\n", "meta": {"hexsha": "61c652fe1c87fe24fa82733c2c70a4de2e33c4ea", "size": 6165, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_sf_hermite.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_hermite.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_hermite.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": 56.5596330275, "max_line_length": 113, "alphanum_fraction": 0.7510137875, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924953, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5842155603982904}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#define USAGE \"./mcmc_loktavolterra.x n_steps n_burn\"\n\nvoid rg4th(float *resultado, float x, float y, float a, float b, float c, float d, float h);\nvoid x_prime(float *valor, float x, float y, float alpha, float beta);\nvoid y_prime(float *valor, float x, float y, float gamma, float delta);\n\nvoid my_model(float *mine_presas,float *mine_depredadores,float *tiempo,float ini_presas, float ini_depredadores,float a, float b, float c, float d, int n_puntos);\nvoid likelihood(float *chi,float *presas,float *depredadores,float *mine_presas,float *mine_depredadores,int n_puntos);\nvoid mcmc(int n_steps,float *a,float *b,float *c,float *d,float *l,float *tiempo,float *presas,float *depredadores,int n_puntos,float *mine_presas,float *mine_depredadores, float ini_presas, float ini_depredadores);\nvoid min(float *mine_presas,float *mine_depredadores,float ini_presas,float ini_depredadores,float *tiempo,float *a,float *b,float *c,float *d,float *l,int n_steps,int n_puntos);\n\nvoid leer(float *tiempo, float *presas, float *depredadores, int n_puntos);\nfloat *reserva(int n_puntos);\nvoid print_array(float *a, float *b, float *c, float *d , float *l, int n_steps, int n_burn);\n\nint main(int argc, char **argv){\n\t\n\tsrand48(time(NULL));\n\t\n\t//Valores que entran\n\tint n_steps=atof(argv[1]);\n\tint n_burn=atof(argv[2]);\n\t//Inicializacion de los arrays que guardan los datos\n\tint n_puntos= 96;\n\tfloat *tiempo;\n\tfloat *presas;\n\tfloat *depredadores;\n\ttiempo=reserva(n_puntos);\n\tpresas=reserva(n_puntos);\n\tdepredadores=reserva(n_puntos);\n\t\n\tleer(tiempo, presas, depredadores, n_puntos);\n\t//Condiciones iniciales para resolver las ecuaciones diferenciales\n\tfloat ini_presas, ini_depredadores;\n\tini_presas=presas[0];\n\tini_depredadores=depredadores[0];\n\t\n\t//Array con los resultados del ajuste\n\tfloat *mine_presas;\n\tmine_presas=reserva(n_puntos);\n\tfloat *mine_depredadores;\n\tmine_depredadores=reserva(n_puntos);\n\t\n\t//Arrays que guardan los datos de las variables\n\tfloat *a; //alpha\n\tfloat *b; //beta\n\tfloat *c; //gamma\n\tfloat *d; //delta\n\tfloat *l;\n\ta=reserva(n_steps);\n\tb=reserva(n_steps);\n\tc=reserva(n_steps);\n\td=reserva(n_steps);\n\tl=reserva(n_steps);\n\t//Primer paso en la cadena\n\ta[0]=drand48();\n\tb[0]=drand48();\n\tc[0]=drand48();\n\td[0]=drand48();\n\tfloat chi;\n\tmy_model(mine_presas,mine_depredadores,tiempo,ini_presas,ini_depredadores,a[0],b[0],c[0],d[0],n_puntos);\n\tlikelihood(&chi,presas,depredadores,mine_presas,mine_depredadores,n_puntos);\n\tl[0]=chi;\n\t\n\tmcmc(n_steps,a,b,c,d,l,tiempo,presas,depredadores,n_puntos,mine_presas,mine_depredadores,ini_presas,ini_depredadores);\n\tmin(mine_presas,mine_depredadores,ini_presas,ini_depredadores,tiempo,a,b,c,d,l,n_steps,n_puntos);\n\n\tprint_array(a,b,c,d,l,n_steps,n_burn);\n\t\n\tfree(tiempo);\n\tfree(presas);\n\tfree(mine_presas);\n\tfree(depredadores);\n\tfree(mine_depredadores);\n\tfree(a);\n\tfree(b);\n\tfree(c);\n\tfree(d);\n\t\n\treturn 0;\n}\n\n//OBTENCION DEL MEJOR AJUSTE\nvoid min(float *mine_presas,float *mine_depredadores,float ini_presas,float ini_depredadores,float *tiempo,float *a,float *b,float *c,float *d,float *l,int n_steps,int n_puntos){\n\tint i;\n\tfloat temp, a2, b2, c2, d2;\n\ttemp=l[0];\n\ta2=a[0];\n\tb2=b[0];\n\tc2=c[0];\n\td2=d[0];\n\tfor(i=1;i l[i] ){\n\t\t\ttemp=l[i];\n\t\t\ta2=a[i];\n\t\t\tb2=b[i];\n\t\t\tc2=c[i];\n\t\t\td2=d[i];\n\t\t}\n\t}\n\tmy_model(mine_presas,mine_depredadores,tiempo,ini_presas,ini_depredadores,a2,b2,c2,d2,n_puntos);\t\n}\n\n//ITERACIONES\nvoid mcmc(int n_steps,float *a,float *b,float *c,float *d,float *l,float *tiempo,float *presas,float *depredadores,int n_puntos,float *mine_presas,float *mine_depredadores, float ini_presas, float ini_depredadores){\n\tint i;\n\tfloat a2,b2,c2,d2,chi,chi2,alpha,beta;\n\tconst gsl_rng_type * T;\n\tgsl_rng * r;\n\tgsl_rng_env_setup();\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc (T);\n\t\n for(i=0;i<(n_steps-1);i++){\n\t\ta2 = a[i] + gsl_ran_gaussian(r, 0.1);\n\t\tb2 = b[i] + gsl_ran_gaussian(r, 0.1);\n\t\tc2 = c[i] + gsl_ran_gaussian(r, 0.1);\n\t\td2 = c[i] + gsl_ran_gaussian(r, 0.1);\n\t\t\n\t\tfloat *presas_init;\n\t\tfloat *presas_prime;\n\t\tpresas_init=reserva(n_puntos);\n\t\tpresas_prime=reserva(n_puntos);\n\t\tfloat *depredadores_init;\n\t\tfloat *depredadores_prime;\n\t\tdepredadores_init=reserva(n_puntos);\n\t\tdepredadores_prime=reserva(n_puntos);\n\t\t\n\t\tmy_model(presas_init,depredadores_init,tiempo,ini_presas,ini_depredadores,a[i],b[i],c[i],d[i],n_puntos);\n\t\tlikelihood(&chi,presas,depredadores,presas_init,depredadores_init,n_puntos);\n\t\t\n\t\tmy_model(presas_prime,depredadores_prime,tiempo,ini_presas,ini_depredadores,a2,b2,c2,d2,n_puntos);\n\t\tlikelihood(&chi2,presas,depredadores,presas_prime,depredadores_prime,n_puntos);\n\t\t\n\t\talpha = -chi2 + chi;\n\t\tif(alpha >= 0.0){\n\t\t\ta[i+1]=a2;\n\t\t\tb[i+1]=b2;\n\t\t\tc[i+1]=c2;\n\t\t\td[i+1]=d2;\n\t\t\tl[i+1]=chi2;\n\t\t}\n\t\telse{\n\t\t\tbeta = drand48();\n\t\t\tif(alpha < -6000.0 ){\n\t\t\t\ta[i+1]=a[i];\n\t\t\t\tb[i+1]=b[i];\n\t\t\t\tc[i+1]=c[i];\n\t\t\t\td[i+1]=d[i];\n\t\t\t\tl[i+1]=chi;\n\t\t\t}\n\t\t\telse if(beta <= exp(alpha)){\n\t\t\t\ta[i+1]=a2;\n\t\t\t\tb[i+1]=b2;\n\t\t\t\tc[i+1]=c2;\n\t\t\t\td[i+1]=d2;\n\t\t\t\tl[i+1]=chi2;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ta[i+1]=a[i];\n\t\t\t\tb[i+1]=b[i];\n\t\t\t\tc[i+1]=c[i];\n\t\t\t\td[i+1]=d[i];\n\t\t\t\tl[i+1]=chi;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfree(presas_init);\n\t\tfree(presas_prime);\n\t\tfree(depredadores_init);\n\t\tfree(depredadores_prime);\n\t}\n\n gsl_rng_free (r);\n}\n\n//IMPRESION DE LOS ARRAYS\nvoid print_array(float *a, float *b, float *c, float *d , float *l, int n_steps, int n_burn){\n int i;\n for(i=n_burn;i\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n\nstatic double logTimeBegin;\nstatic double logTimeMax;\n\n\ndouble drift_integ(double a, void *param)\n{\n double h;\n\n h = hubble_function(a);\n\n return 1 / (h * a * a * a);\n}\n\ndouble gravkick_integ(double a, void *param)\n{\n double h;\n\n h = hubble_function(a);\n\n return 1 / (h * a * a);\n}\n\n\ndouble hydrokick_integ(double a, void *param)\n{\n double h;\n\n h = hubble_function(a);\n\n return 1 / (h * pow(a, 3 * GAMMA_MINUS1) * a);\n}\n\ndouble growthfactor_integ(double a, void *param)\n{\n double s;\n\n s = hubble_function(a) / All.Hubble * sqrt(a * a * a);\n\n return pow(sqrt(a) / s, 3);\n}\n\n\nvoid init_drift_table(void)\n{\n#define WORKSIZE 100000\n int i;\n double result, abserr;\n\n /*---------- DEBUG ! ------------*/\n#ifdef DARKENERGY_DEBUG\n FILE *FdDKfac;\n char mode[2], buf[200];\n\n strcpy(mode, \"w\");\n sprintf(buf, \"%s%s\", All.OutputDir, \"driftkickfac.txt\");\n FdDKfac = fopen(buf, mode);\n fprintf(FdDKfac, \"i a drift GravKick HydroKick\\n\");\n /*---------- DEBUG ! ------------*/\n#endif\n\n gsl_function F;\n gsl_integration_workspace *workspace;\n\n logTimeBegin = log(All.TimeBegin);\n logTimeMax = log(All.TimeMax);\n\n workspace = gsl_integration_workspace_alloc(WORKSIZE);\n\n for(i = 0; i < DRIFT_TABLE_LENGTH; i++)\n {\n F.function = &drift_integ;\n gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), All.Hubble,\t/* note: absolute error just a dummy */\n\t\t\t 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);\n DriftTable[i] = result;\n\n\n F.function = &gravkick_integ;\n gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), All.Hubble,\t/* note: absolute error just a dummy */\n\t\t\t 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);\n GravKickTable[i] = result;\n\n\n F.function = &hydrokick_integ;\n gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), All.Hubble,\t/* note: absolute error just a dummy */\n\t\t\t 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);\n HydroKickTable[i] = result;\n\n#ifdef DARKENERGY_DEBUG\n /*---------- DEBUG ! ------------*/\n fprintf(FdDKfac, \"%d %e %e %e %e \\n\", i,\n\t exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), DriftTable[i],\n\t GravKickTable[i], HydroKickTable[i]);\n /*---------- DEBUG ! ------------*/\n#endif\n }\n\n gsl_integration_workspace_free(workspace);\n\n#ifdef DARKENERGY_DEBUG\n /*---------- DEBUG ! ------------*/\n fclose(FdDKfac);\n /*---------- DEBUG ! ------------*/\n#endif\n}\n\n\n/*! This function integrates the cosmological prefactor for a drift\n * step between time0 and time1. The value returned is\n * \\f[ \\int_{a_0}^{a_1} \\frac{{\\rm d}a}{H(a)}\n * \\f]\n * \n * A lookup-table is used for reasons of speed. \n */\ndouble get_drift_factor(int time0, int time1)\n{\n double a1, a2, df1, df2, u1, u2;\n int i1, i2;\n static int last_time0 = -1, last_time1 = -1;\n static double last_value;\n\n if(time0 == last_time0 && time1 == last_time1)\n return last_value;\n\n /* note: will only be called for cosmological integration */\n\n a1 = logTimeBegin + time0 * All.Timebase_interval;\n a2 = logTimeBegin + time1 * All.Timebase_interval;\n\n if(logTimeMax > logTimeBegin)\n u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n else\n u1 = 0;\n i1 = (int) u1;\n if(i1 >= DRIFT_TABLE_LENGTH)\n i1 = DRIFT_TABLE_LENGTH - 1;\n\n if(i1 <= 1)\n df1 = u1 * DriftTable[0];\n else\n df1 = DriftTable[i1 - 1] + (DriftTable[i1] - DriftTable[i1 - 1]) * (u1 - i1);\n\n if(logTimeMax > logTimeBegin)\n u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n else\n u2 = 0;\n i2 = (int) u2;\n if(i2 >= DRIFT_TABLE_LENGTH)\n i2 = DRIFT_TABLE_LENGTH - 1;\n\n if(i2 <= 1)\n df2 = u2 * DriftTable[0];\n else\n df2 = DriftTable[i2 - 1] + (DriftTable[i2] - DriftTable[i2 - 1]) * (u2 - i2);\n\n last_time0 = time0;\n last_time1 = time1;\n\n return last_value = (df2 - df1);\n}\n\n\ndouble get_gravkick_factor(int time0, int time1)\n{\n double a1, a2, df1, df2, u1, u2;\n int i1, i2;\n static int last_time0 = -1, last_time1 = -1;\n static double last_value;\n\n if(time0 == last_time0 && time1 == last_time1)\n return last_value;\n\n /* note: will only be called for cosmological integration */\n\n a1 = logTimeBegin + time0 * All.Timebase_interval;\n a2 = logTimeBegin + time1 * All.Timebase_interval;\n\n if(logTimeMax > logTimeBegin)\n u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n else\n u1 = 0;\n i1 = (int) u1;\n if(i1 >= DRIFT_TABLE_LENGTH)\n i1 = DRIFT_TABLE_LENGTH - 1;\n\n if(i1 <= 1)\n df1 = u1 * GravKickTable[0];\n else\n df1 = GravKickTable[i1 - 1] + (GravKickTable[i1] - GravKickTable[i1 - 1]) * (u1 - i1);\n\n if(logTimeMax > logTimeBegin)\n u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n else\n u2 = 0;\n i2 = (int) u2;\n if(i2 >= DRIFT_TABLE_LENGTH)\n i2 = DRIFT_TABLE_LENGTH - 1;\n\n if(i2 <= 1)\n df2 = u2 * GravKickTable[0];\n else\n df2 = GravKickTable[i2 - 1] + (GravKickTable[i2] - GravKickTable[i2 - 1]) * (u2 - i2);\n\n last_time0 = time0;\n last_time1 = time1;\n\n return last_value = (df2 - df1);\n}\n\ndouble get_hydrokick_factor(int time0, int time1)\n{\n double a1, a2, df1, df2, u1, u2;\n int i1, i2;\n static int last_time0 = -1, last_time1 = -1;\n static double last_value;\n\n if(time0 == last_time0 && time1 == last_time1)\n return last_value;\n\n /* note: will only be called for cosmological integration */\n\n a1 = logTimeBegin + time0 * All.Timebase_interval;\n a2 = logTimeBegin + time1 * All.Timebase_interval;\n\n if(logTimeMax > logTimeBegin)\n u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n else\n u1 = 0;\n i1 = (int) u1;\n if(i1 >= DRIFT_TABLE_LENGTH)\n i1 = DRIFT_TABLE_LENGTH - 1;\n\n if(i1 <= 1)\n df1 = u1 * HydroKickTable[0];\n else\n df1 = HydroKickTable[i1 - 1] + (HydroKickTable[i1] - HydroKickTable[i1 - 1]) * (u1 - i1);\n\n if(logTimeMax > logTimeBegin)\n u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n else\n u2 = 0;\n i2 = (int) u2;\n if(i2 >= DRIFT_TABLE_LENGTH)\n i2 = DRIFT_TABLE_LENGTH - 1;\n\n if(i2 <= 1)\n df2 = u2 * HydroKickTable[0];\n else\n df2 = HydroKickTable[i2 - 1] + (HydroKickTable[i2] - HydroKickTable[i2 - 1]) * (u2 - i2);\n\n last_time0 = time0;\n last_time1 = time1;\n\n return last_value = (df2 - df1);\n}\n", "meta": {"hexsha": "9ea74830b81172dfab9bbf31ca27fe52b29480a5", "size": 6772, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/driftfac.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/driftfac.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/driftfac.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3632958801, "max_line_length": 182, "alphanum_fraction": 0.6343768458, "num_tokens": 2290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5841510152614787}} {"text": "/* randist/binomial.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n/* The binomial distribution has the form,\n\n prob(k) = n!/(k!(n-k)!) * p^k (1-p)^(n-k) for k = 0, 1, ..., n\n\n This is the algorithm from Knuth */\n\nunsigned int\ngsl_ran_binomial (const gsl_rng * r, double p, unsigned int n)\n{\n unsigned int i, a, b, k = 0;\n\n while (n > 10)\t/* This parameter is tunable */\n {\n double X;\n a = 1 + (n / 2);\n b = 1 + n - a;\n\n X = gsl_ran_beta (r, (double) a, (double) b);\n\n if (X >= p)\n\t{\n\t n = a - 1;\n\t p /= X;\n\t}\n else\n\t{\n\t k += a;\n\t n = b - 1;\n\t p = (p - X) / (1 - X);\n\t}\n }\n\n for (i = 0; i < n; i++)\n {\n double u = gsl_rng_uniform (r);\n if (u < p)\n\tk++;\n }\n\n return k;\n}\n\ndouble\ngsl_ran_binomial_pdf (const unsigned int k, const double p, \n\t\t const unsigned int n)\n{\n if (k > n)\n {\n return 0 ;\n }\n else \n {\n double a = k;\n double b = n - k;\n double P;\n double Cnk = gsl_sf_choose (n, k) ;\n\n P = Cnk * pow (p, a) * pow (1 - p, b);\n \n return P;\n }\n}\n", "meta": {"hexsha": "23dea82af3b18c839b7327bedd7892e9c1dfb8a3", "size": 1936, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/randist/binomial.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/randist/binomial.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/randist/binomial.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.0, "max_line_length": 72, "alphanum_fraction": 0.5867768595, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658109754052, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5841081597353273}} {"text": "/* cdf/gsl_cdf.h\n * \n * Copyright (C) 2002 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/* Author: J. Stover */\n\n#ifndef __GSL_CDF_H__\n#define __GSL_CDF_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\nGSL_EXPORT double gsl_cdf_ugaussian_P (const double x);\nGSL_EXPORT double gsl_cdf_ugaussian_Q (const double x);\n\nGSL_EXPORT double gsl_cdf_ugaussian_Pinv (const double P);\nGSL_EXPORT double gsl_cdf_ugaussian_Qinv (const double Q);\n\nGSL_EXPORT double gsl_cdf_gaussian_P (const double x, const double sigma);\nGSL_EXPORT double gsl_cdf_gaussian_Q (const double x, const double sigma);\n\nGSL_EXPORT double gsl_cdf_gaussian_Pinv (const double P, const double sigma);\nGSL_EXPORT double gsl_cdf_gaussian_Qinv (const double Q, const double sigma);\n\nGSL_EXPORT double gsl_cdf_gamma_P (const double x, const double a, const double b);\nGSL_EXPORT double gsl_cdf_gamma_Q (const double x, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_gamma_Pinv (const double P, const double a, const double b);\nGSL_EXPORT double gsl_cdf_gamma_Qinv (const double Q, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_cauchy_P (const double x, const double a);\nGSL_EXPORT double gsl_cdf_cauchy_Q (const double x, const double a);\n\nGSL_EXPORT double gsl_cdf_cauchy_Pinv (const double P, const double a);\nGSL_EXPORT double gsl_cdf_cauchy_Qinv (const double Q, const double a);\n\nGSL_EXPORT double gsl_cdf_laplace_P (const double x, const double a);\nGSL_EXPORT double gsl_cdf_laplace_Q (const double x, const double a);\n\nGSL_EXPORT double gsl_cdf_laplace_Pinv (const double P, const double a);\nGSL_EXPORT double gsl_cdf_laplace_Qinv (const double Q, const double a);\n\nGSL_EXPORT double gsl_cdf_rayleigh_P (const double x, const double sigma);\nGSL_EXPORT double gsl_cdf_rayleigh_Q (const double x, const double sigma);\n\nGSL_EXPORT double gsl_cdf_rayleigh_Pinv (const double P, const double sigma);\nGSL_EXPORT double gsl_cdf_rayleigh_Qinv (const double Q, const double sigma);\n\nGSL_EXPORT double gsl_cdf_chisq_P (const double x, const double nu);\nGSL_EXPORT double gsl_cdf_chisq_Q (const double x, const double nu);\n\nGSL_EXPORT double gsl_cdf_chisq_Pinv (const double P, const double nu);\nGSL_EXPORT double gsl_cdf_chisq_Qinv (const double Q, const double nu);\n\nGSL_EXPORT double gsl_cdf_exponential_P (const double x, const double mu);\nGSL_EXPORT double gsl_cdf_exponential_Q (const double x, const double mu);\n\nGSL_EXPORT double gsl_cdf_exponential_Pinv (const double P, const double mu);\nGSL_EXPORT double gsl_cdf_exponential_Qinv (const double Q, const double mu);\n\nGSL_EXPORT double gsl_cdf_exppow_P (const double x, const double a, const double b);\nGSL_EXPORT double gsl_cdf_exppow_Q (const double x, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_tdist_P (const double x, const double nu);\nGSL_EXPORT double gsl_cdf_tdist_Q (const double x, const double nu);\n\nGSL_EXPORT double gsl_cdf_tdist_Pinv (const double P, const double nu);\nGSL_EXPORT double gsl_cdf_tdist_Qinv (const double Q, const double nu);\n\nGSL_EXPORT double gsl_cdf_fdist_P (const double x, const double nu1, const double nu2);\nGSL_EXPORT double gsl_cdf_fdist_Q (const double x, const double nu1, const double nu2);\n\nGSL_EXPORT double gsl_cdf_fdist_Pinv (const double P, const double nu1, const double nu2);\nGSL_EXPORT double gsl_cdf_fdist_Qinv (const double Q, const double nu1, const double nu2);\n\nGSL_EXPORT double gsl_cdf_beta_P (const double x, const double a, const double b);\nGSL_EXPORT double gsl_cdf_beta_Q (const double x, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_beta_Pinv (const double P, const double a, const double b);\nGSL_EXPORT double gsl_cdf_beta_Qinv (const double Q, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_flat_P (const double x, const double a, const double b);\nGSL_EXPORT double gsl_cdf_flat_Q (const double x, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_flat_Pinv (const double P, const double a, const double b);\nGSL_EXPORT double gsl_cdf_flat_Qinv (const double Q, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_lognormal_P (const double x, const double zeta, const double sigma);\nGSL_EXPORT double gsl_cdf_lognormal_Q (const double x, const double zeta, const double sigma);\n\nGSL_EXPORT double gsl_cdf_lognormal_Pinv (const double P, const double zeta, const double sigma);\nGSL_EXPORT double gsl_cdf_lognormal_Qinv (const double Q, const double zeta, const double sigma);\n\nGSL_EXPORT double gsl_cdf_gumbel1_P (const double x, const double a, const double b);\nGSL_EXPORT double gsl_cdf_gumbel1_Q (const double x, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_gumbel1_Pinv (const double P, const double a, const double b);\nGSL_EXPORT double gsl_cdf_gumbel1_Qinv (const double Q, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_gumbel2_P (const double x, const double a, const double b);\nGSL_EXPORT double gsl_cdf_gumbel2_Q (const double x, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_gumbel2_Pinv (const double P, const double a, const double b);\nGSL_EXPORT double gsl_cdf_gumbel2_Qinv (const double Q, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_weibull_P (const double x, const double a, const double b);\nGSL_EXPORT double gsl_cdf_weibull_Q (const double x, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_weibull_Pinv (const double P, const double a, const double b);\nGSL_EXPORT double gsl_cdf_weibull_Qinv (const double Q, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_pareto_P (const double x, const double a, const double b);\nGSL_EXPORT double gsl_cdf_pareto_Q (const double x, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_pareto_Pinv (const double P, const double a, const double b);\nGSL_EXPORT double gsl_cdf_pareto_Qinv (const double Q, const double a, const double b);\n\nGSL_EXPORT double gsl_cdf_logistic_P (const double x, const double a);\nGSL_EXPORT double gsl_cdf_logistic_Q (const double x, const double a);\n\nGSL_EXPORT double gsl_cdf_logistic_Pinv (const double P, const double a);\nGSL_EXPORT double gsl_cdf_logistic_Qinv (const double Q, const double a);\n\nGSL_EXPORT double gsl_cdf_binomial_P (const unsigned int k, const double p, const unsigned int n);\nGSL_EXPORT double gsl_cdf_binomial_Q (const unsigned int k, const double p, const unsigned int n);\n\nGSL_EXPORT double gsl_cdf_poisson_P (const unsigned int k, const double mu);\nGSL_EXPORT double gsl_cdf_poisson_Q (const unsigned int k, const double mu);\n\nGSL_EXPORT double gsl_cdf_geometric_P (const unsigned int k, const double p);\nGSL_EXPORT double gsl_cdf_geometric_Q (const unsigned int k, const double p);\n\nGSL_EXPORT double gsl_cdf_negative_binomial_P (const unsigned int k, const double p, const double n);\nGSL_EXPORT double gsl_cdf_negative_binomial_Q (const unsigned int k, const double p, const double n);\n\nGSL_EXPORT double gsl_cdf_pascal_P (const unsigned int k, const double p, const unsigned int n);\nGSL_EXPORT double gsl_cdf_pascal_Q (const unsigned int k, const double p, const unsigned int n);\n\nGSL_EXPORT double gsl_cdf_hypergeometric_P (const unsigned int k, const unsigned int n1,\n const unsigned int n2, const unsigned int t);\nGSL_EXPORT double gsl_cdf_hypergeometric_Q (const unsigned int k, const unsigned int n1,\n const unsigned int n2, const unsigned int t);\n\n__END_DECLS\n\n#endif /* __GSL_CDF_H__ */\n", "meta": {"hexsha": "ec7be9e516b1ba7e8034ecf8b32e49c00bd8b8f3", "size": 8365, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_cdf.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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/core/gsl/include/gsl/gsl_cdf.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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/core/gsl/include/gsl/gsl_cdf.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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": 48.3526011561, "max_line_length": 101, "alphanum_fraction": 0.7882845188, "num_tokens": 2220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5841081433642726}} {"text": "// Alessandro Casalino\n//\n// Compile with (Mac with default homebrew gsl 2.6) gcc-9 -O2 coupled_quintessence_evolve.c -o coupled_quintessence_evolve.exe -L/usr/local/Cellar/gsl/2.6/lib -I/usr/local/Cellar/gsl/2.6/include -lgsl\n// Run with ./coupled_quintessence_evolve.exe\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n// PHYSICAL PARAMETERS VALUES\n\n// INITIAL CONDITIONS\n// Initial value of the scale factor\ndouble a_init = 1e-14;\n// Final value of the scale factor\ndouble a_end = 1.1;\n\n// Values of fractional density for the cosmological matter today\ndouble Omega_rad_0 = 8e-5;\ndouble Omega_b_0 = 0.0486;//0.0490439;\ndouble Omega_Lambda_0 = 0.;//0.6911;\ndouble Omega_cdm_0 = 0.2589;//0.264201;\n\n// Physical constants for output conversions\ndouble _G_ = 6.67428e-11; /**< Newton constant in m^3/Kg/s^2 */\ndouble _MPc_over_m_ = 3.085677581282e22; // Conversion factor from Mpc to m\ndouble _Gyr_over_Mpc_ = 3.06601394e2; // Conversion factor from Gyr to Mpc\ndouble _c_ = 2.99792458e8; // Speed of light in m/s\ndouble _H0_ = 67.74; // H0 of LCDM in Km/s/Mpc (h:0.6731)\n\ndouble fourpiG = 0.5;\n\ndouble T_CONF = 1.;\n\n// COMPUTATION PARAMETERS VALUES\n\n// Number of points used in the computation\nint points = (int) 1e6;\n// Max particle horizon value\ndouble max_tau = 40.;\n// Min particle horizon value\ndouble min_tau = 1e-9;\n\n// Raise this value to make the csv file smaller, but decreasing resolution\n// The value inserted is the ratio between the number of values written in a full resolution file / decreased resolution file\nint csv_resolution = 10;\n\n// BISECTION PARAMTERS\n// Bisection precision\ndouble delta_bisection = 1e-2;\n\n// Bisection target\n// 1: mg_field\n// 2: mg_field_p\n// 3: potential_constant\nint bisection_type = 3;\n\ndouble bisection_min = 0.;\ndouble bisection_max = 20.;\n\n// Initial conditions (considered accordingly to the bisection_type choice)\ndouble mg_field_bk_0 = 1e-20;\ndouble mg_field_p_bk_0 = 1.;\n\n// TEST MODE\n// Provides some informations on the terminal and the .csv file during the computation (1: on, others: off)\nint TEST_MODE = 1;\n\n\n// Definition of the POTENTIAL\n// For a list of the models see above\ndouble mg_pot_const = 1.;\ndouble mg_pot_exp = -0.5;\n\n\ndouble mg_pot(const double mg_field_bk) {\n\n return mg_pot_const * pow(mg_field_bk, mg_pot_exp);\n\n}\n\ndouble mg_pot_p(const double mg_field_bk) {\n\n return mg_pot_exp * mg_pot_const * pow(mg_field_bk, mg_pot_exp - 1.);\n\n}\n\n// Definition of the COUPLING FUNCION\n// For a list of the models see above\ndouble mg_coupl_const = 0.1;\n\n\ndouble mg_coupl(const double mg_field_bk) {\n\n // 2 factor to be consistent with hi_class units (8 pi G = 1)\n return mg_coupl_const * mg_field_bk * mg_field_bk;\n\n}\n\ndouble mg_coupl_p(const double mg_field_bk) {\n\n return 2.*mg_coupl_const * mg_field_bk;\n\n}\n\ndouble mg_coupl_pp(const double mg_field_bk) {\n\n return 2.*mg_coupl_const;\n\n}\n\n// Definitions of DIFFERENTIAL EQUATION system\n// Need to have first order equations to use Runge Kutta\n//\ndouble a_p_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)\n{\n\treturn a_p;\n}\ndouble a_pp_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)\n{\n double a3 = a * a * a;\n double rhoa3 = (Omega_cdm_0 + Omega_b_0) + (Omega_Lambda_0 * a3) + (Omega_rad_0 / a);\n double Pa3 = - (Omega_Lambda_0 * a3) + 1./3. * (Omega_rad_0 / a );\n\n return fourpiG / 3. * ( (rhoa3 - 3. * Pa3) - a * mg_field_p_bk * mg_field_p_bk * (1. + 3./2./fourpiG * mg_coupl_pp(mg_field_bk)) + 4. * a3 * mg_pot(mg_field_bk) + 3./2./fourpiG * a3 * mg_pot_p(mg_field_bk) * mg_coupl_p(mg_field_bk))/(1. + mg_coupl(mg_field_bk) + 3./4./fourpiG * mg_coupl_p(mg_field_bk) * mg_coupl_p(mg_field_bk));\n}\ndouble mg_field_bk_p_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)\n{\n\treturn mg_field_p_bk;\n}\ndouble mg_field_bk_pp_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)\n{\n double a2 = a * a;\n double rhoa2 = (Omega_cdm_0 + Omega_b_0) / a + (Omega_Lambda_0 * a2) + (Omega_rad_0 / a / a);\n double Pa2 = - (Omega_Lambda_0 * a2) + 1./3. * (Omega_rad_0 / a / a );\n\n\treturn - 2. * a_p/a * mg_field_p_bk + ( - mg_pot_p(mg_field_bk) * a2 * ( 1. + mg_coupl(mg_field_bk) ) + ( rhoa2 - 3. * Pa2 + 4. * a2 * mg_pot(mg_field_bk) - mg_field_p_bk * mg_field_p_bk * ( 1. + 3./2./fourpiG * mg_coupl_pp(mg_field_bk) ) ) /2. * mg_coupl_p(mg_field_bk) ) / (1. + mg_coupl(mg_field_bk) + 3./4./fourpiG * mg_coupl_p(mg_field_bk) * mg_coupl_p(mg_field_bk) );\n}\ndouble Hconf(const double a, const double mg_field_bk, const double mg_field_p_bk)\n{\n double a2 = a * a;\n double rhoa2 = (Omega_cdm_0 + Omega_b_0) / a + (Omega_Lambda_0 * a2) + (Omega_rad_0 / a / a);\n\n return - mg_field_p_bk * mg_coupl_p(mg_field_bk)/(1. + mg_coupl(mg_field_bk))/2. + sqrt((2. * fourpiG / 3.) * (1. + mg_coupl(mg_field_bk)) * ( rhoa2 + (mg_field_p_bk * mg_field_p_bk / 2.) + (a2 * mg_pot(mg_field_bk)) ) + mg_field_p_bk * mg_field_p_bk/4. * mg_coupl_p(mg_field_bk) * mg_coupl_p(mg_field_bk))/(1. + mg_coupl(mg_field_bk));\n}\n\n// Integrand for the particle horizon integral\ndouble particleHorizonIntegrand(double a, double mg_field_bk, double mg_field_p_bk)\n{\n\treturn 1. / ( a * Hconf(a, mg_field_bk, mg_field_p_bk) );\n}\n// Particle horizon integral step\ndouble particleHorizon(const int i, double * a, double * mg_field_bk, double * mg_field_p_bk) {\n double h = a[i]-a[i-1];\n double fa = particleHorizonIntegrand(a[i-1],mg_field_bk[i-1],mg_field_p_bk[i-1]);\n double fb = particleHorizonIntegrand(a[i],mg_field_bk[i],mg_field_p_bk[i]);\n\n return h*(fa+fb)/2.;\n}\n\n\n\nint scan_for_a0 (double * a, double ae) {\n\n int i=0;\n\n for(i=0; a[i] <= ae && i < points; i++);\n\n return i;\n\n}\n\n// Function used to print results stored in vectors as a csv file\nvoid csv(double * t, double * a, double * a_p, double * mg_field_bk, double * mg_field_p_bk, double * particleHorizonVec, char * filename) {\n\n FILE *fp;\n fp = fopen (filename, \"w+\");\n fprintf(fp, \"%s, %s, %s, %s, %s, %s, %s, %s\", \"t\", \"a(t)\", \"H(t)/H0\", \"H_prime(t)/H0^2\", \"Omega_df\", \"Omega_r\", \"Omega_b\", \"Omega_cdm\");\n fprintf(fp, \", %s\", \"omega_df\");\n fprintf(fp, \", %s\", \"PH\"); // Particle horizon\n fprintf(fp, \", %s\", \"mg_field\");\n fprintf(fp, \", %s\", \"mg_field_p\");\n if(TEST_MODE==1) fprintf(fp, \", %s\", \"H_check(t)/H0\");\n fprintf(fp, \"\\n\");\n\n // Time conversion factor\n // double tcf = 1./_H0_/(60.*60.*24.*365.*1e9)*_MPc_over_m_/1000.;\n\n int i = 0;\n double particleHorizonRes = 0.;\n\n for(i=1;i0){\n printf(\"WARNING: the energy density is negative at a = %e\\n\", a[i]);\n w1++;\n }\n if( (Omega_df+Omega_rad+Omega_b+Omega_cdm > 1.01 || Omega_df+Omega_rad+Omega_b+Omega_cdm < 0.99) && w2==0){\n printf(\"WARNING: the fractional density sum is %e at a = %e\\n\", Omega_df+Omega_rad+Omega_b+Omega_cdm,a[i]);\n w2++;\n }\n if( (Omega_df> 1. || Omega_rad > 1. || Omega_b > 1. || Omega_cdm > 1.) && w3==0){\n printf(\"WARNING: one fractional density is > 1 at a = %e\\n\", a[i]);\n w3++;\n }\n\n double omega_df = P_df/rho_df;\n\n if(T_CONF==0) H_prime = ( H_prime - H * H )/a[i]/a[i]; // this is Hubble prime with cosmological time\n if(T_CONF==0) H = H / a[i]; // this it the Hubble constant with cosmological time\n\n fprintf(fp, \"%e, %e, %e, %e, %e, %e, %e, %e\", t[i], a[i], H / H0, H_prime /H0 /H0, Omega_df, Omega_rad, Omega_b, Omega_cdm );\n fprintf(fp, \", %e\", omega_df);\n\n fprintf(fp, \", %e\", particleHorizonVec[i]);\n\n fprintf(fp, \", %e\", mg_field_bk[i]);\n fprintf(fp, \", %e\", mg_field_p_bk[i]);\n\n if(TEST_MODE==1){\n\n double H_test;\n\n H_test = a_p[i]/a[i];\n if(T_CONF==0) H_test = H_test / a[i];\n\n fprintf(fp, \", %e\", H_test / sqrt(2. * fourpiG / 3. / (1. + mg_coupl(mg_field_bk[i_a0])) ));\n\n }\n\n fprintf(fp, \"\\n\");\n\n if(a[i+csv_resolution]<= a_end){\n i=i+csv_resolution;\n }\n else{\n i++;\n }\n\n }\n\n fclose(fp);\n\n}\n\n// This divides an interval in a logarithmic scale of basis 10, and store results in input vector v\nvoid logscale10 (double * v, double A, double B, int points){\n\n int i;\n\n double a = log10(A);\n double b = log10(B);\n\n double h = (b - a) / (points-1.0);\n\n for(i=0;i Bisection target: mg_field_bk.\\n\", result);\n if(TEST_MODE==1) printf(\"\\n\");\n\n while(fabs((max-min)/min)>delta_bisection){\n\n a_p[0] = a_init * Hconf(a[0], min, mg_field_p_bk[0]);\n mg_field_bk[0] = min;\n double rk4_min = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);\n a_p[0] = a_init * Hconf(a[0], C, mg_field_p_bk[0]);\n mg_field_bk[0] = C;\n double rk4_C = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);\n\n if(rk4_min*rk4_C>=0) {\n min=C;\n }\n else {\n max=C;\n }\n\n C=(max+min)/2.;\n\n if (TEST_MODE == 1) printf(\"TEST_MODE ON - min: %e , max: %e, C: %e, rk4_min: %e , rk4_C: %e \\n\", min, max, C, rk4_min, rk4_C);\n\n }\n\n result = (max+min)/2.;\n\n if(TEST_MODE==1) printf(\"\\n\");\n printf(\"\\t-> Result of bisection method is mg_field_bk: %e (internal units).\\n\", result);\n\n }\n\n else if(type==2){\n\n printf(\"\\t-> Bisection target: mg_field_p_bk.\\n\", result);\n if(TEST_MODE==1) printf(\"\\n\");\n\n while(fabs((max-min)/min)>delta_bisection){\n\n a_p[0] = a_init * Hconf(a[0], mg_field_bk[0], min);\n mg_field_p_bk[0] = min;\n double rk4_min = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);\n a_p[0] = a_init * Hconf(a[0], mg_field_bk[0], C);\n mg_field_p_bk[0] = C;\n double rk4_C = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);\n\n if(rk4_min*rk4_C>=0) {\n min=C;\n }\n else {\n max=C;\n }\n\n C=(max+min)/2.;\n\n if (TEST_MODE == 1) printf(\"TEST_MODE ON - min: %e , max: %e, C: %e, rk4_min: %e , rk4_C: %e \\n\", min, max, C, rk4_min, rk4_C);\n\n }\n\n result = (max+min)/2.;\n\n if(TEST_MODE==1) printf(\"\\n\");\n printf(\"\\t-> Result of bisection method is mg_field_p_bk: %e (internal units).\\n\", result);\n\n }\n\n else if(type==3){\n\n printf(\"\\t-> Bisection target: mg_pot_const.\\n\", result);\n if(TEST_MODE==1) printf(\"\\n\");\n\n while(fabs((max-min)/min)>delta_bisection){\n\n mg_pot_const = min;\n a_p[0] = a_init * Hconf(a[0], mg_field_bk[0], mg_field_p_bk[0]);\n double rk4_min = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);\n mg_pot_const = C;\n a_p[0] = a_init * Hconf(a[0], mg_field_bk[0], mg_field_p_bk[0]);\n double rk4_C = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);\n\n if(rk4_min*rk4_C>=0) {\n min=C;\n }\n else {\n max=C;\n }\n\n C=(max+min)/2.;\n\n if (TEST_MODE == 1) printf(\"TEST_MODE ON - min: %e , max: %e, C: %e, rk4_min: %e , rk4_C: %e \\n\", min, max, C, rk4_min, rk4_C);\n\n }\n\n result = (max+min)/2.;\n\n if(TEST_MODE==1) printf(\"\\n\");\n printf(\"\\t-> Result of bisection method is mg_pot_const: %e (internal units).\\n\", result);\n\n }\n\n else{\n result = 0.;\n }\n\n return result;\n\n}\n\nint main() {\n\n double Omega_f_0 = 1. - Omega_Lambda_0 - Omega_rad_0 - Omega_b_0 - Omega_cdm_0;\n\n printf(\"\\n\\t\\t----------------------------------------\\n\\n\");\n\n // Definition of the vector needed for the evolution functions\n double * t; double * a; double * a_p; double * mg_field_bk; double * mg_field_p_bk; double * particleHorizonVec;\n t = (double *) malloc(sizeof(double) * points);\n a = (double *) malloc(sizeof(double) * points);\n a_p = (double *) malloc(sizeof(double) * points);\n mg_field_bk = (double *) malloc(sizeof(double) * points);\n mg_field_p_bk = (double *) malloc(sizeof(double) * points);\n particleHorizonVec = (double *) malloc(sizeof(double) * points);\n\n if(!t||!a||!a_p||!mg_field_bk||!mg_field_p_bk||!particleHorizonVec){\n printf(\"Error! The memory cannot be allocated. The program will be terminated.\\n\");\n exit(1);\n }\n\n // Initial conditions (tau=0)\n a[0] = a_init;\n\n mg_field_bk[0] = mg_field_bk_0;\n mg_field_p_bk[0] = mg_field_p_bk_0;\n\n printf(\"\\n Extended quintessence evolution\\n\");\n\n printf(\"\\n Parameters used: \\n\");\n printf(\"\\t- Potential constant: %e\\n\", mg_pot_const);\n printf(\"\\t- Potential exponent: %e\\n\", mg_pot_exp);\n printf(\"\\t- Function constant: %e\\n\", mg_coupl_const);\n\n printf(\" Searching for best initial value for the dark fluid ... \\n \\n\");\n\n double bisection_result = bisection(bisection_min, bisection_max, t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0,bisection_type);\n\n if (bisection_type==1) {\n mg_field_bk[0] = bisection_result;\n if(mg_field_bk[0] > bisection_max*(1.-0.05)) printf(\"\\n\\n WARNING: it seems that the initial value is too near the bounds! \\n\\n\");\n }\n else if (bisection_type==2) {\n mg_field_p_bk[0] = bisection_result;\n if(mg_field_p_bk[0] > bisection_max*(1.-0.05)) printf(\"\\n\\n WARNING: it seems that the initial value is too near the bounds! \\n\\n\");\n }\n else if (bisection_type==3) {\n mg_pot_const = bisection_result;\n if(mg_pot_const > bisection_max*(1.-0.05)) printf(\"\\n\\n WARNING: it seems that the initial value is too near the bounds! \\n\\n\");\n }\n else {\n printf(\"No bisection type chosen. The evolution will be computed with provided initial conditions.\");\n }\n\n a_p[0] = a_init * Hconf(a_init, mg_field_bk[0], mg_field_p_bk[0]);\n\n printf(\"\\n\\n Evolving the system ...\\n\");\n\n rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);\n\n int last_int = scan_for_a0(a,a_end);\n int last_int_print = scan_for_a0(a,1.);\n\n if(last_int >= points-1) printf(\"\\n\\n WARNING: the a = a_end value seems not to be reached in the result vectors! \\n\\n\");\n\n double t_age = 0.;\n int i = 0;\n for(i=2;i\n#include \n#include \n#include \n#include \n#include \n\nint\nmain (void)\n{\n const double eps = 100.0 * GSL_DBL_EPSILON;\n\n gsl_ieee_env_setup ();\n\n {\n double x, y;\n double c[3] = { 1.0, 0.5, 0.3 };\n x = 0.5;\n y = gsl_poly_eval (c, 3, x);\n gsl_test_rel (y, 1 + 0.5 * x + 0.3 * x * x, eps,\n \"gsl_poly_eval({1, 0.5, 0.3}, 0.5)\");\n }\n\n {\n double x, y;\n double d[11] = { 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1 };\n x = 1.0;\n y = gsl_poly_eval (d, 11, x);\n gsl_test_rel (y, 1.0, eps,\n \"gsl_poly_eval({1,-1, 1, -1, 1, -1, 1, -1, 1, -1, 1}, 1.0)\");\n\n }\n\n /* Quadratic */\n\n {\n double x0, x1;\n\n int n = gsl_poly_solve_quadratic (4.0, -20.0, 26.0, &x0, &x1);\n\n gsl_test (n != 0, \"gsl_poly_solve_quadratic, no roots, (2x - 5)^2 = -1\");\n }\n\n {\n double x0, x1;\n\n int n = gsl_poly_solve_quadratic (4.0, -20.0, 25.0, &x0, &x1);\n\n gsl_test (n != 2, \"gsl_poly_solve_quadratic, one root, (2x - 5)^2 = 0\");\n gsl_test_rel (x0, 2.5, 1e-9, \"x0, (2x - 5)^2 = 0\");\n gsl_test_rel (x1, 2.5, 1e-9, \"x1, (2x - 5)^2 = 0\");\n gsl_test (x0 != x1, \"x0 == x1, (2x - 5)^2 = 0\");\n }\n\n {\n double x0, x1;\n\n int n = gsl_poly_solve_quadratic (4.0, -20.0, 21.0, &x0, &x1);\n\n gsl_test (n != 2, \"gsl_poly_solve_quadratic, two roots, (2x - 5)^2 = 4\");\n gsl_test_rel (x0, 1.5, 1e-9, \"x0, (2x - 5)^2 = 4\");\n gsl_test_rel (x1, 3.5, 1e-9, \"x1, (2x - 5)^2 = 4\");\n }\n\n {\n double x0, x1;\n\n int n = gsl_poly_solve_quadratic (4.0, 7.0, 0.0, &x0, &x1);\n\n gsl_test (n != 2, \"gsl_poly_solve_quadratic, two roots, x(4x + 7) = 0\");\n gsl_test_rel (x0, -1.75, 1e-9, \"x0, x(4x + 7) = 0\");\n gsl_test_rel (x1, 0.0, 1e-9, \"x1, x(4x + 7) = 0\");\n }\n\n {\n double x0, x1;\n\n int n = gsl_poly_solve_quadratic (5.0, 0.0, -20.0, &x0, &x1);\n\n gsl_test (n != 2,\n \"gsl_poly_solve_quadratic, two roots b = 0, 5 x^2 = 20\");\n gsl_test_rel (x0, -2.0, 1e-9, \"x0, 5 x^2 = 20\");\n gsl_test_rel (x1, 2.0, 1e-9, \"x1, 5 x^2 = 20\");\n }\n\n\n {\n double x0, x1;\n\n int n = gsl_poly_solve_quadratic (0.0, 3.0, -21.0, &x0, &x1);\n\n gsl_test (n != 1,\n \"gsl_poly_solve_quadratic, one root (linear) 3 x - 21 = 0\");\n gsl_test_rel (x0, 7.0, 1e-9, \"x0, 3x - 21 = 0\");\n }\n\n\n {\n double x0, x1;\n int n = gsl_poly_solve_quadratic (0.0, 0.0, 1.0, &x0, &x1);\n\n gsl_test (n != 0,\n \"gsl_poly_solve_quadratic, no roots 1 = 0\");\n }\n\n\n /* Cubic */\n\n {\n double x0, x1, x2;\n\n int n = gsl_poly_solve_cubic (0.0, 0.0, -27.0, &x0, &x1, &x2);\n\n gsl_test (n != 1, \"gsl_poly_solve_cubic, one root, x^3 = 27\");\n gsl_test_rel (x0, 3.0, 1e-9, \"x0, x^3 = 27\");\n }\n\n {\n double x0, x1, x2;\n\n int n = gsl_poly_solve_cubic (-51.0, 867.0, -4913.0, &x0, &x1, &x2);\n\n gsl_test (n != 3, \"gsl_poly_solve_cubic, three roots, (x-17)^3=0\");\n gsl_test_rel (x0, 17.0, 1e-9, \"x0, (x-17)^3=0\");\n gsl_test_rel (x1, 17.0, 1e-9, \"x1, (x-17)^3=0\");\n gsl_test_rel (x2, 17.0, 1e-9, \"x2, (x-17)^3=0\");\n }\n\n {\n double x0, x1, x2;\n\n int n = gsl_poly_solve_cubic (-57.0, 1071.0, -6647.0, &x0, &x1, &x2);\n\n gsl_test (n != 3,\n \"gsl_poly_solve_cubic, three roots, (x-17)(x-17)(x-23)=0\");\n gsl_test_rel (x0, 17.0, 1e-9, \"x0, (x-17)(x-17)(x-23)=0\");\n gsl_test_rel (x1, 17.0, 1e-9, \"x1, (x-17)(x-17)(x-23)=0\");\n gsl_test_rel (x2, 23.0, 1e-9, \"x2, (x-17)(x-17)(x-23)=0\");\n }\n\n {\n double x0, x1, x2;\n\n int n = gsl_poly_solve_cubic (-11.0, -493.0, +6647.0, &x0, &x1, &x2);\n\n gsl_test (n != 3,\n \"gsl_poly_solve_cubic, three roots, (x+23)(x-17)(x-17)=0\");\n gsl_test_rel (x0, -23.0, 1e-9, \"x0, (x+23)(x-17)(x-17)=0\");\n gsl_test_rel (x1, 17.0, 1e-9, \"x1, (x+23)(x-17)(x-17)=0\");\n gsl_test_rel (x2, 17.0, 1e-9, \"x2, (x+23)(x-17)(x-17)=0\");\n }\n\n {\n double x0, x1, x2;\n\n int n = gsl_poly_solve_cubic (-143.0, 5087.0, -50065.0, &x0, &x1, &x2);\n\n gsl_test (n != 3,\n \"gsl_poly_solve_cubic, three roots, (x-17)(x-31)(x-95)=0\");\n gsl_test_rel (x0, 17.0, 1e-9, \"x0, (x-17)(x-31)(x-95)=0\");\n gsl_test_rel (x1, 31.0, 1e-9, \"x1, (x-17)(x-31)(x-95)=0\");\n gsl_test_rel (x2, 95.0, 1e-9, \"x2, (x-17)(x-31)(x-95)=0\");\n }\n\n {\n double x0, x1, x2;\n\n int n = gsl_poly_solve_cubic (-109.0, 803.0, 50065.0, &x0, &x1, &x2);\n\n gsl_test (n != 3,\n \"gsl_poly_solve_cubic, three roots, (x+17)(x-31)(x-95)=0\");\n gsl_test_rel (x0, -17.0, 1e-9, \"x0, (x+17)(x-31)(x-95)=0\");\n gsl_test_rel (x1, 31.0, 1e-9, \"x1, (x+17)(x-31)(x-95)=0\");\n gsl_test_rel (x2, 95.0, 1e-9, \"x2, (x+17)(x-31)(x-95)=0\");\n }\n\n /* Quadratic with complex roots */\n\n {\n gsl_complex z0, z1;\n\n int n = gsl_poly_complex_solve_quadratic (4.0, -20.0, 26.0, &z0, &z1);\n\n gsl_test (n != 2,\n \"gsl_poly_complex_solve_quadratic, 2 roots (2x - 5)^2 = -1\");\n gsl_test_rel (GSL_REAL (z0), 2.5, 1e-9, \"z0.real, (2x - 5)^2 = -1\");\n gsl_test_rel (GSL_IMAG (z0), -0.5, 1e-9, \"z0.imag, (2x - 5)^2 = -1\");\n\n gsl_test_rel (GSL_REAL (z1), 2.5, 1e-9, \"z1.real, (2x - 5)^2 = -1\");\n gsl_test_rel (GSL_IMAG (z1), 0.5, 1e-9, \"z1.imag, (2x - 5)^2 = -1\");\n }\n\n {\n gsl_complex z0, z1;\n\n int n = gsl_poly_complex_solve_quadratic (4.0, -20.0, 25.0, &z0, &z1);\n\n gsl_test (n != 2,\n \"gsl_poly_complex_solve_quadratic, one root, (2x - 5)^2 = 0\");\n gsl_test_rel (GSL_REAL (z0), 2.5, 1e-9, \"z0.real, (2x - 5)^2 = 0\");\n gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, \"z0.imag (2x - 5)^2 = 0\");\n gsl_test_rel (GSL_REAL (z1), 2.5, 1e-9, \"z1.real, (2x - 5)^2 = 0\");\n gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, \"z1.imag (2x - 5)^2 = 0\");\n gsl_test (GSL_REAL (z0) != GSL_REAL (z1),\n \"z0.real == z1.real, (2x - 5)^2 = 0\");\n gsl_test (GSL_IMAG (z0) != GSL_IMAG (z1),\n \"z0.imag == z1.imag, (2x - 5)^2 = 0\");\n }\n\n {\n gsl_complex z0, z1;\n\n int n = gsl_poly_complex_solve_quadratic (4.0, -20.0, 21.0, &z0, &z1);\n\n gsl_test (n != 2,\n \"gsl_poly_complex_solve_quadratic, two roots, (2x - 5)^2 = 4\");\n gsl_test_rel (GSL_REAL (z0), 1.5, 1e-9, \"z0.real, (2x - 5)^2 = 4\");\n gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, \"z0.imag, (2x - 5)^2 = 4\");\n gsl_test_rel (GSL_REAL (z1), 3.5, 1e-9, \"z1.real, (2x - 5)^2 = 4\");\n gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, \"z1.imag, (2x - 5)^2 = 4\");\n }\n\n {\n gsl_complex z0, z1;\n\n int n = gsl_poly_complex_solve_quadratic (4.0, 7.0, 0.0, &z0, &z1);\n\n gsl_test (n != 2,\n \"gsl_poly_complex_solve_quadratic, two roots, x(4x + 7) = 0\");\n gsl_test_rel (GSL_REAL (z0), -1.75, 1e-9, \"z0.real, x(4x + 7) = 0\");\n gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, \"z0.imag, x(4x + 7) = 0\");\n gsl_test_rel (GSL_REAL (z1), 0.0, 1e-9, \"z1.real, x(4x + 7) = 0\");\n gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, \"z1.imag, x(4x + 7) = 0\");\n }\n\n {\n gsl_complex z0, z1;\n\n int n = gsl_poly_complex_solve_quadratic (5.0, 0.0, -20.0, &z0, &z1);\n\n gsl_test (n != 2,\n \"gsl_poly_complex_solve_quadratic, two roots b = 0, 5 x^2 = 20\");\n gsl_test_rel (GSL_REAL (z0), -2.0, 1e-9, \"z0.real, 5 x^2 = 20\");\n gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, \"z0.imag, 5 x^2 = 20\");\n gsl_test_rel (GSL_REAL (z1), 2.0, 1e-9, \"z1.real, 5 x^2 = 20\");\n gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, \"z1.imag, 5 x^2 = 20\");\n }\n\n {\n gsl_complex z0, z1;\n\n int n = gsl_poly_complex_solve_quadratic (5.0, 0.0, 20.0, &z0, &z1);\n\n gsl_test (n != 2,\n \"gsl_poly_complex_solve_quadratic, two roots b = 0, 5 x^2 = -20\");\n gsl_test_rel (GSL_REAL (z0), 0.0, 1e-9, \"z0.real, 5 x^2 = -20\");\n gsl_test_rel (GSL_IMAG (z0), -2.0, 1e-9, \"z0.imag, 5 x^2 = -20\");\n gsl_test_rel (GSL_REAL (z1), 0.0, 1e-9, \"z1.real, 5 x^2 = -20\");\n gsl_test_rel (GSL_IMAG (z1), 2.0, 1e-9, \"z1.imag, 5 x^2 = -20\");\n }\n\n\n {\n gsl_complex z0, z1;\n\n int n = gsl_poly_complex_solve_quadratic (0.0, 3.0, -21.0, &z0, &z1);\n\n gsl_test (n != 1,\n \"gsl_poly_complex_solve_quadratic, one root (linear) 3 x - 21 = 0\");\n\n gsl_test_rel (GSL_REAL (z0), 7.0, 1e-9, \"z0.real, 3x - 21 = 0\");\n gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, \"z0.imag, 3x - 21 = 0\");\n }\n\n\n {\n gsl_complex z0, z1;\n\n int n = gsl_poly_complex_solve_quadratic (0.0, 0.0, 1.0, &z0, &z1);\n gsl_test (n != 0,\n \"gsl_poly_complex_solve_quadratic, no roots 1 = 0\");\n }\n\n\n\n /* Cubic with complex roots */\n\n {\n gsl_complex z0, z1, z2;\n\n int n = gsl_poly_complex_solve_cubic (0.0, 0.0, -27.0, &z0, &z1, &z2);\n\n gsl_test (n != 3, \"gsl_poly_complex_solve_cubic, three root, x^3 = 27\");\n gsl_test_rel (GSL_REAL (z0), -1.5, 1e-9, \"z0.real, x^3 = 27\");\n gsl_test_rel (GSL_IMAG (z0), -1.5 * sqrt (3.0), 1e-9,\n \"z0.imag, x^3 = 27\");\n gsl_test_rel (GSL_REAL (z1), -1.5, 1e-9, \"z1.real, x^3 = 27\");\n gsl_test_rel (GSL_IMAG (z1), 1.5 * sqrt (3.0), 1e-9, \"z1.imag, x^3 = 27\");\n gsl_test_rel (GSL_REAL (z2), 3.0, 1e-9, \"z2.real, x^3 = 27\");\n gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, \"z2.imag, x^3 = 27\");\n }\n\n {\n gsl_complex z0, z1, z2;\n\n int n = gsl_poly_complex_solve_cubic (-1.0, 1.0, 39.0, &z0, &z1, &z2);\n\n gsl_test (n != 3,\n \"gsl_poly_complex_solve_cubic, three root, (x+3)(x^2-4x+13) = 0\");\n gsl_test_rel (GSL_REAL (z0), -3.0, 1e-9, \"z0.real, (x+3)(x^2+1) = 0\");\n gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, \"z0.imag, (x+3)(x^2+1) = 0\");\n gsl_test_rel (GSL_REAL (z1), 2.0, 1e-9, \"z1.real, (x+3)(x^2+1) = 0\");\n gsl_test_rel (GSL_IMAG (z1), -3.0, 1e-9, \"z1.imag, (x+3)(x^2+1) = 0\");\n gsl_test_rel (GSL_REAL (z2), 2.0, 1e-9, \"z2.real, (x+3)(x^2+1) = 0\");\n gsl_test_rel (GSL_IMAG (z2), 3.0, 1e-9, \"z2.imag, (x+3)(x^2+1) = 0\");\n }\n\n {\n gsl_complex z0, z1, z2;\n\n int n =\n gsl_poly_complex_solve_cubic (-51.0, 867.0, -4913.0, &z0, &z1, &z2);\n\n gsl_test (n != 3,\n \"gsl_poly_complex_solve_cubic, three roots, (x-17)^3=0\");\n gsl_test_rel (GSL_REAL (z0), 17.0, 1e-9, \"z0.real, (x-17)^3=0\");\n gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, \"z0.imag, (x-17)^3=0\");\n gsl_test_rel (GSL_REAL (z1), 17.0, 1e-9, \"z1.real, (x-17)^3=0\");\n gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, \"z1.imag, (x-17)^3=0\");\n gsl_test_rel (GSL_REAL (z2), 17.0, 1e-9, \"z2.real, (x-17)^3=0\");\n gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, \"z2.imag, (x-17)^3=0\");\n }\n\n {\n gsl_complex z0, z1, z2;\n\n int n =\n gsl_poly_complex_solve_cubic (-57.0, 1071.0, -6647.0, &z0, &z1, &z2);\n\n gsl_test (n != 3,\n \"gsl_poly_complex_solve_cubic, three roots, (x-17)(x-17)(x-23)=0\");\n gsl_test_rel (GSL_REAL (z0), 17.0, 1e-9, \"z0.real, (x-17)(x-17)(x-23)=0\");\n gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, \"z0.imag, (x-17)(x-17)(x-23)=0\");\n gsl_test_rel (GSL_REAL (z1), 17.0, 1e-9, \"z1.real, (x-17)(x-17)(x-23)=0\");\n gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, \"z1.imag, (x-17)(x-17)(x-23)=0\");\n gsl_test_rel (GSL_REAL (z2), 23.0, 1e-9, \"z2.real, (x-17)(x-17)(x-23)=0\");\n gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, \"z2.imag, (x-17)(x-17)(x-23)=0\");\n }\n\n {\n gsl_complex z0, z1, z2;\n\n int n =\n gsl_poly_complex_solve_cubic (-11.0, -493.0, +6647.0, &z0, &z1, &z2);\n\n gsl_test (n != 3,\n \"gsl_poly_complex_solve_cubic, three roots, (x+23)(x-17)(x-17)=0\");\n gsl_test_rel (GSL_REAL (z0), -23.0, 1e-9,\n \"z0.real, (x+23)(x-17)(x-17)=0\");\n gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, \"z0.imag, (x+23)(x-17)(x-17)=0\");\n gsl_test_rel (GSL_REAL (z1), 17.0, 1e-9, \"z1.real, (x+23)(x-17)(x-17)=0\");\n gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, \"z1.imag, (x+23)(x-17)(x-17)=0\");\n gsl_test_rel (GSL_REAL (z2), 17.0, 1e-9, \"z2.real, (x+23)(x-17)(x-17)=0\");\n gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, \"z2.imag, (x+23)(x-17)(x-17)=0\");\n }\n\n\n {\n gsl_complex z0, z1, z2;\n\n int n =\n gsl_poly_complex_solve_cubic (-143.0, 5087.0, -50065.0, &z0, &z1, &z2);\n\n gsl_test (n != 3,\n \"gsl_poly_complex_solve_cubic, three roots, (x-17)(x-31)(x-95)=0\");\n gsl_test_rel (GSL_REAL (z0), 17.0, 1e-9, \"z0.real, (x-17)(x-31)(x-95)=0\");\n gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, \"z0.imag, (x-17)(x-31)(x-95)=0\");\n gsl_test_rel (GSL_REAL (z1), 31.0, 1e-9, \"z1.real, (x-17)(x-31)(x-95)=0\");\n gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, \"z1.imag, (x-17)(x-31)(x-95)=0\");\n gsl_test_rel (GSL_REAL (z2), 95.0, 1e-9, \"z2.real, (x-17)(x-31)(x-95)=0\");\n gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, \"z2.imag, (x-17)(x-31)(x-95)=0\");\n }\n\n\n {\n /* Wilkinson polynomial: y = (x-1)(x-2)(x-3)(x-4)(x-5) */\n\n double a[6] = { -120, 274, -225, 85, -15, 1 };\n double z[6*2];\n\n gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc (6);\n\n int status = gsl_poly_complex_solve (a, 6, w, z);\n\n gsl_poly_complex_workspace_free (w);\n\n gsl_test (status,\n \"gsl_poly_complex_solve, 5th-order Wilkinson polynomial\");\n gsl_test_rel (z[0], 1.0, 1e-9, \"z0.real, 5th-order polynomial\");\n gsl_test_rel (z[1], 0.0, 1e-9, \"z0.imag, 5th-order polynomial\");\n gsl_test_rel (z[2], 2.0, 1e-9, \"z1.real, 5th-order polynomial\");\n gsl_test_rel (z[3], 0.0, 1e-9, \"z1.imag, 5th-order polynomial\");\n gsl_test_rel (z[4], 3.0, 1e-9, \"z2.real, 5th-order polynomial\");\n gsl_test_rel (z[5], 0.0, 1e-9, \"z2.imag, 5th-order polynomial\");\n gsl_test_rel (z[6], 4.0, 1e-9, \"z3.real, 5th-order polynomial\");\n gsl_test_rel (z[7], 0.0, 1e-9, \"z3.imag, 5th-order polynomial\");\n gsl_test_rel (z[8], 5.0, 1e-9, \"z4.real, 5th-order polynomial\");\n gsl_test_rel (z[9], 0.0, 1e-9, \"z4.imag, 5th-order polynomial\");\n }\n\n {\n /* : 8-th order polynomial y = x^8 + x^4 + 1 */\n\n double a[9] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 };\n double z[8*2];\n\n double C = 0.5;\n double S = sqrt (3.0) / 2.0;\n\n gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc (9);\n\n int status = gsl_poly_complex_solve (a, 9, w, z);\n\n gsl_poly_complex_workspace_free (w);\n\n gsl_test (status, \"gsl_poly_complex_solve, 8th-order polynomial\");\n\n gsl_test_rel (z[0], -S, 1e-9, \"z0.real, 8th-order polynomial\");\n gsl_test_rel (z[1], C, 1e-9, \"z0.imag, 8th-order polynomial\");\n gsl_test_rel (z[2], -S, 1e-9, \"z1.real, 8th-order polynomial\");\n gsl_test_rel (z[3], -C, 1e-9, \"z1.imag, 8th-order polynomial\");\n gsl_test_rel (z[4], -C, 1e-9, \"z2.real, 8th-order polynomial\");\n gsl_test_rel (z[5], S, 1e-9, \"z2.imag, 8th-order polynomial\");\n gsl_test_rel (z[6], -C, 1e-9, \"z3.real, 8th-order polynomial\");\n gsl_test_rel (z[7], -S, 1e-9, \"z3.imag, 8th-order polynomial\");\n gsl_test_rel (z[8], C, 1e-9, \"z4.real, 8th-order polynomial\");\n gsl_test_rel (z[9], S, 1e-9, \"z4.imag, 8th-order polynomial\");\n gsl_test_rel (z[10], C, 1e-9, \"z5.real, 8th-order polynomial\");\n gsl_test_rel (z[11], -S, 1e-9, \"z5.imag, 8th-order polynomial\");\n gsl_test_rel (z[12], S, 1e-9, \"z6.real, 8th-order polynomial\");\n gsl_test_rel (z[13], C, 1e-9, \"z6.imag, 8th-order polynomial\");\n gsl_test_rel (z[14], S, 1e-9, \"z7.real, 8th-order polynomial\");\n gsl_test_rel (z[15], -C, 1e-9, \"z7.imag, 8th-order polynomial\");\n\n }\n\n {\n int i;\n\n double xa[7] = {0.16, 0.97, 1.94, 2.74, 3.58, 3.73, 4.70 };\n double ya[7] = {0.73, 1.11, 1.49, 1.84, 2.30, 2.41, 3.07 };\n\n double dd_expected[7] = { 7.30000000000000e-01,\n 4.69135802469136e-01,\n -4.34737219941284e-02,\n 2.68681098870099e-02,\n -3.22937056934996e-03,\n 6.12763259971375e-03,\n -6.45402453527083e-03 };\n\n double dd[7], coeff[7], work[7];\n \n gsl_poly_dd_init (dd, xa, ya, 7);\n\n for (i = 0; i < 7; i++)\n {\n gsl_test_rel (dd[i], dd_expected[i], 1e-10, \"divided difference dd[%d]\", i);\n }\n\n for (i = 0; i < 7; i++)\n {\n double y = gsl_poly_dd_eval(dd, xa, 7, xa[i]);\n gsl_test_rel (y, ya[i], 1e-10, \"divided difference y[%d]\", i);\n }\n\n gsl_poly_dd_taylor (coeff, 1.5, dd, xa, 7, work);\n \n for (i = 0; i < 7; i++)\n {\n double y = gsl_poly_eval(coeff, 7, xa[i] - 1.5);\n gsl_test_rel (y, ya[i], 1e-10, \"taylor expansion about 1.5 y[%d]\", i);\n }\n }\n\n\n /* now summarize the results */\n\n exit (gsl_test_summary ());\n}\n", "meta": {"hexsha": "bd0e141b3195333d3f956df9b1867c49cee46181", "size": 17147, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/poly/test.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/test.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/test.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": 33.6876227898, "max_line_length": 84, "alphanum_fraction": 0.5498337902, "num_tokens": 7772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5836162172058458}} {"text": "static const char help[] =\n\"Build and view a tiny three-triangle mesh using DMPlex, and integrate a\\n\"\n\"scalar function over it. Option prefixes tny_ and plex_view_.\\n\\n\";\n\n/* either build DMPlex via call to DMPlexCreateFromCellList()\n ./tiny\nor by directly setting cones \"by hand\":\n ./tiny -tny_by_hand\n\ncompute an integral by symmetric Gauss quadrature:\n ./tiny -tny_integrate_f\n ./tiny -tny_integrate_f -tny_quaddegree 1|[2]|3\n\ncompare these views:\n ./tiny -dm_view\n ./tiny -section_view\n ./tiny -v_vec_view\n\nand -plex_view_xxx options (see plexview.h)\n\nparallel refinement works:\n mpiexec -n 2 ./tiny -dm_refine 1 -plex_view_ranges -plex_view_coords\n\nFIXME interpolation of f(x,y) by P2\n\nFIXME interpolate f(x,y) by P2 and integrate it\n\nFIXME add option -tny_element P1|P2|P3\n*/\n\n#include \n#include \"../../quadrature.h\"\n#include \"plexview.h\"\n\n// Describe the mesh \"triangle style\" with separate numbering for cells and vertices.\nstatic const int dim = 2,\n ncell = 3,\n nvert = 5,\n cells[9] = {0, 3, 2, // 9 = ncell * (dim+1)\n 0, 2, 1,\n 2, 3, 4};\nstatic const double coordverts[10] = {0.0, 0.0, // 10 = nvert * dim\n 0.0, 1.0,\n 0.5, 1.0,\n 1.0, 0.0,\n 1.0, 1.0};\n\n// Describe same mesh, but directly as DMPlex, i.e. by giving cell and\n// edge cones in DAG. These values are generated by DMPlexCreateFromCellList()\n// internally, so they are redundant if we use that create method.\nstatic const int npoint = 15,\n ccone[3][3] = {{8,9,10},\n {10,11,12},\n {9,13,14}},\n econe[7][2] = {{3,6},\n {5,6},\n {3,5},\n {4,5},\n {3,4},\n {6,7},\n {5,7}};\n\nstatic double f(double x, double y) {\n return exp(- x - 2 * y);\n}\n\nextern PetscErrorCode CreateMeshByHand(DM*);\nextern PetscErrorCode CreateCoordinateSectionByHand(DM*);\nextern PetscErrorCode CreateSectionP2(DM,PetscSection*);\nextern PetscErrorCode IntegrateF(DM,double(double,double),int,double*);\nextern PetscErrorCode EvaluateFP2(DM,PetscSection,double(double,double),Vec*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n DM dmplex;\n PetscSection p2section;\n Vec v;\n PetscBool by_hand = PETSC_FALSE,\n integrate_f = PETSC_FALSE;\n int quaddegree = 2;\n\n PetscInitialize(&argc,&argv,NULL,help);\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD, \"tny_\", \"options for tiny\", \"\");CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-by_hand\",\n \"use by-hand construction\",\n \"tiny.c\", by_hand, &by_hand, NULL);CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-integrate_f\",\n \"integrate f(x,y) by summing over cells and using quadrature\",\n \"tiny.c\", integrate_f, &integrate_f, NULL);CHKERRQ(ierr);\n ierr = PetscOptionsInt(\"-quaddegree\",\n \"use this quadrature degree for numerical integrations\",\n \"tiny.c\", quaddegree, &quaddegree, NULL);CHKERRQ(ierr);\n ierr = PetscOptionsEnd();\n\n // create the DMPlex mesh\n if (by_hand) {\n ierr = CreateMeshByHand(&dmplex); CHKERRQ(ierr);\n ierr = CreateCoordinateSectionByHand(&dmplex); CHKERRQ(ierr);\n } else {\n PetscMPIInt rank;\n ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank); CHKERRQ(ierr);\n if (rank == 0) { // create mesh on rank 0\n ierr = DMPlexCreateFromCellList(PETSC_COMM_WORLD,\n dim,ncell,nvert,dim+1,\n PETSC_TRUE, // \"interpolate\" flag; TRUE means \"topologically-interpolate\"\n // i.e. create edges (1D) from vertices (0D) and cells (2D)\n cells,dim,coordverts,\n &dmplex); CHKERRQ(ierr);\n } else { // empty mesh on rank > 0\n ierr = DMPlexCreateFromCellList(PETSC_COMM_WORLD,\n dim,0,0,dim+1,PETSC_TRUE,NULL,dim,NULL,&dmplex); CHKERRQ(ierr);\n }\n }\n\n // distribute mesh over processes using default partitioner\n {\n DM distributedMesh = NULL;\n // overlap of 0 is appropriate to P2 etc. FEM:\n ierr = DMPlexDistribute(dmplex, 0, NULL, &distributedMesh);CHKERRQ(ierr);\n if (distributedMesh) {\n ierr = DMDestroy(&dmplex);CHKERRQ(ierr);\n dmplex = distributedMesh;\n }\n }\n\n // reset names before viewing\n ierr = PetscObjectSetName((PetscObject)dmplex, \"tiny mesh\"); CHKERRQ(ierr);\n {\n DM cdm;\n PetscSection csection;\n ierr = DMGetCoordinateDM(dmplex, &cdm); CHKERRQ(ierr);\n ierr = DMGetDefaultSection(cdm, &csection); CHKERRQ(ierr);\n ierr = PetscObjectSetName((PetscObject)csection, \"vertex coordinate section\"); CHKERRQ(ierr);\n }\n ierr = DMSetFromOptions(dmplex); CHKERRQ(ierr);\n ierr = DMViewFromOptions(dmplex, NULL, \"-dm_view\"); CHKERRQ(ierr);\n ierr = PlexViewFromOptions(dmplex); CHKERRQ(ierr);\n\n // integrate f(x,y) by summing over cells and using quadrature\n if (integrate_f) {\n double integral;\n const double intfexact = (1.0 - exp(-1.0)) * 0.5 * (1.0 - exp (-2.0));\n ierr = IntegrateF(dmplex,f,quaddegree,&integral); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"integral of f(x,y) is %.12f with error %.2e\\n\",\n integral,fabs(integral - intfexact)); CHKERRQ(ierr);\n }\n\n // create nodes (degrees of freedom) for P2 elements using PetscSection\n ierr = CreateSectionP2(dmplex,&p2section); CHKERRQ(ierr);\n ierr = DMSetDefaultSection(dmplex, p2section); CHKERRQ(ierr);\n ierr = PetscObjectViewFromOptions((PetscObject)p2section,NULL,\"-tny_view_section\"); CHKERRQ(ierr);\n\n // put function f(x,y) into v by local calculations using coordinates and p2section\n ierr = DMCreateGlobalVector(dmplex, &v); CHKERRQ(ierr);\n ierr = PetscObjectSetName((PetscObject)v, \"v\"); CHKERRQ(ierr);\n ierr = EvaluateFP2(dmplex,p2section,f,&v); CHKERRQ(ierr);\n ierr = PetscObjectViewFromOptions((PetscObject)v,NULL,\"-v_vec_view\"); CHKERRQ(ierr);\n\n VecDestroy(&v); PetscSectionDestroy(&p2section); DMDestroy(&dmplex);\n return PetscFinalize();\n}\n\n/* This function is essentially equivalent to using DMPlexCreateFromCellList().\nNote that rank 0 gets the actual mesh and other ranks get an empty mesh.\nSee the implementations of\n DMPlexBuildFromCellList_Private()\n DMPlexCreateFromCellListParallel()\n DMPlexInterpolate()\n DMPlexBuildCoordinates_Private() */\nPetscErrorCode CreateMeshByHand(DM *dmplex) {\n PetscErrorCode ierr;\n int j;\n PetscMPIInt rank;\n ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank); CHKERRQ(ierr);\n ierr = DMPlexCreate(PETSC_COMM_WORLD,dmplex); CHKERRQ(ierr);\n ierr = DMSetDimension(*dmplex,dim); CHKERRQ(ierr);\n if (rank == 0) {\n // set the total number of points (npoint = ncell + nvert + nedges)\n ierr = DMPlexSetChart(*dmplex, 0, npoint); CHKERRQ(ierr);\n // the points are cells, vertices, edges in that order\n // we only set cones for cells and edges\n for (j = 0; j < ncell; j++) {\n ierr = DMPlexSetConeSize(*dmplex, j, dim+1); CHKERRQ(ierr);\n }\n for (j = ncell + nvert; j < npoint; j++) {\n ierr = DMPlexSetConeSize(*dmplex, j, dim); CHKERRQ(ierr);\n }\n ierr = DMSetUp(*dmplex);\n for (j = 0; j < ncell; j++) {\n ierr = DMPlexSetCone(*dmplex, j, ccone[j]); CHKERRQ(ierr);\n }\n for (j = ncell + nvert; j < npoint; j++) {\n ierr = DMPlexSetCone(*dmplex, j, econe[j-ncell-nvert]); CHKERRQ(ierr);\n }\n } else {\n ierr = DMPlexSetChart(*dmplex, 0, 0); CHKERRQ(ierr);\n }\n // with cones we have only upward directions and no labels for the strata\n // (note: both Symmetrize & Stratify are required, and they must be in this order\n ierr = DMPlexSymmetrize(*dmplex); CHKERRQ(ierr);\n ierr = DMPlexStratify(*dmplex); CHKERRQ(ierr);\n return 0;\n}\n\n// Set up a PetscSection which holds vertex coordinates.\nPetscErrorCode CreateCoordinateSectionByHand(DM *dmplex) {\n PetscErrorCode ierr;\n PetscSection coordSection;\n DM cdm;\n Vec coordinates;\n double *acoord;\n int j, d, dim, vertexstart, vertexend;\n // you have to setup the PetscSection returned by DMGetCoordinateSection() first,\n // or else the Vec returned by DMCreateLocalVector() has zero size\n // (and thus seg faults)\n ierr = DMGetDimension(*dmplex, &dim); CHKERRQ(ierr);\n ierr = DMGetCoordinateSection(*dmplex, &coordSection); CHKERRQ(ierr);\n ierr = DMPlexGetDepthStratum(*dmplex, 0, &vertexstart, &vertexend); CHKERRQ(ierr);\n ierr = PetscSectionSetNumFields(coordSection, 1); CHKERRQ(ierr);\n ierr = PetscSectionSetFieldComponents(coordSection, 0, dim); CHKERRQ(ierr);\n ierr = PetscSectionSetChart(coordSection, vertexstart, vertexend); CHKERRQ(ierr);\n for (j = vertexstart; j < vertexend; j++) {\n ierr = PetscSectionSetDof(coordSection, j, dim); CHKERRQ(ierr);\n ierr = PetscSectionSetFieldDof(coordSection, j, 0, dim); CHKERRQ(ierr);\n }\n ierr = PetscSectionSetUp(coordSection); CHKERRQ(ierr);\n // now we can actually set up the coordinate Vec\n ierr = DMGetCoordinateDM(*dmplex, &cdm); CHKERRQ(ierr);\n ierr = DMCreateLocalVector(cdm, &coordinates); CHKERRQ(ierr);\n ierr = VecSetBlockSize(coordinates,dim); CHKERRQ(ierr);\n ierr = PetscObjectSetName((PetscObject) coordinates, \"coordinates\"); CHKERRQ(ierr);\n ierr = VecGetArray(coordinates, &acoord); CHKERRQ(ierr);\n for (j = 0; j < vertexend-vertexstart; j++) {\n for (d = 0; d < dim; ++d) {\n acoord[j*dim+d] = coordverts[j*dim+d];\n }\n }\n ierr = VecRestoreArray(coordinates, &acoord); CHKERRQ(ierr);\n // finally we tell the DM that it has coordinates\n ierr = DMSetCoordinatesLocal(*dmplex, coordinates); CHKERRQ(ierr);\n VecDestroy(&coordinates);\n return 0;\n}\n\n// use quadrature to integrate a function by summing over cells\nPetscErrorCode IntegrateF(DM dmplex, double f(double x,double y),\n int quaddegree, double *fint) {\n PetscErrorCode ierr;\n DM cdm;\n Vec coords;\n const Quad2DTri q = symmgauss[quaddegree-1];\n const double *acoords;\n double x[3], y[3], xr, yr, dx1, dx2, dy1, dy2, absdetJ,\n csum, fintloc;\n int numpts, *pts = NULL, voff, j, p, l, r,\n vertstart, vertend, cellstart, cellend;\n MPI_Comm comm;\n\n ierr = DMGetCoordinateDM(dmplex, &cdm); CHKERRQ(ierr);\n ierr = DMGetCoordinatesLocal(dmplex, &coords); CHKERRQ(ierr);\n ierr = DMPlexGetHeightStratum(dmplex, 0, &cellstart, &cellend); CHKERRQ(ierr);\n ierr = DMPlexGetDepthStratum(dmplex, 0, &vertstart, &vertend); CHKERRQ(ierr);\n ierr = VecGetArrayRead(coords, &acoords); CHKERRQ(ierr);\n // integral by sum over cells\n fintloc = 0.0;\n for (j = cellstart; j < cellend; j++) {\n ierr = DMPlexGetTransitiveClosure(dmplex, j, PETSC_TRUE, &numpts, &pts);\n if (numpts != 7) {\n SETERRQ(PETSC_COMM_WORLD,1,\"wrong: assume closure of triangle has 7 points\\n\");\n }\n // record vertex coordinates\n for (l = 0; l < 3; l++) { // loop through vertex points\n p = 8 + 2 * l; // p=0,1 are cell info; p=2,...,7 are edge info; omit orientations\n if ((pts[p] < vertstart) || (pts[p] >= vertend)) {\n SETERRQ(PETSC_COMM_WORLD,2,\"wrong: pts[p] should be a vertex\\n\");\n }\n voff = pts[p] - vertstart;\n x[l] = acoords[2*voff+0];\n y[l] = acoords[2*voff+1];\n }\n // geometry of element (cell)\n dx1 = x[1] - x[0];\n dx2 = x[2] - x[0];\n dy1 = y[1] - y[0];\n dy2 = y[2] - y[0];\n absdetJ = fabs(dx1 * dy2 - dx2 * dy1);\n // sum over quadrature points on cell\n csum = 0.0;\n for (r = 0; r < q.n; r++) {\n xr = x[0] + dx1 * q.xi[r] + dx2 * q.eta[r];\n yr = y[0] + dy1 * q.xi[r] + dy2 * q.eta[r];\n csum += q.w[r] * f(xr,yr);\n }\n // add cell contribution\n fintloc += absdetJ * csum;\n ierr = DMPlexRestoreTransitiveClosure(dmplex, j, PETSC_TRUE, &numpts, &pts); CHKERRQ(ierr);\n }\n ierr = VecRestoreArrayRead(coords, &acoords); CHKERRQ(ierr);\n\n ierr = PetscObjectGetComm((PetscObject)dmplex,&comm); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&fintloc,fint,1,MPI_DOUBLE,MPI_SUM,comm); CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode CreateSectionP2(DM dmplex, PetscSection *section) {\n PetscErrorCode ierr;\n int j, pstart, pend, vertexstart, edgeend;\n ierr = PetscSectionCreate(PETSC_COMM_WORLD,section); CHKERRQ(ierr);\n ierr = PetscObjectSetName((PetscObject)*section, \"P2 scalar section\"); CHKERRQ(ierr);\n ierr = PetscSectionSetNumFields(*section, 1); CHKERRQ(ierr);\n ierr = DMPlexGetChart(dmplex, &pstart, &pend); CHKERRQ(ierr);\n ierr = PetscSectionSetChart(*section, pstart, pend); CHKERRQ(ierr);\n ierr = DMPlexGetDepthStratum(dmplex, 0, &vertexstart, NULL); CHKERRQ(ierr);\n ierr = DMPlexGetDepthStratum(dmplex, 1, NULL, &edgeend); CHKERRQ(ierr);\n for (j = pstart; j < pend; ++j) {\n if (j < vertexstart) {\n ierr = PetscSectionSetDof(*section, j, 0); CHKERRQ(ierr);\n ierr = PetscSectionSetFieldDof(*section, j, 0, 0); CHKERRQ(ierr);\n } else {\n ierr = PetscSectionSetDof(*section, j, 1); CHKERRQ(ierr);\n ierr = PetscSectionSetFieldDof(*section, j, 0, 1); CHKERRQ(ierr);\n }\n }\n ierr = PetscSectionSetUp(*section); CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode EvaluateFP2(DM dmplex, PetscSection section,\n double f(double x,double y), Vec *v) {\n PetscErrorCode ierr;\n DM cdm;\n Vec vloc, coords;\n double *avloc, x, y;\n const double *acoords;\n int numpts, *pts = NULL, dof, off, j, p,\n vertstart, vertend, edgestart, edgeend, cellstart, cellend;\n\n // we put values in a local vector, thus redundantly on overlap\n ierr = DMGetLocalVector(dmplex, &vloc); CHKERRQ(ierr);\n ierr = VecGetArray(vloc, &avloc); CHKERRQ(ierr);\n // need coordinates of P2 nodes (i.e. both vertices and edges)\n ierr = DMGetCoordinateDM(dmplex, &cdm); CHKERRQ(ierr);\n ierr = DMGetCoordinatesLocal(dmplex,&coords); CHKERRQ(ierr);\n ierr = DMPlexGetHeightStratum(dmplex, 0, &cellstart, &cellend); CHKERRQ(ierr);\n ierr = DMPlexGetDepthStratum(dmplex, 0, &vertstart, &vertend); CHKERRQ(ierr);\n ierr = DMPlexGetDepthStratum(dmplex, 1, &edgestart, &edgeend); CHKERRQ(ierr);\n ierr = VecGetArrayRead(coords, &acoords); CHKERRQ(ierr);\n for (j = cellstart; j < cellend; j++) {\n ierr = DMPlexGetTransitiveClosure(dmplex, j, PETSC_TRUE, &numpts, &pts);\n for (p = 0; p < numpts*2; p += 2) { // omit orientations\n PetscSectionGetDof(section, pts[p], &dof);\n if (dof > 0) {\n // compute (x,y) for vertex or edge center from coords\n if (pts[p] < vertstart) {\n SETERRQ(PETSC_COMM_WORLD,1,\"cell center computation not implemented\\n\");\n } else if (pts[p] < edgestart) {\n int voff;\n voff = pts[p] - vertstart;\n x = acoords[2*voff+0];\n y = acoords[2*voff+1];\n } else { // pts[p] is an edge ...\n const int *vpts;\n int voff[2];\n ierr = DMPlexGetCone(dmplex, pts[p], &vpts); CHKERRQ(ierr);\n voff[0] = vpts[0] - vertstart;\n voff[1] = vpts[1] - vertstart;\n x = 0.5 * (acoords[2*voff[0]+0] + acoords[2*voff[1]+0]);\n y = 0.5 * (acoords[2*voff[0]+1] + acoords[2*voff[1]+1]);\n }\n // get index \"off\" into Vec vloc based on P2 scalar section\n PetscSectionGetOffset(section, pts[p], &off);\n avloc[off] = f(x,y);\n }\n }\n ierr = DMPlexRestoreTransitiveClosure(dmplex, j, PETSC_TRUE, &numpts, &pts); CHKERRQ(ierr);\n }\n ierr = VecRestoreArray(vloc, &avloc); CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(coords, &acoords); CHKERRQ(ierr);\n\n // now we want v global, i.e. only values not duplicate ghosts\n ierr = DMLocalToGlobalBegin(dmplex,vloc,INSERT_VALUES,*v); CHKERRQ(ierr);\n ierr = DMLocalToGlobalEnd(dmplex,vloc,INSERT_VALUES,*v); CHKERRQ(ierr);\n ierr = DMRestoreLocalVector(dmplex, &vloc); CHKERRQ(ierr);\n return 0;\n}\n\n// FIXME InterpolateFP2()\n\n", "meta": {"hexsha": "bb051d0384b5b33cd93fc167b424dd66c3ec3d82", "size": 17057, "ext": "c", "lang": "C", "max_stars_repo_path": "c/junk/plex/tiny.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/junk/plex/tiny.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/junk/plex/tiny.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": 43.7358974359, "max_line_length": 102, "alphanum_fraction": 0.5996365129, "num_tokens": 4739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629215, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.583236871920227}} {"text": "#include \n#include \n\n#if PETSC_VERSION_LT(3,17,0)\n#undef SETERRQ\n#define SETERRQ(comm,ierr,...) return PetscError(comm,__LINE__,PETSC_FUNCTION_NAME,__FILE__,ierr,PETSC_ERROR_INITIAL,__VA_ARGS__)\n#endif\n\nPETSC_EXTERN PetscErrorCode IGA_Partition(PetscInt,PetscInt,PetscInt,const PetscInt[],PetscInt[],PetscInt[]);\nPETSC_EXTERN PetscErrorCode IGA_Distribute(PetscInt,const PetscInt[],const PetscInt[],const PetscInt[],PetscInt[],PetscInt[]);\n\nstatic inline\nPetscInt IGA_CUT2D(PetscInt M,PetscInt N,\n PetscInt m,PetscInt n)\n{return M*(n-1) + N*(m-1);}\n\nstatic inline\nPetscInt IGA_CUT3D(PetscInt M,PetscInt N,PetscInt P,\n PetscInt m,PetscInt n,PetscInt p)\n{return (N*P*(m-1) + M*P*(n-1) + M*N*(p-1));}\n\nstatic inline\nPetscInt IGA_PART2D_INNER(PetscInt size,\n PetscInt M,PetscInt N,\n PetscInt *_m,PetscInt *_n)\n{\n PetscInt m,n;\n m = (PetscInt)(0.5 + sqrt(((double)M)/((double)N)*((double)size)));\n if (m == 0) {m = 1;} while (m > 0 && size % m) m--;\n n = size / m;\n *_m = m; *_n = n;\n return IGA_CUT2D(M,N,m,n);\n}\n\nstatic inline\nvoid IGA_PART2D(PetscInt size,\n PetscInt M,PetscInt N,\n PetscInt *_m,PetscInt *_n)\n{\n PetscInt m,n;\n PetscInt m1,n1,a;\n PetscInt m2,n2,b;\n a = IGA_PART2D_INNER(size,M,N,&m1,&n1);\n b = IGA_PART2D_INNER(size,N,M,&n2,&m2);\n if (a 0 && size % m) m--;\n /**/\n IGA_PART2D(size/m,N,P,&n,&p);\n C = IGA_CUT3D(M,N,P,m,n,p);\n /**/\n for (mm=m; mm>=1; mm--) {\n if (size % mm) continue;\n IGA_PART2D(size/mm,N,P,&nn,&pp);\n CC = IGA_CUT3D(M,N,P,mm,nn,pp);\n if (CC < C) {m = mm; n = nn; p = pp; C = CC;}\n }\n /**/\n for (nn=n; nn>=1; nn--) {\n if (size % nn) continue;\n IGA_PART2D(size/nn,M,P,&mm,&pp);\n CC = IGA_CUT3D(M,N,P,mm,nn,pp);\n if (CC < C) {m = mm; n = nn; p = pp; C = CC;}\n }\n /**/\n for (pp=p; pp>=1; pp--) {\n if (size % pp) continue;\n IGA_PART2D(size/pp,M,N,&mm,&nn);\n CC = IGA_CUT3D(M,N,P,mm,nn,pp);\n if (CC < C) {m = mm; n = nn; p = pp; C = CC;}\n }\n /**/\n *_m = m; *_n = n; *_p = p;\n return IGA_CUT3D(M,N,P,m,n,p);\n}\n\nstatic inline\nvoid IGA_PART3D(PetscInt size,\n PetscInt M,PetscInt N,PetscInt P,\n PetscInt *_m,PetscInt *_n,PetscInt *_p)\n{\n PetscInt m[3],n[3],p[3],C[3],k,i=0,Cmin=PETSC_MAX_INT,t;\n C[0] = IGA_PART3D_INNER(size,M,N,P,&m[0],&n[0],&p[0]);\n C[1] = IGA_PART3D_INNER(size,N,M,P,&n[1],&m[1],&p[1]);\n C[2] = IGA_PART3D_INNER(size,P,M,N,&p[2],&m[2],&n[2]);\n for (k=0; k<3; k++) if (C[k]= size))\n SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,\"Partition index %D must be in range [0,%D]\",rank,size-1);\n\n switch (dim) {\n case 3: IGA_Part3D(size,N[0],N[1],N[2],&n[0],&n[1],&n[2]); break;\n case 2: IGA_Part2D(size,N[0],N[1],&n[0],&n[1]); break;\n case 1: if (n[0] < 1) n[0] = size; break;\n default: SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,\"Number of dimensions %D must be in range [1,3]\",dim);\n }\n for (k=0; k rank);\n *s = rank * (N/size) + (((N % size) > rank) ? rank : (N % size));\n}\n\nPetscErrorCode IGA_Distribute(PetscInt dim,\n const PetscInt size[],const PetscInt rank[],\n const PetscInt N[],PetscInt n[],PetscInt s[])\n{\n PetscInt k;\n PetscFunctionBegin;\n PetscValidIntPointer(size,2);\n PetscValidIntPointer(rank,3);\n PetscValidIntPointer(N,4);\n PetscValidIntPointer(n,5);\n PetscValidIntPointer(s,6);\n if (dim < 1 || dim > 3)\n SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,\"Number of dimensions %D must be in range [1,3]\",dim);\n for (k=0; k= size[k])\n SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,\"Partition index %D must be in range [0,%D]\",rank[k],size[k]-1);\n if (N[k] < 0)\n SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,\"Number of elements %D must be non-negative\",N[k]);\n }\n for (k=0; k\n\n/*\nvoid compute_spline_coeff(uint n, float* coeff, float* y, uint stride, float* h, float constant_h) {\n\tLinearRegion region(get_temporary_allocator());\n\t\n\tfloat* DL = TEMPORARY_ARRAY(float, n);\n\tfloat* D = TEMPORARY_ARRAY(float, n+1);\n\tfloat* DU = TEMPORARY_ARRAY(float, n);\n\tfloat* B = TEMPORARY_ARRAY(float, n + 1);\n\n\tfor (uint i = 1; i < n; i++) {\n\t\tfloat h0 = h ? h[i - 1] : constant_h;\n\t\tfloat h1 = h ? h[i] : constant_h;\n\n\t\tfloat a0 = y[(i - 1) * stride];\n\t\tfloat a1 = y[i * stride];\n\t\tfloat a2 = y[(i + 1) * stride];\n\n\t\tDL[i-1] = h0;\n\t\tD[i] = 2*(h0 + h1);\n\t\tDU[i] = h1;\n\t\tB[i] = 3/h1 * (a2 - a1) + 3/h0 * (a1 - a0);\n\t}\n\n\tB[0] = 0;\n\tB[n] = 0;\n\n\tD[0] = 1;\n\tD[n] = 1;\n\n\tDU[0] = 0;\n\tDL[n - 1] = 1;\n\t\n\tint info = LAPACKE_sgtsv(LAPACK_ROW_MAJOR, n+1, 1, DL, D, DU, B, 1);\n\tassert(info == 0);\n\n\tfor (uint i = 0; i < n; i++) {\n\t\tfloat h0 = h ? h[i] : constant_h;\n\n\t\tfloat a0 = y[i * stride];\n\t\tfloat a1 = y[(i + 1) * stride];\n\n\t\tfloat c0 = B[i];\n\t\tfloat c1 = B[i + 1];\n\n\t\tcoeff[i * 4 * stride + 0] = a0;\n\t\tcoeff[i * 4 * stride + 1] = 1 / h0 * (a1 - a0) - h0 / 3 * (2 * c0 + c1);\n\t\tcoeff[i * 4 + stride + 2] = c0;\n\t\tcoeff[i * 4 + stride + 3] = (c1 - c0) / (3*h0);\n\t}\n}\n*/\n\n//Cubic hermitian spline\nclass Spline {\n\tstruct Cubic {\n\t\tvec3 a, b, c, d;\n\t};\n\n\tvector coeff;\n\tvector lengths;\n\npublic:\n float total_length;\n \n\tSpline(slice points) {\n\t\tbuild(points);\n\t}\n \n uint points() {\n return lengths.length;\n }\n\n\tvoid build(slice points) {\n\t\tuint n = points.length - 1;\n\n\t\tcoeff.resize(n+1);\n\t\tlengths.resize(n);\n\n\t\tLinearRegion region(get_temporary_allocator());\n\n\t\tvec3* a = TEMPORARY_ARRAY(vec3, n + 1);\n\t\tfor (int i = 1; i <= n - 1; i++)\n\t\t\ta[i] = 3 * ((points[i + 1] - 2 * points[i] + points[i - 1]));\n\n\t\tfloat* l = TEMPORARY_ARRAY(float, n+1);\n\t\tfloat* mu = TEMPORARY_ARRAY(float, n + 1); \n\t\tvec3* z = TEMPORARY_ARRAY(vec3, n + 1);\n\n\t\tl[0] = l[n] = 1;\n\t\tmu[0] = 0;\n\t\tz[0] = z[n] = vec3();\n\t\tcoeff[n].c = vec3();\n\n\t\tfor (int i = 1; i <= n - 1; i++)\n\t\t{\n\t\t\tl[i] = 4 - mu[i - 1];\n\t\t\tmu[i] = 1 / l[i];\n\t\t\tz[i] = (a[i] - z[i - 1]) / l[i];\n\t\t}\n\n\t\tfor (int i = 0; i < n+1; i++)\n\t\t\tcoeff[i].a = points[i];\n\n\t\tfor (int j = n - 1; j >= 0; j--)\n\t\t{\n\t\t\tcoeff[j].c = z[j] - mu[j] * coeff[j + 1].c;\n\t\t\tcoeff[j].d = (1.0f / 3.0f) * (coeff[j + 1].c - coeff[j].c);\n\t\t\tcoeff[j].b = points[j + 1] - points[j] - coeff[j].c - coeff[j].d;\n\t\t}\n\n\t\t/*\t\t\n\t\tfloat* DL = TEMPORARY_ARRAY(float, n);\n\t\tfloat* D = TEMPORARY_ARRAY(float, n + 1);\n\t\tfloat* DU = TEMPORARY_ARRAY(float, n);\n\t\tfloat* B = TEMPORARY_ARRAY(float, n + 1);\n\n\t\tfor (uint k = 0; k < 3; k++) {\n\t\t\tfor (uint i = 1; i < n; i++) {\n\t\t\t\tfloat a0 = points[i - 1][k];\n\t\t\t\tfloat a1 = points[i][k];\n\t\t\t\tfloat a2 = points[i + 1][k];\n\n\t\t\t\tDL[i - 1] = 1.0;\n\t\t\t\tD[i] = 4.0;\n\t\t\t\tDU[i] = 1.0;\n\t\t\t\tB[i] = 3.0*(a2 - a1) + 3.0*(a1 - a0);\n\t\t\t}\n\n\t\t\tB[0] = 0; B[n] = 0;\n\t\t\tD[0] = 1; D[n] = 1;\n\n\t\t\tDL[n - 1] = 0;\n\t\t\tDU[0] = 0;\n \n if (true) {\n char spaces[256];\n for (uint i = 0; i < 256; i++) spaces[i] = ' ';\n \n for (uint i = 0; i < n+1; i++) {\n if (i == 0) printf(\"[ %.2f, %.2f,%.*s][%i] = [%f]\\n\", D[i], DU[0], (n-1)*6, spaces, i, B[i]);\n else if (i == n) printf(\"[%.*s %.2f, %.2f ][%i] = [%f]\\n\", (i-1)*6, spaces, DL[i-1], D[i], i, B[i]);\n else printf(\"[%.*s %.2f, %.2f, %.2f,%.*s][%i] = [%f]\\n\", (i-1)*6, spaces, DL[i-1], D[i], DU[i], (n-1-i)*6, spaces, i, B[i]);\n }\n }\n \n\t\t\tint info = LAPACKE_sgtsv(LAPACK_ROW_MAJOR, n + 1, 1, DL, D, DU, B, 1);\n\t\t\tassert(info == 0);\n\n\t\t\tfor (uint i = 0; i < n; i++) {\n\t\t\t\tfloat a0 = points[i][k]; \n\t\t\t\tfloat a1 = points[i + 1][k];\n\n\t\t\t\tfloat c0 = B[i];\n\t\t\t\tfloat c1 = B[i + 1];\n\n\t\t\t\tcoeff[i].a[k] = a0;\n\t\t\t\tcoeff[i].b[k] = (a1 - a0) - 1.0 / 3 * (2 * c0 + c1);\n\t\t\t\tcoeff[i].c[k] = c0;\n\t\t\t\tcoeff[i].d[k] = (c1 - c0) / 3.0;\n\t\t\t}\n\t\t}\n\t\t*/\n\n total_length = 0;\n\t\tfor (uint i = 0; i < n; i++) {\n\t\t\tlengths[i] = integrate(i,1.0);\n total_length += lengths[i];\n\t\t}\n\t}\n\n\tvec3 at_time(float t) {\n\t\tuint i = min(t, coeff.length-1);\n\t\tfloat x = t - i;\n\t\tfloat xx = x * x;\n\t\tfloat xxx = xx * x;\n\n\t\tvec3 result = coeff[i].a + coeff[i].b * x + coeff[i].c * xx + coeff[i].d * xxx;\n\t\treturn result;\n\t}\n \n vec3 tangent(float t) {\n uint i = min(t, coeff.length - 1);\n float x = t - i;\n float xx = x * x;\n \n vec3 result = coeff[i].b + 2.0f * coeff[i].c * x + 3.0f * coeff[i].d * xx;\n return normalize(result);\n }\n\n\tfloat arc_length_integrand(uint spline, float t) {\n\t\tfloat tt = t * t;\n\n\t\tvec3 result = coeff[spline].b + 2.0f * coeff[spline].c * t + 3.0f * coeff[spline].d * tt;\n\t\treturn length(result);\n\t}\n\n\tfloat integrate(uint spline, float t) {\n\t\tuint n = 16;\n\t\tfloat h = t / n;\n\t\t\n\t\tfloat XI0 = arc_length_integrand(spline, t);\n\t\tfloat XI1 = 0;\n\t\tfloat XI2 = 0;\n\n\t\tfor (uint i = 0; i < n; i++) {\n\t\t\tfloat X = i * h;\n\t\t\tif (i % 2 == 0) XI2 += arc_length_integrand(spline, X);\n\t\t\telse XI1 += arc_length_integrand(spline, X);\n\t\t}\n\n\t\tfloat XI = h * (XI0 + 2 * XI2 + 4 * XI1) / 3.0f;\n\t\treturn XI;\n\t}\n \n float const_speed_reparam(float t, float speed) {\n float desired_distance = speed * t;\n\n float distance = 0.0f;\n\n uint spline;\n for (spline = 0; spline < lengths.length; spline++) {\n float new_distance = distance + lengths[spline];\n if (new_distance >= desired_distance) break;\n\t\t\tdistance = new_distance;\n }\n \n assert(spline < lengths.length);\n float d = desired_distance - distance;\n\n float s = 0.5f;\n for (uint i = 0; i < 10; i++) {\n float arc_length = integrate(spline, s);\n float arc_speed = arc_length_integrand(spline, s);\n //printf(\"S %f, arc length %f, arc speed %f\\n\", s, arc_length, arc_speed);\n s = s - (arc_length - d) / arc_speed;\n }\n \n return spline + s;\n }\n\n\tvec3 const_speed_at_time(float t, float speed) {\n\t\treturn at_time(const_speed_reparam(t, speed));\n\t}\n};\n", "meta": {"hexsha": "d7b6dd042588529bdff46de232826ba35f88bd91", "size": 6261, "ext": "h", "lang": "C", "max_stars_repo_path": "CFD/include/numerical/spline.h", "max_stars_repo_name": "CompilerLuke/NextEngine", "max_stars_repo_head_hexsha": "aa1a8e9d9370bce004dba00854701597cab74989", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-10T18:19:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T18:19:16.000Z", "max_issues_repo_path": "CFD/include/numerical/spline.h", "max_issues_repo_name": "CompilerLuke/NextEngine", "max_issues_repo_head_hexsha": "aa1a8e9d9370bce004dba00854701597cab74989", "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": "CFD/include/numerical/spline.h", "max_forks_repo_name": "CompilerLuke/NextEngine", "max_forks_repo_head_hexsha": "aa1a8e9d9370bce004dba00854701597cab74989", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-02T06:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T16:47:57.000Z", "avg_line_length": 24.5529411765, "max_line_length": 144, "alphanum_fraction": 0.4967257627, "num_tokens": 2389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5830837750839342}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#undef __FUNCT__\n#define __FUNCT__ \"DEwk\"\nPetscErrorCode DEwk(PetscInt k, mpfr_t h, mpfr_t *wk)\n{\n PetscErrorCode ierr;\n mpfr_t kh, msinh, mcosh, piOver2, tmp;\n PetscFunctionBegin;\n \n mpfr_inits(kh, msinh, mcosh, piOver2, tmp, NULL);\n\n //init piOver2\n mpfr_const_pi(piOver2, MPFR_RNDN);\n mpfr_mul_d(piOver2, piOver2, 0.5, MPFR_RNDN);\n \n mpfr_set_d(kh, (double) k, MPFR_RNDN);\n mpfr_mul(kh, kh, h, MPFR_RNDN);\n mpfr_set(*wk, h, MPFR_RNDN);\n mpfr_sinh_cosh(msinh, mcosh, kh, MPFR_RNDN);\n mpfr_mul(msinh, msinh, piOver2, MPFR_RNDN);\n mpfr_mul(mcosh, mcosh, piOver2, MPFR_RNDN);\n mpfr_cosh(tmp, msinh, MPFR_RNDN);\n mpfr_sqr(tmp, tmp, MPFR_RNDN);\n mpfr_mul(*wk, *wk, mcosh, MPFR_RNDN);\n mpfr_div(*wk, *wk, tmp, MPFR_RNDN);\n\n PetscFunctionReturn(0);\n}\n\n\n/* have to make single exponential */\n#undef __FUNCT__\n#define __FUNCT__ \"SEwk\"\nPetscErrorCode SEwk(PetscInt k, mpfr_t h, mpfr_t *wk)\n{\n PetscErrorCode ierr;\n mpfr_t kh, msinh, mcosh, piOver2, tmp;\n PetscFunctionBegin;\n \n mpfr_inits(kh, msinh, mcosh, piOver2, tmp, NULL);\n\n //init piOver2\n mpfr_const_pi(piOver2, MPFR_RNDN);\n mpfr_mul_d(piOver2, piOver2, 0.5, MPFR_RNDN);\n \n mpfr_set_d(kh, (double) k, MPFR_RNDN);\n mpfr_mul(kh, kh, h, MPFR_RNDN);\n //printf(\"wow kh: %15.15f\\n\", mpfr_get_d(kh, MPFR_RNDN));\n mpfr_tanh(*wk, kh, MPFR_RNDN);\n //printf(\"wow wk: %15.15f\\n\", mpfr_get_d(*wk, MPFR_RNDN));\n mpfr_mul(*wk, *wk, *wk, MPFR_RNDN);\n mpfr_d_sub(*wk, 1.0, *wk, MPFR_RNDN);\n mpfr_mul(*wk, *wk, h, MPFR_RNDN);\n //mpfr_set(*wk, h, MPFR_RNDN);\n //mpfr_sinh_cosh(msinh, mcosh, kh, MPFR_RNDN);\n //mpfr_mul(msinh, msinh, piOver2, MPFR_RNDN);\n //mpfr_mul(mcosh, mcosh, piOver2, MPFR_RNDN);\n //mpfr_cosh(tmp, msinh, MPFR_RNDN);\n //mpfr_sqr(tmp, tmp, MPFR_RNDN);\n //mpfr_mul(*wk, *wk, mcosh, MPFR_RNDN);\n //mpfr_div(*wk, *wk, tmp, MPFR_RNDN);\n\n PetscFunctionReturn(0);\n}\n\n/* have to make single exponential */\n#undef __FUNCT__\n#define __FUNCT__ \"ERFwk\"\nPetscErrorCode ERFwk(PetscInt k, mpfr_t h, mpfr_t *wk)\n{\n PetscErrorCode ierr;\n mpfr_t kh, msinh, mcosh, piOver2, tmp;\n PetscFunctionBegin;\n \n mpfr_inits(kh, msinh, mcosh, piOver2, tmp, NULL);\n\n // init constant\n mpfr_const_pi(piOver2, MPFR_RNDN);\n mpfr_sqrt(piOver2, piOver2, MPFR_RNDN);\n mpfr_d_div(piOver2, 2.0, piOver2, MPFR_RNDN);\n \n mpfr_set_d(kh, (double) k, MPFR_RNDN);\n mpfr_mul(kh, kh, h, MPFR_RNDN);\n mpfr_mul(tmp, kh, kh, MPFR_RNDN);\n mpfr_mul_d(tmp, tmp, -1.0, MPFR_RNDN);\n mpfr_exp(*wk, tmp, MPFR_RNDN);\n mpfr_mul(*wk, *wk, h, MPFR_RNDN);\n mpfr_mul(*wk, *wk, piOver2, MPFR_RNDN);\n\n\n PetscFunctionReturn(0);\n}\n\n/* generates n weights spaced h apart in the positive direction */\n/* includes \"center\" n=0 weight as first entry */\n#undef __FUNCT__\n#define __FUNCT__ \"DExkwk\"\nPetscErrorCode DExkwk(PetscInt n, mpfr_t h, mpfr_t **xk, mpfr_t **wk)\n{\n PetscErrorCode ierr;\n PetscInt k;\n mpfr_t kh, msinh, mcosh, piOver2, tmp;\n PetscReal alp, bet;\n PetscInt flopCount;\n PetscFunctionBegin;\n flopCount = 0;\n \n mpfr_inits(kh, msinh, mcosh, piOver2, tmp, NULL);\n\n // init piOver2\n mpfr_const_pi(piOver2, MPFR_RNDN);\n mpfr_mul_d(piOver2, piOver2, 0.5, MPFR_RNDN); flopCount ++;\n \n \n for(k=0; k -2*prec)\n cont = 0;\n else\n mpfr_mul_d(hl, hl, 0.5, MPFR_RNDN); // make hl larger if value not small\n }\n //printf(\"hl: %15.15f\\n\", mpfr_get_d(hl, MPFR_RNDN));\n //ierr = DEwk(nPts, hl, &lwk);CHKERRQ(ierr);\n //ierr = DEwk(nPts, hr, &rwk);CHKERRQ(ierr);\n\n cont = 1;\n while(cont == 1) {\n // average hl and hr\n mpfr_add(h, hl, hr, MPFR_RNDN);\n mpfr_mul_d(h, h, 0.5, MPFR_RNDN);\n \n // calculate weight and size\n ierr = DEwk(nPts, h, &wk);CHKERRQ(ierr);\n ierr = DEwk(nPts, hl, &lwk);CHKERRQ(ierr);\n ierr = DEwk(nPts, hr, &rwk);CHKERRQ(ierr);\n mpfr_log10(swk, wk, MPFR_RNDN);\n mpfr_log10(slwk, lwk, MPFR_RNDN);\n mpfr_log10(srwk, rwk, MPFR_RNDN);\n if( mpfr_get_d(swk, MPFR_RNDN) < -2*prec)\n mpfr_set(hr, h, MPFR_RNDN);\n else\n mpfr_set(hl, h, MPFR_RNDN);\n // calculate maximum possible error\n mpfr_sub(error, slwk, srwk, MPFR_RNDN);\n mpfr_abs(error, error, MPFR_RNDN);\n if(mpfr_get_d(error, MPFR_RNDN) < tol)\n cont = 0;\n }\n \n mpfr_set(*step, h, MPFR_RNDN);\n \n mpfr_clears(wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error, NULL);\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"FindStepSizeSE\"\nPetscErrorCode FindStepSizeSE(PetscInt prec, PetscInt nPts, mpfr_t *step)\n{\n PetscErrorCode ierr;\n const PetscReal tol = 1e-25;\n mpfr_t wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error;\n PetscInt cont;\n PetscFunctionBegin;\n\n if(prec < 1) {\n printf(\"prec should be positive\\n\");\n PetscFunctionReturn(1);\n }\n \n mpfr_inits(wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error, NULL);\n\n mpfr_set_d(hl, 0.0, MPFR_RNDN);\n mpfr_set_d(hr, 2.0, MPFR_RNDN);\n\n /* make hr large enough */\n mpfr_set_d(hr, 1.0, MPFR_RNDN);\n cont = 1;\n while(cont == 1) {\n ierr = SEwk(nPts, hr, &rwk);CHKERRQ(ierr);\n mpfr_log10(srwk, rwk, MPFR_RNDN);\n if(mpfr_get_d(srwk, MPFR_RNDN) < -2*prec)\n cont = 0;\n else\n mpfr_mul_d(hr, hr, 2.0, MPFR_RNDN); // make hr larger if value not small\n }\n //printf(\"hr: %15.15f\\n\", mpfr_get_d(hr, MPFR_RNDN));\n /* make hl small enough */\n mpfr_mul_d(hl, hr, 0.5, MPFR_RNDN);\n cont = 1;\n while(cont == 1) {\n ierr = SEwk(nPts, hl, &lwk);CHKERRQ(ierr);\n mpfr_log10(slwk, lwk, MPFR_RNDN);\n if(mpfr_get_d(slwk, MPFR_RNDN) > -2*prec)\n cont = 0;\n else\n mpfr_mul_d(hl, hl, 0.5, MPFR_RNDN); // make hl larger if value not small\n }\n //printf(\"hl: %15.15f\\n\", mpfr_get_d(hl, MPFR_RNDN));\n ierr = SEwk(nPts, hl, &lwk);CHKERRQ(ierr);\n ierr = SEwk(nPts, hr, &rwk);CHKERRQ(ierr);\n //printf(\"lwk: %3.3e\\n\", mpfr_get_d(lwk, MPFR_RNDN));\n //printf(\"rwk: %3.3e\\n\", mpfr_get_d(rwk, MPFR_RNDN));\n\n cont = 1;\n while(cont == 1) {\n // average hl and hr\n mpfr_add(h, hl, hr, MPFR_RNDN);\n mpfr_mul_d(h, h, 0.5, MPFR_RNDN);\n \n // calculate weight and size\n ierr = SEwk(nPts, h, &wk);CHKERRQ(ierr);\n ierr = SEwk(nPts, hl, &lwk);CHKERRQ(ierr);\n ierr = SEwk(nPts, hr, &rwk);CHKERRQ(ierr);\n mpfr_log10(swk, wk, MPFR_RNDN);\n mpfr_log10(slwk, lwk, MPFR_RNDN);\n mpfr_log10(srwk, rwk, MPFR_RNDN);\n if( mpfr_get_d(swk, MPFR_RNDN) < -2*prec)\n mpfr_set(hr, h, MPFR_RNDN);\n else\n mpfr_set(hl, h, MPFR_RNDN);\n // calculate maximum possible error\n mpfr_sub(error, slwk, srwk, MPFR_RNDN);\n mpfr_abs(error, error, MPFR_RNDN);\n if(mpfr_get_d(error, MPFR_RNDN) < tol)\n cont = 0;\n //printf(\"h: %15.15f\\nlwk: %3.3e\\nrwk: %3.3e\\n\", mpfr_get_d(h, MPFR_RNDN), mpfr_get_d(lwk, MPFR_RNDN), mpfr_get_d(rwk, MPFR_RNDN));\n }\n \n mpfr_set(*step, h, MPFR_RNDN);\n \n mpfr_clears(wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error, NULL);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"FindStepSizeERF\"\nPetscErrorCode FindStepSizeERF(PetscInt prec, PetscInt nPts, mpfr_t *step)\n{\n PetscErrorCode ierr;\n const PetscReal tol = 1e-25;\n mpfr_t wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error;\n PetscInt cont;\n PetscFunctionBegin;\n\n if(prec < 1) {\n printf(\"prec should be positive\\n\");\n PetscFunctionReturn(1);\n }\n \n mpfr_inits(wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error, NULL);\n\n mpfr_set_d(hl, 0.0, MPFR_RNDN);\n mpfr_set_d(hr, 2.0, MPFR_RNDN);\n\n /* make hr large enough */\n mpfr_set_d(hr, 1.0, MPFR_RNDN);\n cont = 1;\n while(cont == 1) {\n ierr = ERFwk(nPts, hr, &rwk);CHKERRQ(ierr);\n mpfr_log10(srwk, rwk, MPFR_RNDN);\n if(mpfr_get_d(srwk, MPFR_RNDN) < -2*prec)\n cont = 0;\n else\n mpfr_mul_d(hr, hr, 2.0, MPFR_RNDN); // make hr larger if value not small\n }\n //printf(\"hr: %15.15f\\n\", mpfr_get_d(hr, MPFR_RNDN));\n /* make hl small enough */\n mpfr_mul_d(hl, hr, 0.5, MPFR_RNDN);\n cont = 1;\n while(cont == 1) {\n ierr = ERFwk(nPts, hl, &lwk);CHKERRQ(ierr);\n mpfr_log10(slwk, lwk, MPFR_RNDN);\n if(mpfr_get_d(slwk, MPFR_RNDN) > -2*prec)\n cont = 0;\n else\n mpfr_mul_d(hl, hl, 0.5, MPFR_RNDN); // make hl larger if value not small\n }\n //printf(\"hl: %15.15f\\n\", mpfr_get_d(hl, MPFR_RNDN));\n ierr = ERFwk(nPts, hl, &lwk);CHKERRQ(ierr);\n ierr = ERFwk(nPts, hr, &rwk);CHKERRQ(ierr);\n //printf(\"lwk: %3.3e\\n\", mpfr_get_d(lwk, MPFR_RNDN));\n //printf(\"rwk: %3.3e\\n\", mpfr_get_d(rwk, MPFR_RNDN));\n\n cont = 1;\n while(cont == 1) {\n // average hl and hr\n mpfr_add(h, hl, hr, MPFR_RNDN);\n mpfr_mul_d(h, h, 0.5, MPFR_RNDN);\n \n // calculate weight and size\n ierr = ERFwk(nPts, h, &wk);CHKERRQ(ierr);\n ierr = ERFwk(nPts, hl, &lwk);CHKERRQ(ierr);\n ierr = ERFwk(nPts, hr, &rwk);CHKERRQ(ierr);\n mpfr_log10(swk, wk, MPFR_RNDN);\n mpfr_log10(slwk, lwk, MPFR_RNDN);\n mpfr_log10(srwk, rwk, MPFR_RNDN);\n if( mpfr_get_d(swk, MPFR_RNDN) < -2*prec)\n mpfr_set(hr, h, MPFR_RNDN);\n else\n mpfr_set(hl, h, MPFR_RNDN);\n // calculate maximum possible error\n mpfr_sub(error, slwk, srwk, MPFR_RNDN);\n mpfr_abs(error, error, MPFR_RNDN);\n if(mpfr_get_d(error, MPFR_RNDN) < tol)\n cont = 0;\n //printf(\"h: %15.15f\\n\", mpfr_get_d(h, MPFR_RNDN));\n }\n //printf(\"h: %15.15f\\n\", mpfr_get_d(h, MPFR_RNDN));\n //printf(\"h: %15.15f\\nlwk: %3.3e\\nrwk: %3.3e\\n\", mpfr_get_d(h, MPFR_RNDN), mpfr_get_d(lwk, MPFR_RNDN), mpfr_get_d(rwk, MPFR_RNDN));\n mpfr_set(*step, h, MPFR_RNDN);\n \n mpfr_clears(wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error, NULL);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"DEQuad\"\nPetscErrorCode DEQuad(PetscErrorCode (*f)(mpfr_t*,mpfr_t*,void*), mpfr_t a, mpfr_t b, PetscInt prec, PetscInt nPts, PetscReal *integral, void *ctx)\n{\n PetscErrorCode ierr;\n PetscInt k;\n PetscInt nSide;\n mpfr_t alpha, beta;\n mpfr_t leftXk, rightXk;\n mpfr_t wk;\n mpfr_t *wkVals;\n mpfr_t *xkVals;\n mpfr_t lx, rx;\n mpfr_t leftFx, rightFx;\n mpfr_t pi2;\n mpfr_t kh, h;\n mpfr_t sum;\n PetscInt flopCount;\n PetscFunctionBegin;\n flopCount = 0;\n \n if(nPts % 2 == 0) {\n nSide = nPts/2; flopCount++;\n }\n if(nPts % 2 == 1) {\n nSide = (nPts-1)/2; flopCount++;\n }\n\n /* initializations */\n mpfr_inits(alpha, beta, leftXk, rightXk, wk, leftFx, rightFx, pi2, kh, h, sum, lx, rx, NULL);\n wkVals = (mpfr_t*) malloc(sizeof(mpfr_t)*(nSide+1));\n xkVals = (mpfr_t*) malloc(sizeof(mpfr_t)*(nSide+1));\n for(k=0; k\n#include \n#include \n#include \n#include \n#include \n#include \"ellipsoid.h\"\n#include \"../sphere/sphere.h\"\n#include \"ellSolv.h\"\n\n\ndouble calcEnp(EllipsoidalSystem *e, Point *point, int n, int p) {\n //if(point->type == 'c')\n //cartesianToEllipsoidal(e, point);\n int signm = 1;\n int signn = 1;\n if(point->x2 < 0)\n signm = -1;\n if(point->x3 < 0)\n signn = -1;\n double eL, eM, eN;\n calcLame(e, n, p, point->x1, signm, signn, &eL);\n calcLame(e, n, p, point->x2, signm, signn, &eM);\n calcLame(e, n, p, point->x3, signm, signn, &eN);\n\n return eL*eM*eN;\n}\n\ndouble calcGnp(EllipsoidalSystem *e, Point *positions, double *charges, int nCharges, int n, int p)\n{\n clock_t start, diff;\n int msec;\n start = clock();\n double normConstant;\n calcNormalization(e, n, p, &normConstant);\n diff = clock() - start;\n msec = diff * 1000 / CLOCKS_PER_SEC;\n //printf(\"normConstant took %d seconds and %d milliseconds\\n\", msec/1000, msec%1000);\n //double normConstant = 1.0;\n double sum = 0;\n double Enp;\n\n for(int k=0; kx2 < 0)\n signm = -1;\n if(point->x3 < 0)\n signn = -1;\n\n double enpval = calcEnp(e, point, n, p);\n double ival;\n calcI(e, n, p, point->x1, signm, signn, &ival);\n //printf(\"ENP: %15.15f\\nI: %15.15f\\n\", enpval, ival);\n return (2*n + 1) * enpval * ival;\n}\n\n\nvoid calcBnpAndCnpFromGnp(Problem *problem, int n, int p, double Gnp, double *Bnp, double *Cnp)\n{\n EllipsoidalSystem *e = problem->e;\n double Ea;\n calcLame(e, n, p, e->a, 1, 1, &Ea);\n double Ia;\n calcI(problem->e, n, p, e->a, 1, 1, &Ia);\n double Fa = (2*n + 1) * Ea * Ia;\n double EaDer;\n calcLameDerivative(e, n, p, e->a, 1, 1, &EaDer);\n double IaDer;\n calcIDerivative(e, n, p, e->a, 1, 1, &IaDer);\n double FaDer = (2*n+1) * (Ea*IaDer + EaDer*Ia); //chain rule?\n double e1 = problem->e1;\n double e2 = problem->e2;\n \n //calc Bnp\n double first = (Fa/Ea)*(e1 - e2)/(e1*e2);\n first /= (1-(e1/e2)*((EaDer*Fa)/(FaDer*Ea)));\n *Bnp = first*Gnp;\n\n //calc Cnp\n first = (e1/e2)*(EaDer/FaDer)*(*Bnp);\n first += (Gnp/e2);\n *Cnp = first;\n}\n\n\n\ndouble calcCoulomb(Problem *problem, int maxDeg, Point *r)\n{\n //FILE *fp = fopen(\"fnpnorm.txt\", \"w\");\n double Gnp, Fnp, Enp;\n double sum = 0;\n int count = 0;\n for(int n=0; n<=maxDeg; ++n) {\n for(int p=0; p < 2*n+1; ++p) {\n clock_t start = clock(), diff;\n Gnp = calcGnp(problem->e, problem->positions, problem->charges, problem->nCharges, n, p);\n diff = clock() - start;\n int msec = diff * 1000 / CLOCKS_PER_SEC;\n //printf(\"Gnp took %d seconds %d milliseconds\\n\", msec/1000, msec%1000);\n start = clock();\n Fnp = calcFnp(problem->e, r, n, p);\n diff = clock() - start;\n msec = diff * 1000 / CLOCKS_PER_SEC;\n //printf(\"Fnp took %d seconds %d milliseconds\\n\\n\", msec/1000, msec%1000);\n //fprintf(fp, \"%8.8e %8.8e\\n\", (double)count, fabs(Fnp));\n\n sum += (Gnp*Fnp)/problem->e1;\n\n count++;\n }\n printf(\"n: %d\\n\", n);\n printf(\"Gnp: %16.16f\\n\", Gnp);\n printf(\"Fnp: %16.16f\\n\", Fnp);\n //printf(\"enp: %16.16f\\n\", Enp);\n printf(\"sum: %16.16f\\n\", sum);\n \n }\n //fclose(fp);\n return sum;\n}\n\n\n\n\n\n\n\ndouble calcCoulombEllipsoidalGrid(Problem *problem, int maxDeg, Point *r, int nPoints, double *solution) {\n\n EllipsoidalSystem *e = problem->e;\n double Gnp, Bnp, Fnp, Enp, Cnp;\n for(int i=0; ie, problem->positions, problem->charges, problem->nCharges, n, p);\n calcBnpAndCnpFromGnp(problem, n, p, Gnp, &Bnp, &Cnp);\n\n for(int k=0; k= e->a) {\n\t Fnp = calcFnp(problem->e, r+k, n, p);\n\t solution[k] += Cnp*Fnp;\n\t}\n\telse {\n\t Enp = calcEnp(problem->e, r+k, n, p);\n\t solution[k] += Bnp*Enp;\n\t if(n==3 && p==2) {\n\t printf(\"do we get here2\\n\");\n\t printf(\"(%d,%d)\\n\", n, p);\n\t printf(\"Enp: %15.15f\\n\", Enp);\n\t printf(\"Bnp: %15.15f\\n\", Bnp);\n\t printf(\"\\n\");\n\t }\n\t}\n }\n\n\n\n count++;\n }\n //printf(\"n: %d\\n\", n);\n //printf(\"Gnp: %16.16f\\n\", Gnp);\n //printf(\"Cnp: %16.16f\\n\", Cnp);\n //printf(\"Fnp: %16.16f\\n\", Fnp);\n //printf(\"enp: %16.16f\\n\", Enp);\n //printf(\"sum: %16.16f\\n\", solution[0]);\n \n }\n //fclose(fp);\n return solution[0];\n}\n\n\n\n\n", "meta": {"hexsha": "ba3480c7e6b1dc7d406ebb0227345c0e8bf21783", "size": 4712, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ellipsoid/ellSolv.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/ellipsoid/ellSolv.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/ellipsoid/ellSolv.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": 24.0408163265, "max_line_length": 106, "alphanum_fraction": 0.5704584041, "num_tokens": 1830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.583037259501225}} {"text": "#include \n#include \n#include \n\ntypedef struct ornsteinuhlenbeckprocess_{\n int steps;\n double dt;\n double sigma;\n double *x;\n gsl_rng *rng;\n} OrnsteinUhlenbeckProcess;\n\nvoid OrnsteinUhlenbeckProcess_run(OrnsteinUhlenbeckProcess *self) {\n int i;\n double sgm = self->sigma * sqrt(self->dt);\n for (i = 1; i < self->steps; ++i){\n self->x[i] = (1 - self->dt) * self->x[i-1] \\\n + gsl_ran_gaussian_ziggurat(self->rng, sgm);\n }\n}\n", "meta": {"hexsha": "b8dad9f78532489c99b635c801e4f45678d9e538", "size": 480, "ext": "c", "lang": "C", "max_stars_repo_path": "lib/libcomparatist_oup.c", "max_stars_repo_name": "tkf/comparatist", "max_stars_repo_head_hexsha": "44f30077857fc96cb77539f3fe0a7e8112f86c82", "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": "lib/libcomparatist_oup.c", "max_issues_repo_name": "tkf/comparatist", "max_issues_repo_head_hexsha": "44f30077857fc96cb77539f3fe0a7e8112f86c82", "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": "lib/libcomparatist_oup.c", "max_forks_repo_name": "tkf/comparatist", "max_forks_repo_head_hexsha": "44f30077857fc96cb77539f3fe0a7e8112f86c82", "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.8571428571, "max_line_length": 67, "alphanum_fraction": 0.66875, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5829356256369969}} {"text": "#ifndef CONVOLUTION_H\n#define CONVOLUTION_H\n\n#include \n\n#include \n\n#include \n\nextern \"C\" {\n #include \n}\n\nusing namespace std;\n\n\ntemplate\nconstexpr T relu(T x) {\n return (x > 0) ? x : 0;\n}\n\ntemplate\nvoid mul_mat(T *A, double *B, double *C, size_t m, size_t k, size_t n) {\n for(size_t r = 0; r < m; r++) {\n for(size_t c = 0; c < n; c++) {\n double x = 0.0;\n for(size_t z = 0; z < k; z++) {\n x += A[r * k + z] * B[z * n + c];\n }\n C[r * n + c] = x;\n }\n }\n}\n\ntemplate\nstruct ConvolutionLayer {\n static constexpr size_t conv_size = conv_height * conv_width;\n static constexpr size_t in_map_size = in_height * in_width;\n static constexpr size_t inputs_no = in_maps * in_height * in_width;\n static constexpr size_t parameters_no = out_maps * (conv_width * conv_height * in_maps + 1);\n static constexpr size_t bias_idx = conv_width * conv_height * in_maps;\n static constexpr size_t out_height = (in_height - conv_height) / vert_stride +1;\n static constexpr size_t out_width = (in_width - conv_width) / horiz_stride + 1;\n static constexpr size_t out_map_size = out_height * out_width;\n static constexpr size_t internal_no = out_maps * out_height * out_width;\n static constexpr size_t outputs_no = out_maps * out_height * out_width;\n\n static constexpr size_t p_idx(size_t out_map, size_t in_map, size_t conv_r, size_t conv_c) {\n return out_map * (in_maps * conv_height * conv_width + 1) + in_map * (conv_height * conv_width)\n + conv_r * conv_width + conv_c;\n }\n\n static void forward(double* inputs, double * parameters, double* outputs) {\n for (size_t j = 0; j < out_maps; j++) {\n double *pj = &(parameters[j*(conv_height * conv_width * in_maps + 1)]);\n\n for (size_t out_r = 0; out_r < out_height; out_r++) {\n for (size_t out_c = 0; out_c < out_width; out_c++) {\n const size_t out_idx = j * (out_map_size) + out_r * out_width + out_c;\n double a = 0;\n for (size_t i = 0; i < in_maps; i++) {\n const size_t i_idx = i * conv_size;\n const size_t i2_idx = i * in_map_size;\n for (size_t conv_r = 0; conv_r < conv_height; conv_r++) {\n for (size_t conv_c = 0; conv_c < conv_width; conv_c++) {\n size_t p2_idx = i_idx + conv_r * conv_width + conv_c;\n size_t in_idx =\n i2_idx + (out_r * vert_stride + conv_r) * in_width + out_c * horiz_stride + conv_c;\n a += pj[p2_idx] * inputs[in_idx];\n }\n }\n }\n a += pj[bias_idx];\n outputs[out_idx] = relu(a);\n }\n }\n }\n }\n};\n\ntemplate\nstruct ConvolutionLayer2 {\n static constexpr size_t in_map_size = in_height * in_width;\n static constexpr size_t inputs_no = in_maps * in_map_size;\n static constexpr size_t out_height = (in_height - conv_height) / vert_stride +1;\n static constexpr size_t out_width = (in_width - conv_width) / horiz_stride + 1;\n static constexpr size_t out_map_size = out_height * out_width;\n static constexpr size_t internal_no = out_maps * out_map_size;\n static constexpr size_t outputs_no = out_maps * out_map_size;\n static constexpr size_t conv_size = conv_height * conv_width;\n static constexpr size_t parameters_no = out_maps * (in_maps * conv_size + 1);\n\n static constexpr size_t p_idx(size_t out_map, size_t in_map, size_t conv_r, size_t conv_c) {\n return out_map * (in_maps * conv_height * conv_width + 1) + in_map * (conv_height * conv_width)\n + conv_r * conv_width + conv_c;\n }\n\n static void forward(double* inputs, double *parameters, double* outputs) {\n double* _in = (double*) malloc(sizeof(double) * in_maps * conv_size * out_map_size);\n\n for (size_t out_r = 0; out_r < out_height; out_r++) {\n for (size_t out_c = 0; out_c < out_width; out_c++) {\n for (size_t i = 0; i < in_maps; i++) {\n for (size_t conv_r = 0; conv_r < conv_height; conv_r++) {\n for (size_t conv_c = 0; conv_c < conv_width; conv_c++) {\n size_t in_idx =\n i * in_map_size +\n (out_r * vert_stride + conv_r) * in_width +\n out_c * horiz_stride + conv_c;\n size_t row_idx = i * conv_size + conv_r * conv_width + conv_c;\n size_t _in_idx = row_idx * out_map_size + out_r * out_width + out_c;\n _in[_in_idx] = inputs[in_idx];\n }\n }\n }\n }\n }\n\n for (size_t j = 0; j < out_maps;j++) {\n double bias = parameters[(j+1) * (in_maps * conv_size + 1) - 1];\n for (size_t i = 0; i < out_map_size; i++) {\n outputs[j * out_map_size + i] = bias;\n }\n }\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n out_maps, out_map_size, in_maps * conv_size,\n 1.0, parameters, in_maps * conv_size + 1,\n _in, out_map_size,\n 1.0, outputs, out_map_size);\n\n for(size_t j = 0; j < out_maps * out_map_size; j++) {\n outputs[j] = relu(outputs[j]);\n }\n }\n};\n\n\n#endif\n", "meta": {"hexsha": "97029be348e73492f62bd8481fca8316a2fd4e0f", "size": 5427, "ext": "h", "lang": "C", "max_stars_repo_path": "convolution/src/convolution.h", "max_stars_repo_name": "tudor-berariu/cc-hacks", "max_stars_repo_head_hexsha": "0a2599b83e2eddf4b703e9c06acbb067d430117b", "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": "convolution/src/convolution.h", "max_issues_repo_name": "tudor-berariu/cc-hacks", "max_issues_repo_head_hexsha": "0a2599b83e2eddf4b703e9c06acbb067d430117b", "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": "convolution/src/convolution.h", "max_forks_repo_name": "tudor-berariu/cc-hacks", "max_forks_repo_head_hexsha": "0a2599b83e2eddf4b703e9c06acbb067d430117b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1712328767, "max_line_length": 101, "alphanum_fraction": 0.6187580615, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5829356234918046}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#define N 8\n\nint\nmain (void)\n{\n int i;\n double xi, yi;\n double x[N] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 };\n double y[N] = { 0.0, 0.0, 2.0, 0.0,-1.0,-2.0,-1.0, 0.0 };\n\n printf (\"#m=0,S=2\\n\");\n\n for (i = 0; i < N; i++)\n {\n printf (\"%g %g\\n\", x[i], y[i]);\n }\n\n printf (\"#m=1,S=0\\n\");\n\n {\n gsl_interp_accel *acc = gsl_interp_accel_alloc ();\n gsl_spline *spline = gsl_spline_alloc (gsl_interp_akima, N);\n gsl_spline_init (spline, x, y, N);\n\n for (xi = x[0]; xi < x[N-1]; xi += 0.01)\n {\n double yi = gsl_spline_eval (spline, xi, acc);\n printf (\"%g %g\\n\", xi, yi);\n }\n gsl_spline_free (spline);\n gsl_interp_accel_free(acc);\n }\n}\n", "meta": {"hexsha": "643236effa1ab406b542f64b22df97b4ea731a1c", "size": 804, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/interpolation/demo2.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/interpolation/demo2.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/interpolation/demo2.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.1, "max_line_length": 64, "alphanum_fraction": 0.5310945274, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5827579086375491}} {"text": "#include \"ridc.h\"\n#include \n#include \n#include \n#include \n\n#ifndef _BRUSSELATOR_H_\n#define _BRUSSELATOR_H_\n\nclass Brusselator_GSL : public ODE {\npublic:\n Brusselator_GSL(int my_neq, int my_nt, double my_ti, double my_tf, double my_dt) {\n neq = my_neq; \n nt = my_nt; \n ti = my_ti; \n tf = my_tf; \n dt = my_dt; \n }\n \n void rhs(double t, double *u, double *f) {\n /** user implemented rhs function, u'=rhs(t,u) \n @return (by reference) f: rhs(t,u)\n @param t current time step\n @param u solution u at time t\n @param f rhs(t,u)\n */ \n double A = 1.0;\n double B = 3.0;\n double alpha = 0.02;\n double dx = 1.0/(neq+1);\n int Nx = neq/2;\n \n f[0] = A+u[0]*u[0]*u[Nx] -(B+1.0)*u[0] +alpha/dx/dx*(u[1]-2*u[0]+1.0);\n f[Nx-1] = A+u[Nx-1]*u[Nx-1]*u[2*Nx-1] -(B+1.0)*u[Nx-1]\n + alpha/dx/dx*(1.0-2*u[Nx-1]+u[Nx-2]);\n \n f[Nx] = B*u[0]- u[0]*u[0]*u[Nx] + alpha/dx/dx*(u[Nx+1]-2*u[Nx]+3.0);\n f[2*Nx-1] = B*u[Nx-1]- u[Nx-1]*u[Nx-1]*u[2*Nx-1]\n + alpha/dx/dx*(3.0-2*u[2*Nx-1]+u[2*Nx-2]);\n \n for (int i=1; idata[i];\n\tif (std::abs(stepsize[i])>maxstepsize) {\n\t maxstepsize = std::abs(x->data[i]);\n\t}\n }\n \n // if update sufficiently small enough\n if ( maxstepsize < NEWTON_TOL) {\n\tbreak;\n }\n\n counter++;\n //error if too many steps\n if (counter > NEWTON_MAXSTEP) {\n\tfprintf(stderr,\"max Newton iterations reached\\n\");\n\texit(42);\n }\n } // end Newton iteration\n \n for (int i=0; i\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\n#undef __FUNCT__\n#define __FUNCT__ \"CoulombExact\"\nPetscErrorCode CoulombExact(PetscReal eps1, Vec srcXYZ, Vec srcMag, Vec tarXYZ, Vec sol)\n{\n PetscErrorCode ierr;\n PetscReal srcX, srcY, srcZ;\n PetscReal tarX, tarY, tarZ;\n PetscReal dx2, dy2, dz2;\n PetscReal val, mag;\n const PetscScalar *srcXYZArray;\n const PetscScalar *srcMagArray;\n const PetscScalar *tarXYZArray;\n PetscScalar *solArray;\n PetscInt nSrc, nTar;\n PetscInt i, k;\n PetscFunctionBeginUser;\n\n ierr = VecGetSize(srcMag, &nSrc);CHKERRQ(ierr);\n ierr = VecGetSize(sol, &nTar);CHKERRQ(ierr);\n\n ierr = VecGetArrayRead(srcXYZ, &srcXYZArray);CHKERRQ(ierr);\n ierr = VecGetArrayRead(tarXYZ, &tarXYZArray);CHKERRQ(ierr);\n ierr = VecGetArrayRead(srcMag, &srcMagArray);CHKERRQ(ierr);\n ierr = VecGetArray (sol , &solArray );CHKERRQ(ierr);\n for(i=0; i\n#include \n#include \n#include \n#include \n\nstatic int\njacobi_check(const size_t n, const gsl_integration_fixed_params * params)\n{\n (void) n;\n\n if (fabs(params->b - params->a) <= GSL_DBL_EPSILON)\n {\n GSL_ERROR(\"|b - a| too small\", GSL_EDOM);\n }\n else if (params->a >= params->b)\n {\n GSL_ERROR(\"lower integration limit must be smaller than upper limit\", GSL_EDOM);\n }\n else if (params->alpha <= -1.0 || params->beta <= -1.0)\n {\n GSL_ERROR(\"alpha and beta must be > -1\", GSL_EDOM);\n }\n else\n {\n return GSL_SUCCESS;\n }\n}\n\nstatic int\njacobi_init(const size_t n, double * diag, double * subdiag, gsl_integration_fixed_params * params)\n{\n const double absum = params->beta + params->alpha;\n const double abdiff = params->beta - params->alpha;\n const double a2b2 = absum * abdiff; /* beta^2 - alpha^2 */\n size_t i;\n\n /* construct the diagonal and subdiagonal elements of Jacobi matrix */\n diag[0] = abdiff/(absum + 2.0);\n subdiag[0] = 2.0*sqrt((params->alpha + 1.0)*(params->beta + 1.0)/(absum + 3.0))/(absum + 2.0);\n for (i = 1; i < n; i++)\n {\n diag[i] = a2b2 / ( (absum + 2.0*i) * (absum + 2.0*i + 2.0) );\n subdiag[i] = sqrt ( 4.0*(i + 1.0) * (params->alpha + i + 1.0) * (params->beta + i + 1.0) * (absum + i + 1.0) / ( pow((absum + 2.0*i + 2.0), 2.0) - 1.0 ) ) / ( absum + 2.0*i + 2.0 );\n }\n\n params->zemu = pow(2.0, absum + 1.0) * gsl_sf_gamma(params->alpha + 1.0) * gsl_sf_gamma(params->beta + 1.0) / gsl_sf_gamma(absum + 2.0);\n params->shft = 0.5*(params->b + params->a);\n params->slp = 0.5*(params->b - params->a);\n params->al = params->alpha;\n params->be = params->beta;\n\n return GSL_SUCCESS;\n}\n\nstatic const gsl_integration_fixed_type jacobi_type =\n{\n jacobi_check,\n jacobi_init\n};\n\nconst gsl_integration_fixed_type *gsl_integration_fixed_jacobi = &jacobi_type;\n", "meta": {"hexsha": "0c0637b05976fe844f2b141a3bfa796982d22479", "size": 2945, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/integration/jacobi.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/integration/jacobi.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/jacobi.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": 33.4659090909, "max_line_length": 187, "alphanum_fraction": 0.6617996604, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5823028499634955}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef gauge_config\n#include \"config.h\"\n#define gauge_config 1\n\n#define sq(x) ((x)*(x))\n#define cb(x) ((x)*(x)*(x))\n#endif\n\n\n// SU(3) Matrix\n// only the first two rows carries useful information (Lang p.80)\n// note that the first two rows must be orthonormal\n// use su3_normalize() for this\ntypedef struct{\n gsl_complex a1;\n gsl_complex a2;\n gsl_complex a3;\n gsl_complex b1;\n gsl_complex b2;\n gsl_complex b3;\n} su3_matrix;\n\n// SU(3) matrix methods --------------------------------------\n\n// print matrix\nvoid su3_print(const su3_matrix A){\n printf(\"%f + i*%f \\t\", GSL_REAL(A.a1), GSL_IMAG(A.a1));\n printf(\"%f + i*%f \\t\", GSL_REAL(A.a2), GSL_IMAG(A.a2));\n printf(\"%f + i*%f \\n\", GSL_REAL(A.a3), GSL_IMAG(A.a3));\n printf(\"%f + i*%f \\t\", GSL_REAL(A.b1), GSL_IMAG(A.b1));\n printf(\"%f + i*%f \\t\", GSL_REAL(A.b2), GSL_IMAG(A.b2));\n printf(\"%f + i*%f \\n\", GSL_REAL(A.b3), GSL_IMAG(A.b3));\n}\n\n// the identity matrix\nsu3_matrix su3_unit(){\n su3_matrix u;\n u.a1=GSL_COMPLEX_ONE;\n u.a2=GSL_COMPLEX_ZERO;\n u.a3=GSL_COMPLEX_ZERO;\n u.b1=GSL_COMPLEX_ZERO;\n u.b2=GSL_COMPLEX_ONE;\n u.b3=GSL_COMPLEX_ZERO;\n return u;\n}\n\n// normalize matrix\nsu3_matrix su3_norm(const su3_matrix A){\n su3_matrix result;\n // normalize first row\n double norm = sqrt(gsl_complex_abs2(A.a1)+gsl_complex_abs2(A.a2)+gsl_complex_abs2(A.a3));\n result.a1 = gsl_complex_div(A.a1,gsl_complex_rect(norm,0));\n result.a2 = gsl_complex_div(A.a2,gsl_complex_rect(norm,0));\n result.a3 = gsl_complex_div(A.a3,gsl_complex_rect(norm,0));\n\n // orthogonize second row\n gsl_complex dprod = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.b1,gsl_complex_conjugate(result.a1)),\n gsl_complex_mul(A.b2,gsl_complex_conjugate(result.a2))),\n gsl_complex_mul(A.b3,gsl_complex_conjugate(result.a3)));\n result.b1 = gsl_complex_sub(A.b1,gsl_complex_mul(result.a1,dprod));\n result.b2 = gsl_complex_sub(A.b2,gsl_complex_mul(result.a2,dprod));\n result.b3 = gsl_complex_sub(A.b3,gsl_complex_mul(result.a3,dprod));\n\n // normalize second row\n norm = sqrt(gsl_complex_abs2(result.b1)+gsl_complex_abs2(result.b2)+gsl_complex_abs2(result.b3));\n result.b1 = gsl_complex_div(result.b1,gsl_complex_rect(norm,0));\n result.b2 = gsl_complex_div(result.b2,gsl_complex_rect(norm,0));\n result.b3 = gsl_complex_div(result.b3,gsl_complex_rect(norm,0));\n return result;\n}\n\n// multiply matrices\nsu3_matrix su3_mul(const su3_matrix A, const su3_matrix B){\n su3_matrix result;\n gsl_complex w1,w2,w3;\n\n // Third row of B as a cross product (c.f. Lang p.80)\n w1 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(B.a2),gsl_complex_conjugate(B.b3)), gsl_complex_mul(gsl_complex_conjugate(B.a3),gsl_complex_conjugate(B.b2)) );\n w2 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(B.a3),gsl_complex_conjugate(B.b1)), gsl_complex_mul(gsl_complex_conjugate(B.a1),gsl_complex_conjugate(B.b3)) );\n w3 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(B.a1),gsl_complex_conjugate(B.b2)), gsl_complex_mul(gsl_complex_conjugate(B.a2),gsl_complex_conjugate(B.b1)) );\n\n result.a1 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.a1,B.a1),gsl_complex_mul(A.a2,B.b1)), gsl_complex_mul(A.a3,w1));\n result.a2 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.a1,B.a2),gsl_complex_mul(A.a2,B.b2)), gsl_complex_mul(A.a3,w2));\n result.a3 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.a1,B.a3),gsl_complex_mul(A.a2,B.b3)), gsl_complex_mul(A.a3,w3));\n\n result.b1 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.b1,B.a1),gsl_complex_mul(A.b2,B.b1)), gsl_complex_mul(A.b3,w1));\n result.b2 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.b1,B.a2),gsl_complex_mul(A.b2,B.b2)), gsl_complex_mul(A.b3,w2));\n result.b3 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.b1,B.a3),gsl_complex_mul(A.b2,B.b3)), gsl_complex_mul(A.b3,w3));\n\n return result;\n}\n\n// inverse matrix\nsu3_matrix su3_inv(const su3_matrix A){\n su3_matrix result;\n gsl_complex w1,w2,w3;\n\n // Third row of B as a cross product (c.f. Lang p.80)\n w1 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(A.a2),gsl_complex_conjugate(A.b3)), gsl_complex_mul(gsl_complex_conjugate(A.a3),gsl_complex_conjugate(A.b2)) );\n w2 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(A.a3),gsl_complex_conjugate(A.b1)), gsl_complex_mul(gsl_complex_conjugate(A.a1),gsl_complex_conjugate(A.b3)) );\n w3 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(A.a1),gsl_complex_conjugate(A.b2)), gsl_complex_mul(gsl_complex_conjugate(A.a2),gsl_complex_conjugate(A.b1)) );\n\n result.a1 = gsl_complex_sub( gsl_complex_mul(A.b2,w3), gsl_complex_mul( A.b3,w2) );\n result.a2 = gsl_complex_sub( gsl_complex_mul(A.a3,w2), gsl_complex_mul( A.a2,w3) );\n result.a3 = gsl_complex_sub( gsl_complex_mul(A.a2,A.b3), gsl_complex_mul( A.a3,A.b2) );\n\n result.b1 = gsl_complex_sub( gsl_complex_mul(A.b3,w1), gsl_complex_mul( A.b1,w3) );\n result.b2 = gsl_complex_sub( gsl_complex_mul(A.a1,w3), gsl_complex_mul( A.a3,w1) );\n result.b3 = gsl_complex_sub( gsl_complex_mul(A.a3,A.b1), gsl_complex_mul( A.a1,A.b3) );\n\n return result;\n}\n\n// generate random matrix\nsu3_matrix su3_rand(const gsl_rng* r){\n su3_matrix result;\n result.a1 = gsl_complex_rect(1,eps*(gsl_rng_uniform(r)*2-1));\n result.a2 = gsl_complex_rect(0,eps*(gsl_rng_uniform(r)*2-1));\n result.a3 = gsl_complex_rect(0,eps*(gsl_rng_uniform(r)*2-1));\n\n result.b1 = gsl_complex_rect(0,eps*(gsl_rng_uniform(r)*2-1));\n result.b2 = gsl_complex_rect(1,eps*(gsl_rng_uniform(r)*2-1));\n result.b3 = gsl_complex_rect(0,eps*(gsl_rng_uniform(r)*2-1));\n return su3_norm(result);\n}\n\ndouble su3_trace(const su3_matrix A){\n gsl_complex c3;\n c3 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(A.a1),gsl_complex_conjugate(A.b2)), gsl_complex_mul(gsl_complex_conjugate(A.a2),gsl_complex_conjugate(A.b1)) );\n\n return GSL_REAL(gsl_complex_add(gsl_complex_add(A.a1,A.b2),c3));\n}\n\n// end of SU(3) matrix methods ---------------------------------------------\n", "meta": {"hexsha": "000121a87303a3bf27dffca92327556cb623efe0", "size": 6216, "ext": "c", "lang": "C", "max_stars_repo_path": "su3/su3_matrix.c", "max_stars_repo_name": "uchuutamashi/lqcd", "max_stars_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "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": "su3/su3_matrix.c", "max_issues_repo_name": "uchuutamashi/lqcd", "max_issues_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-04-23T03:08:28.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-11T18:46:57.000Z", "max_forks_repo_path": "su3/su3_matrix.c", "max_forks_repo_name": "uchuutamashi/lqcd", "max_forks_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "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": 42.8689655172, "max_line_length": 173, "alphanum_fraction": 0.7332689833, "num_tokens": 1967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5810399281613137}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mpi.h\"\n\n//data specific parameters\n#define KMEANS 3 //number of cluster groups\n#define DIMENSIONS 4 //number of dimensions of data\n#define DATA_ROWS 150\n\n//run specific parameters\n#define THREAD_COUNT 6 //count of thread used by OpenMP\n#define FITNESS_FUNCTION fitness5 //specify fitness function used, 5 possibilities (fitness1,fitness2,...,fitness5)\n#define SWARM_SIZE (200)\n#define MAX_ITERATIONS (10000)\n#define GEN_MUTATION 4 //how many parts of genes will be mutated\n#define ELITE 4 //how many genes will be preserved without change\n\n#define REAL long double\n#define size_t int\n#define ROOT 0\n\nlong double vectors[DATA_ROWS][DIMENSIONS]; //here are stored data vectors\n\nlong double fitness[SWARM_SIZE];\nint chrom[SWARM_SIZE][DATA_ROWS];\nint new_chromosoms[SWARM_SIZE][DATA_ROWS];\n\nlong double fit_data_vectors[KMEANS][DIMENSIONS][DATA_ROWS]; //used to compute fitness\n#pragma omp threadprivate(fit_data_vectors)\nchar dataset[100];\n\n/*\n * FITNEES FUNCTION\n * fitness1 - vseobecne kriterium (VVV)\n * fitness2 - spriemerovane kovariancne matice sa pouziju na fitness (EEE)\n * fitness3 - stopa kovariancnych matic (VII)\n * fitness4 - sucet stvorcov euklidovskych vzdialenosti fitness (KMEANS)\n * fitness5 - spriemerovane stopy kovariancnych matic (EII)\n */\n\nlong double my_mean(const long double data[], const size_t stride,\n\t\tconst size_t size) {\n\tlong double mean = 0;\n\tsize_t i;\n\n\tfor (i = 0; i < size; i++) {\n\t\tmean += (data[i * stride] - mean) / (i + 1);\n\t}\n\n\treturn mean;\n}\n\nlong double _my_covariance(const long double data1[], const size_t stride1,\n\t\tconst long double data2[], const size_t stride2, const size_t n,\n\t\tconst long double mean1, const long double mean2) {\n\n\tlong double covariance = 0;\n\n\tsize_t i;\n\n\t/* find the sum of the squares */\n\tfor (i = 0; i < n; i++) {\n\t\tconst long double delta1 = (data1[i * stride1] - mean1);\n\t\tconst long double delta2 = (data2[i * stride2] - mean2);\n\t\tcovariance += (delta1 * delta2 - covariance) / (i + 1);\n\t}\n\n\treturn covariance;\n}\n\nlong double my_gsl_stats_covariance(const long double data1[],\n\t\tconst size_t stride1, const long double data2[], const size_t stride2,\n\t\tconst size_t n) {\n\tconst long double mean1 = my_mean(data1, stride1, n);\n\tconst long double mean2 = my_mean(data2, stride2, n);\n\n\treturn _my_covariance(data1, stride1, data2, stride2, n, mean1, mean2);\n}\n\nlong double my_gsl_linalg_LU_det(gsl_matrix_long_double * LU, int signum) {\n\tsize_t i, n = LU->size1;\n\tlong double det = (long double) signum;\n\n\tfor (i = 0; i < n; i++) {\n\t\tdet *= gsl_matrix_long_double_get(LU, i, i);\n\t}\n\n\treturn det;\n}\n\nvoid my_gsl_linalg_LU_decomp(gsl_matrix_long_double * A, gsl_permutation * p,\n\t\tint *signum) {\n\tif (A->size1 != A->size2) {\n\t\tprintf(\"LU decomposition requires square matrix\");\n\t} else if (p->size != A->size1) {\n\t\tprintf(\"permutation length must match matrix size\");\n\t} else {\n\t\tconst size_t N = A->size1;\n\t\tsize_t i, j, k;\n\n\t\t*signum = 1;\n\t\tgsl_permutation_init(p);\n\n\t\tfor (j = 0; j < N - 1; j++) {\n\t\t\t/* Find maximum in the j-th column */\n\n\t\t\tlong double ajj, max = fabs(gsl_matrix_long_double_get(A, j, j));\n\t\t\tsize_t i_pivot = j;\n\n\t\t\tfor (i = j + 1; i < N; i++) {\n\t\t\t\tlong double aij = fabs(gsl_matrix_long_double_get(A, i, j));\n\n\t\t\t\tif (aij > max) {\n\t\t\t\t\tmax = aij;\n\t\t\t\t\ti_pivot = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (i_pivot != j) {\n\t\t\t\tgsl_matrix_long_double_swap_rows(A, j, i_pivot);\n\t\t\t\tgsl_permutation_swap(p, j, i_pivot);\n\t\t\t\t*signum = -(*signum);\n\t\t\t}\n\n\t\t\tajj = gsl_matrix_long_double_get(A, j, j);\n\n\t\t\tif (ajj != 0.0) {\n\t\t\t\tfor (i = j + 1; i < N; i++) {\n\t\t\t\t\tlong double aij = gsl_matrix_long_double_get(A, i, j) / ajj;\n\t\t\t\t\tgsl_matrix_long_double_set(A, i, j, aij);\n\n\t\t\t\t\tfor (k = j + 1; k < N; k++) {\n\t\t\t\t\t\tlong double aik = gsl_matrix_long_double_get(A, i, k);\n\t\t\t\t\t\tlong double ajk = gsl_matrix_long_double_get(A, j, k);\n\t\t\t\t\t\tgsl_matrix_long_double_set(A, i, k, aik - aij * ajk);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nint random_int(int min_num, int max_num) {\n\tint result = 0;\n\tresult = (rand() % (max_num - min_num)) + min_num;\n\treturn result;\n}\n\nint my_ceil(float num) {\n\tint inum = (int) num;\n\tif (num == (float) inum) {\n\t\treturn inum;\n\t}\n\treturn inum + 1;\n}\n\nvoid my_export(char filename[100]) {\n\tint i;\n\tFILE *fp;\n\tfp = fopen(filename, \"w\");\n\tfor (i = 0; i < DATA_ROWS; i++) {\n\t\tfprintf(fp, \"%d\\n\", chrom[0][i] + 1);\n\t}\n\tfclose(fp);\n}\n\nlong double fitness1(int i) {\n\tint j, k, h, s;\n\tlong double det;\n\tint fit_cluster_volume[KMEANS];\n\tgsl_matrix_long_double *fit_matrix[KMEANS];\n\tgsl_permutation * p = gsl_permutation_alloc(DIMENSIONS);\n\tlong double result = 0;\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfit_cluster_volume[j] = 0;\n\t}\n\n\tfor (j = 0; j < DATA_ROWS; j++) {\n\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\t\t\tfit_data_vectors[chrom[i][j]][h][fit_cluster_volume[chrom[i][j]]] =\n\t\t\t\t\tvectors[j][h];\n\t\t}\n\n\t\tfit_cluster_volume[chrom[i][j]]++;\n\t}\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfit_matrix[j] = gsl_matrix_long_double_calloc(DIMENSIONS, DIMENSIONS);\n\t\tfor (k = 0; k < DIMENSIONS; k++) {\n\t\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\t\t\t\tgsl_matrix_long_double_set(fit_matrix[j], k, h,\n\t\t\t\t\t\tmy_gsl_stats_covariance(fit_data_vectors[j][k], 1,\n\t\t\t\t\t\t\t\tfit_data_vectors[j][h], 1,\n\t\t\t\t\t\t\t\tfit_cluster_volume[j]));\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\ts = 1;\n\t\tmy_gsl_linalg_LU_decomp(fit_matrix[j], p, &s);\n\t\tdet = my_gsl_linalg_LU_det(fit_matrix[j], s);\n\t\tif (det != 0.0) {\n\t\t\tresult += gsl_sf_log_abs(det) * (double) fit_cluster_volume[j];\n\t\t}\n\t\tgsl_matrix_long_double_free(fit_matrix[j]);\n\t}\n\treturn result;\n}\n\nlong double fitness2(int i) {\n\tint j, k, h, s;\n\tlong double m, det;\n\tint fit_cluster_volume[KMEANS];\n\tgsl_matrix_long_double *fit_matrix[KMEANS];\n\tgsl_matrix_long_double *fit_reuslt_matrix;\n\tgsl_permutation * p = gsl_permutation_alloc(DIMENSIONS);\n\tlong double result = 0;\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfit_cluster_volume[j] = 0;\n\t}\n\n\tfor (j = 0; j < DATA_ROWS; j++) {\n\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\t\t\tfit_data_vectors[chrom[i][j]][h][fit_cluster_volume[chrom[i][j]]] =\n\t\t\t\t\tvectors[j][h];\n\t\t}\n\n\t\tfit_cluster_volume[chrom[i][j]]++;\n\t}\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfit_matrix[j] = gsl_matrix_long_double_calloc(DIMENSIONS, DIMENSIONS);\n\t\tfor (k = 0; k < DIMENSIONS; k++) {\n\t\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\t\t\t\tgsl_matrix_long_double_set(fit_matrix[j], k, h,\n\t\t\t\t\t\tmy_gsl_stats_covariance(fit_data_vectors[j][k], 1,\n\t\t\t\t\t\t\t\tfit_data_vectors[j][h], 1,\n\t\t\t\t\t\t\t\tfit_cluster_volume[j]));\n\t\t\t}\n\t\t}\n\t}\n\n\tfit_reuslt_matrix = gsl_matrix_long_double_calloc(DIMENSIONS, DIMENSIONS);\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfor (k = 0; k < DIMENSIONS; k++) {\n\t\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\n\t\t\t\tm = gsl_matrix_long_double_get(fit_reuslt_matrix, k, h);\n\t\t\t\tm += fit_cluster_volume[j]\n\t\t\t\t\t\t* gsl_matrix_long_double_get(fit_matrix[j], k, h);\n\t\t\t\tgsl_matrix_long_double_set(fit_reuslt_matrix, k, h, m);\n\t\t\t}\n\t\t}\n\t\tgsl_matrix_long_double_free(fit_matrix[j]);\n\t}\n\n\tfor (k = 0; k < DIMENSIONS; k++) {\n\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\t\t\tm = gsl_matrix_long_double_get(fit_reuslt_matrix, k, h);\n\t\t\tm = m / (double) DATA_ROWS;\n\t\t\tgsl_matrix_long_double_set(fit_reuslt_matrix, k, h, m);\n\t\t}\n\t}\n\n\ts = 1;\n\tmy_gsl_linalg_LU_decomp(fit_reuslt_matrix, p, &s);\n\tdet = my_gsl_linalg_LU_det(fit_reuslt_matrix, s);\n\tif (det != 0.0) {\n\t\tresult += gsl_sf_log_abs(det);\n\t}\n\tgsl_matrix_long_double_free(fit_reuslt_matrix);\n\treturn result;\n}\n\nlong double fitness3(int i) {\n\tint j, k, h;\n\tint fit_cluster_volume[KMEANS];\n\tgsl_matrix_long_double *fit_matrix[KMEANS];\n\tlong double result = 0;\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfit_cluster_volume[j] = 0;\n\t}\n\n\tfor (j = 0; j < DATA_ROWS; j++) {\n\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\t\t\tfit_data_vectors[chrom[i][j]][h][fit_cluster_volume[chrom[i][j]]] =\n\t\t\t\t\tvectors[j][h];\n\t\t}\n\n\t\tfit_cluster_volume[chrom[i][j]]++;\n\t}\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfit_matrix[j] = gsl_matrix_long_double_calloc(DIMENSIONS, DIMENSIONS);\n\t\tfor (k = 0; k < DIMENSIONS; k++) {\n\t\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\t\t\t\tgsl_matrix_long_double_set(fit_matrix[j], k, h,\n\t\t\t\t\t\tmy_gsl_stats_covariance(fit_data_vectors[j][k], 1,\n\t\t\t\t\t\t\t\tfit_data_vectors[j][h], 1,\n\t\t\t\t\t\t\t\tfit_cluster_volume[j]));\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfor (k = 0; k < DIMENSIONS; k++) {\n\t\t\tresult += gsl_matrix_long_double_get(fit_matrix[j], k, k);\n\t\t}\n\t\tgsl_matrix_long_double_free(fit_matrix[j]);\n\t}\n\treturn result;\n}\n\nlong double fitness4(int agent) {\n\tint i, j, v;\n\tint weight_matrix[DATA_ROWS][KMEANS];\n\tlong double center_matrix[KMEANS][DIMENSIONS];\n\tlong double sum_w;\n\tlong double sum_wx;\n\tlong double result = 0;\n\n\tfor (i = 0; i < DATA_ROWS; i++) {\n\t\tfor (j = 0; j < KMEANS; j++) {\n\t\t\tif (chrom[agent][i] == j) {\n\t\t\t\tweight_matrix[i][j] = 1;\n\t\t\t} else {\n\t\t\t\tweight_matrix[i][j] = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfor (v = 0; v < DIMENSIONS; v++) {\n\t\t\tsum_w = 0.0;\n\t\t\tfor (i = 0; i < DATA_ROWS; i++) {\n\t\t\t\tsum_w += weight_matrix[i][j];\n\t\t\t}\n\n\t\t\tsum_wx = 0.0;\n\t\t\tfor (i = 0; i < DATA_ROWS; i++) {\n\t\t\t\tsum_wx += weight_matrix[i][j] * vectors[i][v];\n\t\t\t}\n\n\t\t\tcenter_matrix[j][v] = sum_wx / sum_w;\n\t\t}\n\t}\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfor (i = 0; i < DATA_ROWS; i++) {\n\t\t\tsum_w = 0.0;\n\t\t\tfor (v = 0; v < DIMENSIONS; v++) {\n\t\t\t\tsum_w += weight_matrix[i][j]\n\t\t\t\t\t\t* ((vectors[i][v] - center_matrix[j][v])\n\t\t\t\t\t\t\t\t* (vectors[i][v] - center_matrix[j][v]));\n\t\t\t}\n\t\t\tresult += sqrt(sum_w);\n\n\t\t}\n\t}\n\treturn result;\n}\n\nlong double fitness5(int i) {\n\tint j, k, h;\n\tlong double m;\n\tint fit_cluster_volume[KMEANS];\n\tgsl_matrix_long_double *fit_matrix[KMEANS];\n\tgsl_matrix_long_double *fit_reuslt_matrix;\n\tlong double result = 0;\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfit_cluster_volume[j] = 0;\n\t}\n\n\tfor (j = 0; j < DATA_ROWS; j++) {\n\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\t\t\tfit_data_vectors[chrom[i][j]][h][fit_cluster_volume[chrom[i][j]]] =\n\t\t\t\t\tvectors[j][h];\n\t\t}\n\n\t\tfit_cluster_volume[chrom[i][j]]++;\n\t}\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfit_matrix[j] = gsl_matrix_long_double_calloc(DIMENSIONS, DIMENSIONS);\n\t\tfor (k = 0; k < DIMENSIONS; k++) {\n\t\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\t\t\t\tgsl_matrix_long_double_set(fit_matrix[j], k, h,\n\t\t\t\t\t\tmy_gsl_stats_covariance(fit_data_vectors[j][k], 1,\n\t\t\t\t\t\t\t\tfit_data_vectors[j][h], 1,\n\t\t\t\t\t\t\t\tfit_cluster_volume[j]));\n\t\t\t}\n\t\t}\n\t}\n\n\tfit_reuslt_matrix = gsl_matrix_long_double_calloc(DIMENSIONS, DIMENSIONS);\n\n\tfor (j = 0; j < KMEANS; j++) {\n\t\tfor (k = 0; k < DIMENSIONS; k++) {\n\t\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\n\t\t\t\tm = gsl_matrix_long_double_get(fit_reuslt_matrix, k, h);\n\t\t\t\tm += fit_cluster_volume[j]\n\t\t\t\t\t\t* gsl_matrix_long_double_get(fit_matrix[j], k, h);\n\t\t\t\tgsl_matrix_long_double_set(fit_reuslt_matrix, k, h, m);\n\t\t\t}\n\t\t}\n\t\tgsl_matrix_long_double_free(fit_matrix[j]);\n\t}\n\n\tfor (k = 0; k < DIMENSIONS; k++) {\n\t\tfor (h = 0; h < DIMENSIONS; h++) {\n\t\t\tm = gsl_matrix_long_double_get(fit_reuslt_matrix, k, h);\n\t\t\tm = m / (double) DATA_ROWS;\n\t\t\tgsl_matrix_long_double_set(fit_reuslt_matrix, k, h, m);\n\t\t}\n\t}\n\n\tfor (k = 0; k < DIMENSIONS; k++) {\n\t\tresult += gsl_matrix_long_double_get(fit_reuslt_matrix, k, k);\n\t}\n\tgsl_matrix_long_double_free(fit_reuslt_matrix);\n\n\treturn result;\n}\n\nvoid quicksort(long double list[], int ch[][DATA_ROWS], int n) {\n\tint i, j;\n\tlong double pivot;\n\tlong double temp;\n\tint temp_ch[DATA_ROWS];\n\n\tif (n < 2)\n\t\treturn;\n\tpivot = list[n / 2];\n\tfor (i = 0, j = n - 1;; i++, j--) {\n\t\twhile (list[i] < pivot)\n\t\t\ti++;\n\t\twhile (pivot < list[j])\n\t\t\tj--;\n\t\tif (i >= j)\n\t\t\tbreak;\n\t\t//swap\n\t\ttemp = list[i];\n\t\tlist[i] = list[j];\n\t\tlist[j] = temp;\n\t\tmemcpy(&temp_ch, &ch[i][0], sizeof(int) * DATA_ROWS);\n\t\tmemcpy(&ch[i][0], &ch[j][0], sizeof(int) * DATA_ROWS);\n\t\tmemcpy(&ch[j][0], &temp_ch, sizeof(int) * DATA_ROWS);\n\n\t}\n\tquicksort(list, ch, i);\n\tquicksort(list + i, ch + i, n - i);\n}\n\nint *int_array_2dto1d(int array[][DATA_ROWS], int first_dimension,\n\t\tint second_dimension) {\n\tint i, j;\n\tint *subarray = malloc(sizeof(int) * first_dimension * second_dimension);\n\tfor (i = 0; i < first_dimension; i++) {\n\t\tfor (j = 0; j < second_dimension; j++) {\n\t\t\tsubarray[i * second_dimension + j] = array[i][j];\n\t\t}\n\t}\n\treturn subarray;\n}\n\nvoid int_array_1dto2d(int *array, int solver, int elements_per_proc,\n\t\tint first_dimension, int second_dimension) {\n\tint i, j;\n\tfor (i = 0; i < first_dimension; i++) {\n\t\tfor (j = 0; j < second_dimension; j++) {\n\t\t\tchrom[solver * elements_per_proc + i][j] = array[i\n\t\t\t\t\t* second_dimension + j];\n\t\t}\n\t}\n}\n\nint main(int argc, char *argv[]) {\n\tint i, j, k, h, it;\n\n\tint temp_ch[DATA_ROWS];\n\tint *sub_chrom;\n\tint * chrom1d = NULL;\n\tlong double *sub_fitness;\n\n\tunsigned long long int mating_h[SWARM_SIZE];\n\tunsigned long long int max_mating = 0;\n\tint mates[SWARM_SIZE];\n\n\tint r1, r2;\n\n\ttime_t t, tt;\n\n\tint solver, solvers_count;\n\tMPI_Init(&argc, &argv);\n\tMPI_Comm_rank(MPI_COMM_WORLD, &solver);\n\tMPI_Comm_size(MPI_COMM_WORLD, &solvers_count);\n\n\tMPI_Datatype my_type_scatter;\n\tMPI_Type_contiguous(DATA_ROWS, MPI_INT, &my_type_scatter);\n\tMPI_Type_commit(&my_type_scatter);\n\n\tif (SWARM_SIZE % 2 == 1) {\n\t\tprintf(\"SWARM SIZE need to be dividable/partible by 2\\n\");\n\t\texit(1);\n\t}\n\n\tif (argc >= 2) {\n\t\tstrcpy(dataset, argv[1]);\n\t} else {\n\t\tprintf(\"Program argument (dataset to read) not found.\\n\");\n\t\texit(1);\n\t}\n\n\tif (SWARM_SIZE % solvers_count != 0) {\n\t\tprintf(\n\t\t\t\t\"SWARM_SIZE need to be divadable/partible by count of mpi solvers\\n\");\n\t\texit(1);\n\t}\n\n\tsrand(time(NULL));\n\tomp_set_num_threads(THREAD_COUNT);\n\n\tif (solver == ROOT) {\n\t\tfor (i = 0; i < SWARM_SIZE / 2; i++) {\n\t\t\tmating_h[i] = gsl_pow_int((SWARM_SIZE / 2 - i), 5);\n\t\t\tmax_mating += mating_h[i];\n\t\t\tmating_h[i + SWARM_SIZE / 2] = 0;\n\t\t}\n\t}\n\n//read data\n\tFILE *fp;\n\tchar *token;\n\tfp = fopen(dataset, \"r\");\n\n\tif (fp != NULL) {\n\t\tint lineNumber = 0;\n\t\tchar line[1024];\n\t\twhile (fgets(line, sizeof line, fp) != NULL) {\n\t\t\ttoken = strtok(line, \",\");\n\t\t\tfor (i = 0; i < DIMENSIONS - 1; i++) {\n\t\t\t\tvectors[lineNumber][i] = atof(token);\n\t\t\t\ttoken = strtok(NULL, \",\");\n\t\t\t}\n\t\t\tvectors[lineNumber][DIMENSIONS - 1] = atof(token);\n\t\t\tlineNumber++;\n\t\t}\n\t\tfclose(fp);\n\t} else {\n\t\tprintf(\"%s\\n\", strerror(errno));\n\t\texit(1);\n\t}\n//end of read data\n\n\ttime(&t);\n\n//Generate initial population.\n\tif (solver == ROOT) {\n\t\tfor (i = 0; i < SWARM_SIZE; i++) {\n\t\t\tfor (j = 0; j < DATA_ROWS; j++) {\n\t\t\t\tchrom[i][j] = random_int(0, KMEANS);\n\t\t\t}\n\t\t}\n\t}\n\n\t//Compute fitness of each chromosome.\n#pragma omp parallel for shared(i,fitness)\n\tfor (i = 0; i < SWARM_SIZE; i++) {\n\t\tfitness[i] = FITNESS_FUNCTION(i);\n\t}\n\n\tquicksort(fitness, chrom, SWARM_SIZE);\n\n\tfor (it = 0; it < MAX_ITERATIONS; it++) {\n\t\t//Natural selection. Select mates.\n\t\tif (solver == ROOT) {\n\t\t\tfor (i = 0; i < SWARM_SIZE; i++) {\n\t\t\t\tj = random_int(1, max_mating);\n\t\t\t\th = 0;\n\t\t\t\tk = mating_h[h];\n\t\t\t\twhile (j > k) {\n\t\t\t\t\tk += mating_h[++h];\n\t\t\t\t}\n\t\t\t\tmates[i] = h;\n\t\t\t}\n\t\t}\n\n\t\t//Mating\n\t\tif (solver == ROOT) {\n\t\t\tfor (i = 0; i < SWARM_SIZE; i++) {\n\t\t\t\tdo {\n\t\t\t\t\tr1 = random_int(0, DATA_ROWS);\n\t\t\t\t\tr2 = random_int(0, DATA_ROWS);\n\t\t\t\t} while (r1 == r2);\n\n\t\t\t\tif (r1 < r2) {\n\t\t\t\t\tj = r1;\n\t\t\t\t\tk = r2;\n\t\t\t\t} else {\n\t\t\t\t\tj = r2;\n\t\t\t\t\tk = r1;\n\t\t\t\t}\n\n\t\t\t\t//first kid\n\t\t\t\tmemcpy(&temp_ch[0], &chrom[mates[i]][0], j * sizeof(int));\n\t\t\t\tmemcpy(&temp_ch[j], &chrom[mates[i + 1]][j],\n\t\t\t\t\t\t(k - j) * sizeof(int));\n\t\t\t\tmemcpy(&temp_ch[k], &chrom[mates[i]][k],\n\t\t\t\t\t\t(DATA_ROWS - k) * sizeof(int));\n\t\t\t\tmemcpy(new_chromosoms[i], temp_ch, DATA_ROWS * sizeof(int));\n\n\t\t\t\t//second kid\n\t\t\t\tmemcpy(&temp_ch[0], &chrom[mates[i + 1]][0], j * sizeof(int));\n\t\t\t\tmemcpy(&temp_ch[j], &chrom[mates[i]][j], (k - j) * sizeof(int));\n\t\t\t\tmemcpy(&temp_ch[k], &chrom[mates[i + 1]][k],\n\t\t\t\t\t\t(DATA_ROWS - k) * sizeof(int));\n\t\t\t\tmemcpy(new_chromosoms[i + 1], temp_ch, DATA_ROWS * sizeof(int));\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\n\t\t//copy new population\n\t\tif (solver == ROOT) {\n\t\t\tfor (i = ELITE; i < SWARM_SIZE; i++) {\n\t\t\t\tmemcpy(&chrom[i], &new_chromosoms[i], sizeof(int) * DATA_ROWS);\n\t\t\t}\n\t\t}\n\n\t\t//Mutation.\n\t\tif (solver == ROOT) {\n\t\t\tfor (i = ELITE; i < SWARM_SIZE; i++) {\n\t\t\t\tfor (j = 0; j < GEN_MUTATION; j++) {\n\t\t\t\t\tk = random_int(0, DATA_ROWS);\n\t\t\t\t\tchrom[i][k] = random_int(0, KMEANS);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//mpi section\n\t\tif (solver == ROOT) {\n\t\t\tchrom1d = int_array_2dto1d(chrom, SWARM_SIZE, DATA_ROWS);\n\t\t}\n\n\t\tsub_chrom = malloc(\n\t\t\t\tsizeof(int) * (SWARM_SIZE / solvers_count) * DATA_ROWS);\n\n\n\t\tMPI_Scatter(chrom1d,\n\t\tSWARM_SIZE / solvers_count, my_type_scatter, sub_chrom,\n\t\tSWARM_SIZE / solvers_count, my_type_scatter,\n\t\tROOT,\n\t\tMPI_COMM_WORLD);\n\n\t\tint_array_1dto2d(sub_chrom, solver, SWARM_SIZE / solvers_count,\n\t\t\t\tSWARM_SIZE / solvers_count, DATA_ROWS);\n\t\tsub_fitness = malloc(\n\t\t\t\tsizeof(long double) * (SWARM_SIZE / solvers_count));\n\n\n\t\t//Compute fitness of each chromosome.\n#pragma omp parallel for shared(i,fitness,sub_fitness)\n\t\tfor (i = solver * (SWARM_SIZE / solvers_count);\n\t\t\t\ti\n\t\t\t\t\t\t< solver * (SWARM_SIZE / solvers_count)\n\t\t\t\t\t\t\t\t+ (SWARM_SIZE / solvers_count); i++) {\n\t\t\tsub_fitness[i - solver * (SWARM_SIZE / solvers_count)] =\n\t\t\t\t\tFITNESS_FUNCTION(i);\n\t\t}\n\n\t\tMPI_Gather(sub_fitness,\n\t\tSWARM_SIZE / solvers_count,\n\t\tMPI_LONG_DOUBLE, fitness,\n\t\tSWARM_SIZE / solvers_count,\n\t\tMPI_LONG_DOUBLE,\n\t\tROOT,\n\t\tMPI_COMM_WORLD);\n\n\n\t\tfree(sub_chrom);\n\t\tfree(sub_fitness);\n\t\tif (solver == ROOT && chrom1d != NULL) {\n\t\t\tfree(chrom1d);\n\t\t}\n\t\t//end of mpi section\n\n\t\t//Order population\n\t\tif (solver == ROOT) {\n\t\t\tquicksort(fitness, chrom, SWARM_SIZE);\n\t\t}\n\t}\n\n\tif (solver == ROOT) {\n\n\t\ttime(&tt);\n\t\tprintf(\"Program bezal %.f sekund.\\n\", difftime(tt, t));\n\n\t\tprintf(\"fitness: %Lf\\n\", fitness[0]);\n\n\t\tif (argc >= 3) {\n\t\t\tmy_export(argv[2]);\n\t\t} else {\n\t\t\tmy_export(\"/home/lukas/workspace_parallel/mpi_gen/export.txt\");\n\t\t}\n\n\t\tprintf(\"SWARM SIZE: %d\\n\", SWARM_SIZE);\n\t\tprintf(\"MAX_ITERATIONS: %d\\n\", MAX_ITERATIONS);\n\t\tprintf(\"GEN_MUTATION: %d\\n\", GEN_MUTATION);\n\t\tprintf(\"ELITE: %d\\n\", ELITE);\n\t\tprintf(\"DIMENSIONS: %d\\n\", DIMENSIONS);\n\t\tprintf(\"KMEANS: %d\\n\", KMEANS);\n\t\tprintf(\"THREAD_COUNT per instance: %d\\n\", THREAD_COUNT);\n\t\tprintf(\"mpi solvers_count: %d\\n\", solvers_count);\n\t\tprintf(\" FITNESS_FUNCTION \");\n\n\t}\n\n\tMPI_Finalize();\n\n\treturn 0;\n\n}\n", "meta": {"hexsha": "a1be0ffee4ddd139fcb04383082a2742ef3eeb1f", "size": 18294, "ext": "c", "lang": "C", "max_stars_repo_path": "Impl of clus alg/GenClust/MPI_GenClust.c", "max_stars_repo_name": "PetoLau/GenClust", "max_stars_repo_head_hexsha": "7dbf99a958fea4bd10b0bbd0b112fd81059c6a00", "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": "Impl of clus alg/GenClust/MPI_GenClust.c", "max_issues_repo_name": "PetoLau/GenClust", "max_issues_repo_head_hexsha": "7dbf99a958fea4bd10b0bbd0b112fd81059c6a00", "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": "Impl of clus alg/GenClust/MPI_GenClust.c", "max_forks_repo_name": "PetoLau/GenClust", "max_forks_repo_head_hexsha": "7dbf99a958fea4bd10b0bbd0b112fd81059c6a00", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6218034993, "max_line_length": 115, "alphanum_fraction": 0.630643927, "num_tokens": 6130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5809303394170349}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"ellipsoid.h\"\n#include \"MPFReigs.h\"\n\nextern void dgeev_(char *jobvl, char *jobvr, int *N, double *A, int *lda, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, double *work, int *lwork, int *info);\n\nextern void dgetrs_(char *trans, int *n, int *nrhs, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info);\n\nextern void dgetrf_(int *M, int *N, double *A, int *lda, int *ipiv, int *info);\n\nstatic double max(double a, double b) {\n if( a > b)\n return a;\n return b;\n}\n\nstatic double min(double a, double b) {\n if( a > b )\n return b;\n return a;\n}\n\nvoid matTranspose(double *A, int n) {\n double *cpy = (double*) malloc(sizeof(double)*n*n);\n memcpy(cpy, A, sizeof(double)*n*n);\n for(int i=0; iDconsts = NULL;\n s->Rconsts = NULL;\n s->normConstants = NULL;\n s->DmaxN = 0;\n s->RmaxN = 0;\n\n //default init Romain constants to order 40\n int N = 56;\n \n s->a = a;\n s->b = b;\n s->c = c;\n\n s->precision = precision;\n mpfr_set_default_prec(4*precision);\n \n mpfr_t temp; \n mpfr_init(temp);\n \n s->h2 = a*a-b*b;\n s->h = sqrt(s->h2);\n s->k2 = a*a-c*c;\n s->k = sqrt(s->k2); flopCount += 8;\n\n mpfr_inits2(4*s->precision, s->hp_h2, s->hp_h, s->hp_k2, s->hp_k, NULL);\n //calculates high precision h2\n mpfr_set_d(s->hp_h2, b, MPFR_RNDN);\n mpfr_mul_d(s->hp_h2, s->hp_h2, b, MPFR_RNDN);\n mpfr_set_d(temp, a, MPFR_RNDN);\n mpfr_mul_d(temp, temp, a, MPFR_RNDN);\n mpfr_sub(s->hp_h2, temp, s->hp_h2, MPFR_RNDN); flopCount += 3;\n\n //calculates high precision h\n mpfr_sqrt(s->hp_h, s->hp_h2, MPFR_RNDN); flopCount += 1;\n\n //calculates high precision k2\n mpfr_set_d(s->hp_k2, c, MPFR_RNDN);\n mpfr_mul_d(s->hp_k2, s->hp_k2, c, MPFR_RNDN);\n mpfr_sub(s->hp_k2, temp, s->hp_k2, MPFR_RNDN); flopCount += 2;\n \n //calculates high precision k\n mpfr_sqrt(s->hp_k, s->hp_k2, MPFR_RNDN); flopCount += 1;\n\n\n //initializes all the variables for integrate.\n mpfr_inits2(4*s->precision, s->alpha, s->beta, s->h_step, s->sum, s->osum, s->psum, s->yk, s->wk, s->lx, s->rx, s->tmp, s->maxTerm, s->curTerm, s->pi2, s->kh, s->msinh, s->mcosh, s->lval, s->rval, NULL);\n\n //initialize other temp variables\n mpfr_inits2(4*s->precision, s->temp1, s->temp2, s->temp3, s->tempa, s->tempb, s->endpt, NULL);\n\n //constants\n mpfr_inits2(4*s->precision, s->mpfrzero, s->mpfrone, NULL);\n mpfr_set_d(s->mpfrzero, 0.0, MPFR_RNDN);\n mpfr_set_d(s->mpfrone , 1.0, MPFR_RNDN);\n\n\n ierr = initRomainConstsToOrderN(s, N);CHKERRQ(ierr);\n\n ierr = PetscLogFlops(flopCount);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\nvoid ellipsoidInitToOrderN(EllipsoidalSystem *s, int N)\n{\n s->Dconsts = (double***) malloc(sizeof(double**)*(N+1));\n s->normConstants = (double**) malloc(sizeof(double*)*(N+1));\n s->tVals = (char**) malloc(sizeof(char*)*(N+1));\n s->tpVals = (int**) malloc(sizeof(int* )*(N+1));\n for(int n=0; nDconsts[n] = (double**) malloc(sizeof(double*)*(2*n+1));\n s->normConstants[n] = (double*) malloc(sizeof(double)*(2*n+1));\n s->tVals[n] = (char*) malloc(sizeof(char)*(2*n+1));\n s->tpVals[n] = (int *) malloc(sizeof(int) *(2*n+1));\n }\n \n //loop over n\n for(int n=0; n<=N; ++n) {\n getCoefsK(s, n, s->Dconsts[n]);\n if(n != 0) {\n getCoefsL(s, n, s->Dconsts[n] + (n/2)+1);\n getCoefsM(s, n, s->Dconsts[n] + (n/2)+1 + (n+1)/2);\n if(n != 1) {\n\tgetCoefsN(s, n, s->Dconsts[n] + (n/2)+1 + (n+1)/2 + (n+1)/2);\n }\n }\n \n \n //loop over p\n for(int p=0; p<2*n+1; ++p) {\n s->tVals [n][p] = getLameTypeT (n, p);\n s->tpVals[n][p] = getLameTypeTp(n, p);\n }\n }\n \n}\n\nvoid printMatrix(double *M, int matSize) {\n for(int n=0; nh2 + s->k2;\n double beta = s->h2 * s->k2;\n\n //initialize matrix and tridiagonals\n double *M = (double*) malloc(sizeof(double)*matSize*matSize);\n double *d = (double*) malloc(sizeof(double)*matSize);\n double *f = (double*) malloc(sizeof(double)*(matSize-1));\n double *g = (double*) malloc(sizeof(double)*(matSize-1));\n\n flopCount = 2;\n //construct the diagonal (size matSize)\n for(int i=1; i<=matSize; ++i)\n d[i-1] = (n - 2*i + 2)*(n - 2*i + 2);\n flopCount += 7*matSize;\n //construct above and below diagonal (size matSize-1)\n for(int i=1; ih2 + s->k2;\n double beta = s->h2 * s->k2;\n\n //initialize matrix and tridiagonals\n double *M = (double*) malloc(sizeof(double)*matSize*matSize);\n double *d = (double*) malloc(sizeof(double)*matSize);\n double *f = (double*) malloc(sizeof(double)*(matSize-1));\n double *g = (double*) malloc(sizeof(double)*(matSize-1));\n\n //construct the diagonal (size matSize)\n for(int i=1; i<=matSize; ++i)\n d[i-1] = (n - 2*i + 1)*(n - 2*i + 1) + (s->k2/alpha)*(2*n - 4*i + 3);\n //construct above and below diagonal (size matSize-1)\n for(int i=1; ik2 - 2*sqrt((alpha+s->k2)*(alpha+s->k2) - 5*beta)));\n \n double pj;\n //loop over each root\n for(int p=0; pk2)/(2*(2*n-1));\n for(int k=2; kk2) * coefs[p][k-1]\n\t\t + beta*(n - 2*k + 5)*(n - 2*k + 4)*coefs[p][k-2])/(2*(k - 1)*(2*n - 2*k + 3));\n }\n } \n \n}\n\n\nvoid getCoefsM(EllipsoidalSystem *s, int n, double **coefs) {\n int wow = 1;\n wow = wow/2;\n}\nvoid getCoefsN(EllipsoidalSystem *s, int n, double **coefs) {\n int wow = 1;\n wow = wow/2;\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"calcLame2\"\nPetscErrorCode calcLame2(EllipsoidalSystem *s, int n, int p, double l, double *sol)\n{\n PetscErrorCode ierr;\n PetscInt flopCount;\n PetscFunctionBegin;\n flopCount = 0;\n \n char t = getLameTypeT(n, p);\n *sol = 0;\n if (t == 'K') {\n int r = n/2;\n for(int k=0; k <= r; ++k) {\n *sol += s->Dconsts[n][p][k] * pow(l,n - 2*k); flopCount += 2;\n }\n }\n if (t == 'L') {\n int r = (n+1)/2;\n for(int k=0; k <= r-1; ++k) {\n *sol += s->Dconsts[n][p][k] * pow(l, n - 1 - 2*k); flopCount += 2;\n }\n *sol *= sqrt(fabs(l*l - s->h2)); flopCount += 3;\n }\n\n\n ierr = PetscLogFlops(flopCount);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"ellipsoidToCartesian\"\nPetscErrorCode ellipsoidToCartesian(EllipsoidalSystem *s, Point *p)\n{\n PetscErrorCode ierr;\n\n\n PetscFunctionBegin;\n if(p->type != 'c') {\n double h2 = s->h2;\n double k2 = s->k2;\n \n double l = p->x1;\n double m = p->x2;\n double n = p->x3;\n\n //Romain (7)\n p->x1 = sqrt((l * l * m * m * n * n)/(h2 * k2));\n p->x2 = sqrt(((l * l - h2) * (m * m - h2) * (h2-n * n)) / (h2 * (k2 - h2)));\n p->x3 = sqrt(((l * l - k2) * (k2 - m * m) * (k2 - n * n)) / (k2 * (k2 - h2)));\n \n\n if(l * m * n < 0)\n p->x1 = -p->x1;\n if(l * n < 0)\n p->x2 = -p->x2;\n if(l * m < 0)\n p->x3 = -p->x3;\n \n p->type = 'c';\n }\n\n ierr = PetscLogFlops(36);\n PetscFunctionReturn(0);\n} \n\n\nvoid cartesianToEllipsoidal2(struct EllipsoidalSystem *e, struct Point *p) {\n\n if(p->type != 'e') {\n double h2 = e->h2;\n double k2 = e->k2;\n double x = p->x1;\n double y = p->x2;\n double z = p->x3;\n double a = -1.0*(x*x + y*y + z*z + h2 + k2);\n double b = (h2 + k2)*x*x + k2*y*y + h2*z*z + h2*k2;\n double c = -h2*k2*x*x;\n\n double Areal = -(c/2.0) + (a*b/6.0) - (a*a*a/27.0);\n double Aimag = sqrt(-1.0*((a*a*a*c + b*b*b - a*a*b*b)/27.0 + (9.0*c*c - 6.0*a*b*c + a*a*b*b)/36.0));\n \n double r = sqrt(Areal*Areal + Aimag*Aimag);\n double Atheta = atan2(Aimag, Areal);\n\n //Not sure what I was doing with Broot1, Broot2. Commented out\n double Aroot1, Aroot2;//, Broot1, Broot2;\n double ArootReal, ArootImag; //, BrootReal, BrootImag;\n int Ayes = 0;\n\n for(int k=0; k<3; ++k) {\n Aroot1 = cbrt(r)*cos((Atheta + 2.0*k*PETSC_PI)/3.0);\n Aroot2 = cbrt(r)*sin((Atheta + 2.0*k*PETSC_PI)/3.0);\n //what is this jibber jabber\n //Broot1 = cbrt(r)*cos((Btheta + 2.0*k*PETSC_PI)/3.0);\n //Broot2 = cbrt(r)*sin((Btheta + 2.0*k*PETSC_PI)/3.0);\n if(Aroot1 >= 0 && Aroot2 >= 0) {\n\tArootReal = Aroot1;\n\tArootImag = Aroot2;\n\tAyes = 1;\n }\n //Not sure what this is for\n //\n //if(Broot1 >= 0 && Broot2 >= 0) {\n //BrootReal = Broot1;\n //BrootImag = Broot2;\n //}\n //printf(\"A,Ai,B,Bi: %15.15f, %15.15f, %15.15f, %15.15f\\n\", Aroot1, Aroot2, Broot1, Broot2);\n }\n if(Ayes == 0)\n printf(\"\\n\\n\\n\\n COULD NOT FIND PROPER ROOT FOR A\");\n \n double kap1 = -a/3.0 + 2.0*ArootReal;\n double kap2 = -a/3.0 - ArootReal - sqrt(3.0)*ArootImag;\n double kap3 = -a/3.0 - ArootReal + sqrt(3.0)*ArootImag;\n \n double newX1 = sqrt(kap1);\n double newX2 = sqrt(kap2);\n double newX3 = sqrt(kap3);\n \n //p->x1 = sqrt(kap1);\n //p->x2 = sqrt(kap3);\n //p->x3 = sqrt(kap2);\n \n if(x*y*z < 0)\n newX1 = - newX1;\n if(x*y < 0)\n newX2 = -newX2;\n if(x*z < 0)\n newX3 = -newX3;\n\n p->x1 = newX1;\n p->x2 = newX2;\n p->x3 = newX3;\n }\n p->type = 'e';\n}\n\nvoid cartesianToEllipsoidal(struct EllipsoidalSystem *s, struct Point *p)\n{\n if(p->type != 'e') {\n double h2 = s->h2;\n double k2 = s->k2;\n double x = p->x1;\n double y = p->x2;\n double z = p->x3;\n //Use Romain (6) for approximate values\n double a1 = -(x*x + y*y + z*z + h2 + k2);\n double a2 = x*x*(h2 + k2) + y*y*k2 + z*z*h2 + h2*k2;\n double a3 = -x*x*h2*k2;\n double Q = (a1*a1 - 3.*a2)/9.;\n double R = (9.*a1*a2 - 27.*a3 - 2.*a1*a1*a1)/54.;\n double cth = R/sqrt(Q*Q*Q);\n double th = acos(cth);\n \n /*\n # Wikipedia http://en.wikipedia.org/wiki/List_of_trigonometric_identities \n # cos x = 4 cos^3 x/3 - 3 cos x/3 \n # 4 x^3 - 3x - v = 0 ==> {a = 4, b = 0, c = -3, d = -v} \n # Discriminant = 18abcd - 4b^3d + b^2c^2 - 4ac^3 - 27a^2d^2 \n # = 0 - 0 + 0 + 432 - 432*v^2 = 432*(1 - v^2) > 0 so 3 real roots \n # r1 = -1/3a (cbrt((27a^2d + sqrt(729a^4d^2 + 108a^3c^3))/2) + cbrt((27a^2d - sqrt(729a^4d^2 + 108a^3c^3))/2)) \n # = -1/12 (cbrt((432d + 432 sqrt(d^2 - 1))/2) + cbrt((432d - 432 sqrt(d^2 - 1))/2)) \n # = -cbrt(216)/12 (cbrt((d + sqrt(v^2 - 1))) + cbrt((d - sqrt(v^2 - 1)))) \n # = cbrt(216)/(12) (cbrt(cth - i sth) + cbrt(cth + i sth)) \n */\n double lambda[3] = { cos(th/3.0),\n\t\t\t cos((th+4.0*PETSC_PI)/3.0),\n\t\t\t cos((th+2.0*PETSC_PI)/3.0) };\n \n double val3 = 2*sqrt(Q)*lambda[2] - a1/3.0;\n if(val3 < 0 && fabs(val3) < 1e-10)\n val3 = 0;\n else if(val3 < 0) {\n printf(\"\\n\\nTHERE WAS AN ISSUE WITH THE TRANSFORM and we got %8.8e\\n\\n\", 2*sqrt(Q)*lambda[2] -a1/3.0);\n val3 = 0;\n }\n //for(int i=0; i<3; ++i) printf(\"lambda[%d] = %15.15f\\n\", i, lambda[i]);\n p->x1 = sqrt(2*sqrt(Q)*lambda[0] - a1/3);\n p->x2 = sqrt(2*sqrt(Q)*lambda[1] - a1/3);\n p->x3 = sqrt(val3);\n\n //printf(\"p->x1: %15.15f\\n\", p->x1);\n //printf(\"p->x2: %15.15f\\n\", p->x2);\n //printf(\"p->x3: %15.15f\\n\", p->x3);\n /*\n # Improve the estimate \n # Get $\\min(\\lambda^2_i, |\\lambda^2 - h^2|, |\\lambda^2_i - k^2|)$ \n # Rewrite ellipsoid cubic so that smallest value is root \n # Solve the equation using Newton \n # Transform back\n */\n if(x*y*z < 0)\n p->x1 = -p->x1;\n if(x*y < 0)\n p->x2 = -p->x2;\n if(x*z < 0)\n p->x3 = -p->x3;\n \n p->type = 'e';\n }\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"CartesianToEllipsoidalVec\"\nPetscErrorCode CartesianToEllipsoidalVec(EllipsoidalSystem *e, Vec xyzP, Vec ellP)\n{\n PetscErrorCode ierr;\n PetscInt nPts;\n PetscReal h2, k2;\n PetscReal x, y, z;\n PetscReal a1, a2, a3;\n PetscReal Q, R, cth, th;\n PetscReal val3;\n PetscReal lambda, mu, nu;\n const PetscScalar *xyzPArray;\n PetscScalar *ellPArray;\n PetscFunctionBegin;\n\n h2 = e->h2;\n k2 = e->k2;\n ierr = VecGetSize(xyzP, &nPts);CHKERRQ(ierr);\n nPts = nPts/3;\n \n ierr = VecGetArray (ellP, &ellPArray);CHKERRQ(ierr);\n ierr = VecGetArrayRead(xyzP, &xyzPArray);CHKERRQ(ierr);\n for(PetscInt i=0; i < nPts; ++i) {\n\n x = xyzPArray[3*i+0];\n y = xyzPArray[3*i+1];\n z = xyzPArray[3*i+2];\n \n //Use Romain (6) for approximate values\n a1 = -(x*x + y*y + z*z + h2 + k2);\n a2 = x*x*(h2 + k2) + y*y*k2 + z*z*h2 + h2*k2;\n a3 = -x*x*h2*k2;\n Q = (a1*a1 - 3.*a2)/9.;\n R = (9.*a1*a2 - 27.*a3 - 2.*a1*a1*a1)/54.;\n cth = R/sqrt(Q*Q*Q);\n th = acos(cth);\n PetscReal lam[3] = { cos(th/3.0),\n\t\t\t cos((th+4.0*PETSC_PI)/3.0),\n\t\t\t cos((th+2.0*PETSC_PI)/3.0) };\n \n val3 = 2*sqrt(Q)*lam[2] - a1/3.0;\n if(val3 < 0 && fabs(val3) < 1e-10) {\n printf(\"WOOOOW\\n\\n\");\n val3 = 0;\n }\n else if(val3 < 0) {\n printf(\"\\n\\nTHERE WAS AN ISSUE WITH THE TRANSFORM and we got %8.8e\\n\\n\", 2*sqrt(Q)*lam[2] -a1/3.0);\n val3 = 0;\n }\n \n lambda = sqrt(2*sqrt(Q)*lam[0] - a1/3);\n mu = sqrt(2*sqrt(Q)*lam[1] - a1/3);\n nu = sqrt(val3);\n \n if(x*y*z < 0)\n lambda = -lambda;\n if(x*y < 0)\n mu = -mu;\n if(x*z < 0)\n nu = -nu;\n\n ellPArray[3*i+0] = lambda;\n ellPArray[3*i+1] = mu;\n ellPArray[3*i+2] = nu;\n \n }\n\n ierr = VecRestoreArrayRead(xyzP, &xyzPArray);CHKERRQ(ierr);\n ierr = VecRestoreArray (ellP, &ellPArray);CHKERRQ(ierr);\n \n PetscFunctionReturn(0);\n}\n\n\nchar getLameTypeT(int n, int p)\n{\n int r = n/2;\n if(p < r+1)\n return 'K';\n else if(p < (n-r) + (r+1))\n return 'L';\n else if(p < (n-r) + (n-r) + (r+1))\n return 'M';\n else if(p < 2*n+1)\n return 'N';\n else\n printf(\"getLameType passed invalid n,p = (%d,%d)\\n\", n, p);\n return 'E';\n}\n\nint getLameTypeTp(int n, int p)\n{\n int r = n/2;\n if(p < r+1)\n return p;\n else if(p < (n-r) + (r+1))\n return p - (r+1);\n else if(p < (n-r) + (n-r) + (r+1))\n return p - (n-r) - (r+1);\n else if(p < 2*n+1)\n return p - (n-r) - (n-r) - (r+1);\n else\n printf(\"getLameTypeTP passed invalid n,p = (%d,%d)\\n\", n, p);\n return 0;\n}\n\nvoid getLameCoefficientMatrix2(struct EllipsoidalSystem *s, char t, int n, int *mat_size, double *out) {\n\n //For a given Lame type and ordr n, return the tridiagonal matrix\n //the size of the generated coefficient matrix is stored to mat_size\n //The eigenvectors of this matrix give the coefficients for the polynomaial P in the Lame function definition\n //The expressions come from Romain Annex 3\n //OPT: We could memorize this\n double alpha = s->h2;\n double beta = s->k2 - s->h2;\n double gamma = alpha - beta;\n int r = n/2;\n int size_d;\n double *d, *g, *f;\n if(t == 'K') {\n size_d = r+1;\n }\n else if(t == 'L' || t == 'M') {\n size_d = n-r;\n }\n else if(t == 'N') {\n size_d = r;\n }\n d = (double*) malloc(sizeof(double)*size_d);\n g = (double*) malloc(sizeof(double)*(size_d-1));\n f = (double*) malloc(sizeof(double)*(size_d-1));\n \n if (t == 'K') {\n //g missing last item\n for(int k = 0; k < r; ++k)\n g[k] = -(2*k + 2)*(2*k + 1)*beta;\n if(n%2) { //n is odd\n for(int k=0; k < r+1; ++k)\n\td[k] = ((2*r + 1)*(2*r + 2) - 4*k*k)*alpha + (2*k + 1)*(2*k + 1)*beta;\n for(int k=1; k < r+1; ++k)\n\tf[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) + 1); \n }\n else { //n is even\n for(int k=0; k < r+1; ++k)\n\td[k] = 2*r*(2*r + 1)*alpha - 4*k*k*gamma;\n for(int k=1; k < r+1; ++k)\n\tf[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) - 1);\n }\n }\n else if (t == 'L') {\n //g missing last item\n for(int k = 0; k < n-r-1; ++k) {\n g[k] = -(2*k + 2)*(2*k + 3)*beta;\n //printf(\"g[%d] = %15.15f\\n\", k, g[k]);\n //printf(\"n, r, %d, %d\\n\", n, r);\n //printf(\"beta: %15.15f\\n\", beta);\n }\n if(n%2) { //n is odd\n for(int k=0; k < n-r; ++k)\n\td[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 1)*(2*k + 1)*gamma;\n for(int k=1; k < n-r; ++k)\n\tf[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1);\n }\n else { //n is even\n for(int k=0; k < n-r; ++k)\n\td[k] = (2*r*(2*r + 1) - (2*k + 1)*(2*k + 1))*alpha + (2*k + 2)*(2*k + 2)*beta;\n for(int k=1; k < n-r; ++k)\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1);\n }\n }\n else if (t == 'M') {\n //g missing last item\n for(int k = 0; k < n-r-1; ++k)\n g[k] = -(2*k + 2)*(2*k + 1)*beta;\n if(n%2) { //n is odd\n for(int k=0; k < n-r; ++k)\n\td[k] = ((2*r + 1)*(2*r + 2) - (2*k + 1)*(2*k + 1))*alpha + 4*k*k*beta;\n for(int k=1; k < n-r; ++k)\n\tf[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1);\n }\n else { //n is even\n for(int k=0; k < n-r; ++k)\n\td[k] = 2*r*(2*r + 1)*alpha - (2*k + 1)*(2*k + 1)*gamma;\n for(int k=1; k < n-r; ++k)\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1);\n }\n }\n else if (t == 'N') {\n //g missing last item\n for(int k = 0; k < r-1; ++k)\n g[k] = -(2*k + 2)*(2*k + 3)*beta;\n if(n%2) { //n is odd\n for(int k=0; k < r; ++k)\n\td[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 2)*(2*k + 2)*gamma;\n for(int k=1; k < r; ++k)\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k +3);\n }\n else { //n is even\n for(int k=0; k < r; ++k)\n\td[k] = 2*r*(2*r + 1)*alpha - (2*k + 2)*(2*k + 2)*alpha + (2*k + 1)*(2*k + 1)*beta;\n for(int k=1; k < r; ++k)\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1);\n }\n }\n\n\n double *M = (double*) calloc(sizeof(double), size_d*size_d);\n //fill diagonal with d\n for(int k=0; k < size_d; ++k)\n M[k*size_d + k] = d[k];\n //fill above diagonal with g\n for(int k=0; k < size_d-1; ++k)\n M[(k)*size_d + k+1] = g[k];\n //fill below diagonal with f\n for(int k=0; k < size_d-1; ++k)\n M[(k+1)*size_d + k] = f[k];\n \n \n //transpose M for lapack\n matTranspose(M, size_d);\n \n\n int lwork = 16*size_d;\n int info;\n double *vr, *work, *wr, *wi;\n vr = (double*) malloc(sizeof(double)*size_d*size_d);\n wr = (double*) malloc(sizeof(double)*size_d);\n wi = (double*) malloc(sizeof(double)*size_d);\n work = (double*) malloc(sizeof(double)*lwork);\n\n //compute eigenvalues with lapack\n char complefteig, comprighteig;\n complefteig = 'N'; //don't compute left eigenvectors\n comprighteig = 'V'; //compute right eigenvectors\n \n\n dgeev_( &complefteig, &comprighteig, &size_d, M, &size_d, wr, wi, NULL, &size_d, vr, &size_d, work, &lwork, &info );\n \n\n //matTranspose(vr, size_d); \n //printf(\"hot\\n\");\n //printf(\"size_d: %d\\n\", size_d);\n free(wr);\n free(wi);\n free(d);\n free(f);\n free(g);\n free(work);\n free(M);\n //printf(\"amazing\\n\");\n //printf(\"diggity\\n\");\n *mat_size = size_d;\n\n //return vr;\n}\n\n/*\n#undef __FUNCT__\n#define __FUNCT__ \"MatVecMult\"\nPetscErrorCode MatVecMult(PetscInt m, PetscInt n, double **mat, double *vec)\n{\n PetscErrorCode ierr;\n\n PetscFunctionBegin;\n\n for(PetscInt i=0; ihp_h2, MPFR_RNDN);\n mpfr_sub(beta, s->hp_k2, s->hp_h2, MPFR_RNDN);\n mpfr_sub(gamma, alpha, beta, MPFR_RNDN);\n\n PetscInt r = n/2;\n if(t=='K') {\n size_d = r+1;\n }\n else if(t=='L' || t=='M') {\n size_d = n-r;\n }\n else if(t=='N') {\n size_d = r;\n }\n d = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d);\n g = (mpfr_t*) malloc(sizeof(mpfr_t)*(size_d-1));\n f = (mpfr_t*) malloc(sizeof(mpfr_t)*(size_d-1));\n sigma = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d);\n\n for(PetscInt k=0; kprecision, *mat);CHKERRQ(ierr);\n\n //transform back to get eigenvectors of non-symmetric matrix\n for(PetscInt i=0; i < size_d; ++i) {\n for(PetscInt j=0; j < size_d; ++j) {\n //(*mat)[i*size_d+j] = (*mat)[i*size_d+j]*1./(sigma[j]);\n mpfr_div((*mat)[i*size_d+j], (*mat)[i*size_d+j], sigma[j], MPFR_RNDN);\n }\n }\n\n for(PetscInt i=0; i < size_d; ++i) {\n for(PetscInt j=0; j < size_d; ++j) {\n mpfr_neg(temp1, s->hp_h2, MPFR_RNDN);\n mpfr_set_d(temp2, size_d-1, MPFR_RNDN);\n mpfr_pow(temp1, temp1, temp2, MPFR_RNDN);\n mpfr_div(temp1, (*mat)[(i*size_d)+size_d-1], temp1, MPFR_RNDN);\n mpfr_div((*mat)[i*size_d+j], (*mat)[i*size_d+j], temp1, MPFR_RNDN);\n }\n }\n\n //hard fix for n=0 because i have no idea what goes wrong but i know the coef is 1.0\n if(n == 0)\n mpfr_set_d((*mat)[0], 1.0, MPFR_RNDN);\n mpfr_clears(alpha, beta, gamma, NULL);\n PetscFunctionReturn(0);\n}\n \n\n\n\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"getLameCoefficientMatrixSymmetric\"\nPetscErrorCode getLameCoefficientMatrixSymmetric(struct EllipsoidalSystem *s, char t, int n, int* const mat_size, double **mat)\n{\n PetscErrorCode ierr;\n PetscInt flopCount;\n PetscFunctionBegin;\n flopCount = 0;\n \n //For a given Lame type and ordr n, return the tridiagonal matrix\n //the size of the generated coefficient matrix is stored to mat_size\n //The eigenvectors of this matrix give the coefficients for the polynomaial P in the Lame function definition\n //The expressions come from Romain Annex 3\n //OPT: We could memorize this\n double alpha = s->h2;\n double beta = s->k2 - s->h2;\n double gamma = alpha - beta; flopCount += 2;\n int r = n/2;\n int size_d;\n double *d, *g, *f, *sigma;\n if(t == 'K') {\n size_d = r+1;\n }\n else if(t == 'L' || t == 'M') {\n size_d = n-r;\n }\n else if(t == 'N') {\n size_d = r;\n }\n d = (double*) malloc(sizeof(double)*size_d);\n g = (double*) malloc(sizeof(double)*(size_d-1));\n f = (double*) malloc(sizeof(double)*(size_d-1));\n sigma = (double*) malloc(sizeof(double)*size_d);\n \n if (t == 'K') {\n //g missing last item\n for(int k = 0; k < r; ++k) {\n g[k] = -(2*k + 2)*(2*k + 1)*beta; flopCount++;\n }\n if(n%2) { //n is odd\n for(int k=0; k < r+1; ++k) {\n\td[k] = ((2*r + 1)*(2*r + 2) - 4*k*k)*alpha + (2*k + 1)*(2*k + 1)*beta; flopCount += 6;\n }\n for(int k=1; k < r+1; ++k) {\n\tf[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) + 1); flopCount += 2;\n }\n }\n else { //n is even\n for(int k=0; k < r+1; ++k) {\n\td[k] = 2*r*(2*r + 1)*alpha - 4*k*k*gamma; flopCount += 5;\n }\n for(int k=1; k < r+1; ++k) {\n\tf[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) - 1); flopCount += 2;\n }\n }\n }\n else if (t == 'L') {\n //g missing last item\n for(int k = 0; k < n-r-1; ++k) {\n g[k] = -(2*k + 2)*(2*k + 3)*beta; flopCount += 2;\n //printf(\"g[%d] = %15.15f\\n\", k, g[k]);\n //printf(\"n, r, %d, %d\\n\", n, r);\n //printf(\"beta: %15.15f\\n\", beta);\n }\n if(n%2) { //n is odd\n for(int k=0; k < n-r; ++k) {\n\td[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 1)*(2*k + 1)*gamma; flopCount += 3;\n }\n for(int k=1; k < n-r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); flopCount += 3;\n }\n }\n else { //n is even\n for(int k=0; k < n-r; ++k) {\n\td[k] = (2*r*(2*r + 1) - (2*k + 1)*(2*k + 1))*alpha + (2*k + 2)*(2*k + 2)*beta; flopCount += 3;\n }\n for(int k=1; k < n-r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 2;\n }\n }\n }\n else if (t == 'M') {\n //g missing last item\n for(int k = 0; k < n-r-1; ++k) {\n g[k] = -(2*k + 2)*(2*k + 1)*beta; flopCount += 2;\n }\n if(n%2) { //n is odd\n for(int k=0; k < n-r; ++k) {\n\td[k] = ((2*r + 1)*(2*r + 2) - (2*k + 1)*(2*k + 1))*alpha + 4*k*k*beta; flopCount += 5;\n }\n for(int k=1; k < n-r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); flopCount += 2;\n }\n }\n else { //n is even\n for(int k=0; k < n-r; ++k) {\n\td[k] = 2*r*(2*r + 1)*alpha - (2*k + 1)*(2*k + 1)*gamma; flopCount += 3;\n }\n for(int k=1; k < n-r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 2;\n }\n }\n }\n else if (t == 'N') {\n //g missing last item\n for(int k = 0; k < r-1; ++k) {\n g[k] = -(2*k + 2)*(2*k + 3)*beta; flopCount += 2;\n }\n if(n%2) { //n is odd\n for(int k=0; k < r; ++k) {\n\td[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 2)*(2*k + 2)*gamma; flopCount += 3;\n }\n for(int k=1; k < r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k +3); flopCount += 2;\n }\n }\n else { //n is even\n for(int k=0; k < r; ++k) {\n\td[k] = 2*r*(2*r + 1)*alpha - (2*k + 2)*(2*k + 2)*alpha + (2*k + 1)*(2*k + 1)*beta;\n\tflopCount += 4;\n }\n for(int k=1; k < r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 3;\n }\n }\n }\n\n sigma[0] = 1;\n for(PetscInt k=1; kh2,(m+1)-1));\n\n\n //transform back to get eigenvectors\n for(PetscInt i=0; ih2,(size_d)-1));\n flopCount += 3;\n }\n }\n\n\n ierr = PetscLogFlops(flopCount);CHKERRQ(ierr);\n //return vr;\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"getLameCoefficientMatrix\"\nPetscErrorCode getLameCoefficientMatrix(struct EllipsoidalSystem *s, char t, int n, int* const mat_size, double **mat)\n{\n PetscErrorCode ierr;\n PetscInt flopCount;\n PetscFunctionBegin;\n flopCount = 0;\n \n //For a given Lame type and ordr n, return the tridiagonal matrix\n //the size of the generated coefficient matrix is stored to mat_size\n //The eigenvectors of this matrix give the coefficients for the polynomaial P in the Lame function definition\n //The expressions come from Romain Annex 3\n //OPT: We could memorize this\n double alpha = s->h2;\n double beta = s->k2 - s->h2;\n double gamma = alpha - beta; flopCount += 2;\n int r = n/2;\n int size_d;\n double *d, *g, *f;\n if(t == 'K') {\n size_d = r+1;\n }\n else if(t == 'L' || t == 'M') {\n size_d = n-r;\n }\n else if(t == 'N') {\n size_d = r;\n }\n d = (double*) malloc(sizeof(double)*size_d);\n g = (double*) malloc(sizeof(double)*(size_d-1));\n f = (double*) malloc(sizeof(double)*(size_d-1));\n \n if (t == 'K') {\n //g missing last item\n for(int k = 0; k < r; ++k) {\n g[k] = -(2*k + 2)*(2*k + 1)*beta; flopCount++;\n }\n if(n%2) { //n is odd\n for(int k=0; k < r+1; ++k) {\n\td[k] = ((2*r + 1)*(2*r + 2) - 4*k*k)*alpha + (2*k + 1)*(2*k + 1)*beta; flopCount += 6;\n }\n for(int k=1; k < r+1; ++k) {\n\tf[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) + 1); flopCount += 2;\n }\n }\n else { //n is even\n for(int k=0; k < r+1; ++k) {\n\td[k] = 2*r*(2*r + 1)*alpha - 4*k*k*gamma; flopCount += 5;\n }\n for(int k=1; k < r+1; ++k) {\n\tf[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) - 1); flopCount += 2;\n }\n }\n }\n else if (t == 'L') {\n //g missing last item\n for(int k = 0; k < n-r-1; ++k) {\n g[k] = -(2*k + 2)*(2*k + 3)*beta; flopCount += 2;\n //printf(\"g[%d] = %15.15f\\n\", k, g[k]);\n //printf(\"n, r, %d, %d\\n\", n, r);\n //printf(\"beta: %15.15f\\n\", beta);\n }\n if(n%2) { //n is odd\n for(int k=0; k < n-r; ++k) {\n\td[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 1)*(2*k + 1)*gamma; flopCount += 3;\n }\n for(int k=1; k < n-r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); flopCount += 3;\n }\n }\n else { //n is even\n for(int k=0; k < n-r; ++k) {\n\td[k] = (2*r*(2*r + 1) - (2*k + 1)*(2*k + 1))*alpha + (2*k + 2)*(2*k + 2)*beta; flopCount += 3;\n }\n for(int k=1; k < n-r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 2;\n }\n }\n }\n else if (t == 'M') {\n //g missing last item\n for(int k = 0; k < n-r-1; ++k) {\n g[k] = -(2*k + 2)*(2*k + 1)*beta; flopCount += 2;\n }\n if(n%2) { //n is odd\n for(int k=0; k < n-r; ++k) {\n\td[k] = ((2*r + 1)*(2*r + 2) - (2*k + 1)*(2*k + 1))*alpha + 4*k*k*beta; flopCount += 5;\n }\n for(int k=1; k < n-r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); flopCount += 2;\n }\n }\n else { //n is even\n for(int k=0; k < n-r; ++k) {\n\td[k] = 2*r*(2*r + 1)*alpha - (2*k + 1)*(2*k + 1)*gamma; flopCount += 3;\n }\n for(int k=1; k < n-r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 2;\n }\n }\n }\n else if (t == 'N') {\n //g missing last item\n for(int k = 0; k < r-1; ++k) {\n g[k] = -(2*k + 2)*(2*k + 3)*beta; flopCount += 2;\n }\n if(n%2) { //n is odd\n for(int k=0; k < r; ++k) {\n\td[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 2)*(2*k + 2)*gamma; flopCount += 3;\n }\n for(int k=1; k < r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k +3); flopCount += 2;\n }\n }\n else { //n is even\n for(int k=0; k < r; ++k) {\n\td[k] = 2*r*(2*r + 1)*alpha - (2*k + 2)*(2*k + 2)*alpha + (2*k + 1)*(2*k + 1)*beta;\n\tflopCount += 4;\n }\n for(int k=1; k < r; ++k) {\n\tf[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 3;\n }\n }\n }\n\n\n double *M = (double*) calloc(sizeof(double), size_d*size_d);\n //fill diagonal with d\n for(int k=0; k < size_d; ++k)\n M[k*size_d + k] = d[k];\n //fill above diagonal with g\n for(int k=0; k < size_d-1; ++k)\n M[(k)*size_d + k+1] = g[k];\n //fill below diagonal with f\n for(int k=0; k < size_d-1; ++k)\n M[(k+1)*size_d + k] = f[k];\n \n \n //transpose M for lapack\n matTranspose(M, size_d);\n \n\n int lwork = 16*size_d;\n int info;\n double *work, *wr, *wi;\n *mat = (double*) malloc(sizeof(double)*size_d*size_d);\n wr = (double*) malloc(sizeof(double)*size_d);\n wi = (double*) malloc(sizeof(double)*size_d);\n work = (double*) malloc(sizeof(double)*lwork);\n\n //compute eigenvalues with lapack\n char complefteig, comprighteig;\n complefteig = 'N'; //don't compute left eigenvectors\n comprighteig = 'V'; //compute right eigenvectors\n \n /* #################################################### */\n /* ############## NEED TO ADD FLOP COUNT HERE ######### */\n dgeev_( &complefteig, &comprighteig, &size_d, M, &size_d, wr, wi, NULL, &size_d, *mat, &size_d, work, &lwork, &info );\n /* #################################################### */\n /* #################################################### */\n \n //matTranspose(vr, size_d); \n //printf(\"hot\\n\");\n //printf(\"size_d: %d\\n\", size_d);\n free(wr);\n free(wi);\n free(d);\n free(f);\n free(g);\n free(work);\n free(M);\n //printf(\"amazing\\n\");\n //printf(\"diggity\\n\");\n if(mat_size != NULL)\n *mat_size = size_d;\n //for(int k=0; k<(m+1); ++k)\n //b[k] = b[k]/(b[(m+1)-1]/pow(-e->h2,(m+1)-1));\n for(int i=0; ih2,(size_d)-1));\n flopCount += 3;\n }\n }\n ierr = PetscLogFlops(flopCount);CHKERRQ(ierr);\n //return vr;\n PetscFunctionReturn(0);\n}\n\ndouble *computeLameCoefficients(EllipsoidalSystem *e, int n, int p, int *vecsize) {\n char t = getLameTypeT(n, p);\n int tp = getLameTypeTp(n, p);\n int bsize;\n double *B;\n getLameCoefficientMatrix(e, t, n, &bsize, &B);\n //printf(\"B SIZE: %d\\n\", bsize);\n double *ret = (double*) malloc(sizeof(double)*bsize);\n memcpy(ret, B+tp*bsize, sizeof(double)*bsize);\n free(B);\n *vecsize = bsize;\n return ret;\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"initRomainConstsToOrderN\"\nPetscErrorCode initRomainConstsToOrderN(EllipsoidalSystem *e, int N)\n{\n PetscErrorCode ierr;\n PetscFunctionBegin;\n \n if(e->Rconsts != NULL)\n free(e->Rconsts);\n //initialize vector of romain constant matrices\n e->Rconsts = (double***) malloc(sizeof(double**)*(N+1));\n //initialize mpfr version\n e->RconstsMPFR = (mpfr_t***) malloc(sizeof(mpfr_t**)*(N+1));\n //int* mat_size; *mat_size = 1;\n for(int n=0; n<=N; ++n) {\n printf(\"n=%d\\n\", n);\n e->Rconsts[n] = (double**) malloc(sizeof(double*)*4);\n e->RconstsMPFR[n] = (mpfr_t**) malloc(sizeof(mpfr_t*)*4);\n //e->Rconsts[n][0] = getLameCoefficientMatrix(e, 'K', n, NULL);\n ierr = getLameCoefficientMatrix(e, 'K', n, NULL, e->Rconsts[n]+0);CHKERRQ(ierr);\n ierr = getLameCoefficientMatrixSymmetricMPFR(e, 'K', n, NULL, e->RconstsMPFR[n]+0);CHKERRQ(ierr);\n //PetscErrorCode getLameCoefficientMatrixSymmetricMPFR(struct EllipsoidalSystem *s, char t, PetscInt n, PetscInt* const mat_size, mpfr_t **mat)\n //printf(\"wowze\\n\");\n if(n != 0) {\n //e->Rconsts[n][1] = getLameCoefficientMatrix(e, 'L', n, NULL);\n ierr = getLameCoefficientMatrix(e, 'L', n, NULL, e->Rconsts[n]+1);CHKERRQ(ierr);\n ierr = getLameCoefficientMatrixSymmetricMPFR(e, 'L', n, NULL, e->RconstsMPFR[n]+1);CHKERRQ(ierr);\n //e->Rconsts[n][2] = getLameCoefficientMatrix(e, 'M', n, NULL);\n ierr = getLameCoefficientMatrix(e, 'M', n, NULL, e->Rconsts[n]+2);CHKERRQ(ierr);\n ierr = getLameCoefficientMatrixSymmetricMPFR(e, 'M', n, NULL, e->RconstsMPFR[n]+2);CHKERRQ(ierr);\n if(n != 1) {\n\t//e->Rconsts[n][3] = getLameCoefficientMatrix(e, 'N', n, NULL);\n\tierr = getLameCoefficientMatrix(e, 'N', n, NULL, e->Rconsts[n]+3);CHKERRQ(ierr);\n\tierr = getLameCoefficientMatrixSymmetricMPFR(e, 'N', n, NULL, e->RconstsMPFR[n]+3);CHKERRQ(ierr);\n }\n }\n }\n\n ierr = PetscLogFlops(0);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"CalcLameMPFR\"\nPetscErrorCode CalcLameMPFR(EllipsoidalSystem *e, PetscInt n, PetscInt p, mpfr_t l, PetscInt signm, PetscInt signn, mpfr_t *Enp)\n{\n\n PetscErrorCode ierr;\n mpfr_t l2, psi;\n mpfr_t temp1, temp2;\n mpfr_t signh, signk;\n mpfr_t Lambda_Romain;\n mpfr_t P;\n PetscFunctionBegin;\n\n mpfr_inits(temp1, temp2, signh, signk, l2, psi, Lambda_Romain, P, NULL);\n \n mpfr_mul_d(temp1, l, (double) signm, MPFR_RNDN);\n if(mpfr_get_d(temp1, MPFR_RNDN) >= 0)\n mpfr_set_d(signh, 1.0, MPFR_RNDN);\n else\n mpfr_set_d(signh, -1.0, MPFR_RNDN);\n mpfr_mul_d(temp1, l, (double) signn, MPFR_RNDN);\n if(mpfr_get_d(temp1, MPFR_RNDN) >= 0)\n mpfr_set_d(signk, 1.0, MPFR_RNDN);\n else\n mpfr_set_d(signk, -1.0, MPFR_RNDN);\n\n char t = getLameTypeT(n, p);\n PetscInt tp = getLameTypeTp(n, p);\n\n PetscInt r = n/2;\n PetscInt m, type;\n mpfr_mul(l2, l, l, MPFR_RNDN);\n\n if(t == 'K') {\n m = r;\n //psi = pow(l, n-2*r); countFlops++;\n mpfr_set_d(temp1, n-2*r, MPFR_RNDN);\n mpfr_pow(psi, l, temp1, MPFR_RNDN);\n type = 0;\n }\n else if(t == 'L') {\n m = n-r-1;\n //psi = pow(l, 1-n+2*r)*signh*sqrt(fabs(l2-e->h2)); countFlops += 3;\n mpfr_set_d(temp1, 1-n+2*r, MPFR_RNDN);\n mpfr_pow(temp1, l, temp1, MPFR_RNDN);\n mpfr_sub(temp2, l2, e->hp_h2, MPFR_RNDN);\n mpfr_abs(temp2, temp2, MPFR_RNDN);\n mpfr_sqrt(temp2, temp2, MPFR_RNDN);\n mpfr_mul(psi, temp1, temp2, MPFR_RNDN);\n mpfr_mul(psi, psi, signh, MPFR_RNDN);\n type = 1;\n }\n else if(t == 'M') {\n //psi = pow(l, 1-n+2*r)*signk*sqrt(fabs(l2-e->k2)); countFlops += 3;\n m = n-r-1;\n mpfr_set_d(temp1, 1-n+2*r, MPFR_RNDN);\n mpfr_pow(temp1, l, temp1, MPFR_RNDN);\n mpfr_sub(temp2, l2, e->hp_k2, MPFR_RNDN);\n mpfr_abs(temp2, temp2, MPFR_RNDN);\n mpfr_sqrt(temp2, temp2, MPFR_RNDN);\n mpfr_mul(psi, temp1, temp2, MPFR_RNDN);\n mpfr_mul(psi, psi, signk, MPFR_RNDN);\n type = 2;\n }\n else if(t == 'N') {\n //psi = pow(l, n-2*r)*signh*signk*sqrt(fabs((l2-e->k2)*(l2-e->h2))); countFlops += 8;\n m = r-1;\n mpfr_sub(temp1, l2, e->hp_k2, MPFR_RNDN);\n mpfr_sub(temp2, l2, e->hp_h2, MPFR_RNDN);\n mpfr_mul(temp1, temp1, temp2, MPFR_RNDN);\n mpfr_sqrt(temp1, temp1, MPFR_RNDN);\n mpfr_set_d(temp2, n-2*r, MPFR_RNDN);\n mpfr_pow(temp2, l, temp2, MPFR_RNDN);\n mpfr_mul(psi, temp1, temp2, MPFR_RNDN);\n mpfr_mul(psi, psi, signh, MPFR_RNDN);\n mpfr_mul(psi, psi, signk, MPFR_RNDN);\n type = 3;\n }\n else\n printf(\"Invalid Lame Type\\n\");\n\n mpfr_div(temp1, l2, e->hp_h2, MPFR_RNDN);\n mpfr_d_sub(Lambda_Romain, 1.0, temp1, MPFR_RNDN);\n\n mpfr_t *b = e->RconstsMPFR[n][type]+tp*(m+1);\n\n mpfr_set(P, b[m], MPFR_RNDN);\n for(PetscInt j=m-1; j > -1; --j) {\n // P = P*Lambda_Romain + b[j]\n mpfr_mul(P, P, Lambda_Romain, MPFR_RNDN);\n mpfr_add(P, P, b[j], MPFR_RNDN);\n }\n\n // Enp = psi*P\n mpfr_mul(*Enp, psi, P, MPFR_RNDN);\n \n mpfr_clears(temp1, temp2, signh, signk, l2, psi, Lambda_Romain, P, NULL);\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"calcLame\"\nPetscErrorCode calcLame(EllipsoidalSystem *e, int n, int p, double l, int signm, int signn, double *Enp)\n{\n PetscErrorCode ierr;\n PetscInt countFlops;\n PetscFunctionBegin;\n countFlops = 0;\n \n double signh, signk;\n if(signm*l >= 0)\n signh = 1;\n else\n signh = -1;\n if(signn*l >= 0)\n signk = 1;\n else\n signk = -1;\n char t = getLameTypeT(n, p);\n int tp = getLameTypeTp(n, p);\n\n\n //double *B = getLameCoefficientMatrix(e, t, n, &bsize);\n //printf(\"%c\\n\", t);\n\n int r = n/2;\n double l2 = l*l;\n double psi;\n int m;\n int type;\n //This comes from Romain Table II\n if(t == 'K') {\n m = r;\n psi = pow(l, n-2*r); countFlops++;\n type = 0;\n }\n else if(t == 'L') {\n m = n-r-1;\n psi = pow(l, 1-n+2*r)*signh*sqrt(fabs(l2-e->h2)); countFlops += 3;\n type = 1;\n }\n else if(t == 'M') {\n m = n-r-1;\n psi = pow(l, 1-n+2*r)*signk*sqrt(fabs(l2-e->k2)); countFlops += 3;\n type = 2;\n }\n else if(t == 'N') {\n m = r-1;\n psi = pow(l, n-2*r)*signh*signk*sqrt(fabs((l2-e->k2)*(l2-e->h2))); countFlops += 8;\n type = 3;\n }\n else\n printf(\"Invalid Lame Type\\n\");\n //if(isnan(psi))\n //printf(\"psi is nan and s: %15.15f\\n\", l);\n //Romain (30) \\sum^m_{j=0} b_j (1 - \\frac{\\lambda^2}{h^2}) = \\sum^m_{j=0} b_j \\Lambda^j\n double Lambda_Romain = (1.0 - (l2/e->h2)); \n\n //b = B[tp]\n //double *b = (double*) malloc(sizeof(double)*(m+1));\n double *b = e->Rconsts[n][type]+tp*(m+1); countFlops += 4;\n //for(int i=0; i<=m; ++i) {\n //memcpy(b, e->Rconsts[n][type]+tp*(m+1), sizeof(double)*(m+1));\n //}\n //memcpy(b, B+tp*(m+1), sizeof(double)*(m+1));\n \n //Normalize b so that the highest power of lambda has coefficient unity\n //Romain p242 and Dassios (D9,D10 and their gamma in B16-B20)\n //for(int k=0; k<(m+1); ++k)\n //b[k] = b[k]/(b[(m+1)-1]/pow(-e->h2,(m+1)-1));\n\n double P = b[m];\n for(int j=m-1; j>-1; --j) {\n P = P*Lambda_Romain + b[j];\n countFlops += 2;\n }\n //free(B);\n //free(b);\n //printf(\"psi: %15.15f\\n\", psi);\n //printf(\"p: %d\\n\", p);\n \n *Enp = psi*P; countFlops++;\n //printf(\"countFlops: %d\\n\", countFlops);\n \n ierr = PetscLogFlops(countFlops);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"calcLameDerivative\"\nPetscErrorCode calcLameDerivative(EllipsoidalSystem *e, int n, int p, double l, int signm, int signn, double *sol)\n{\n PetscErrorCode ierr;\n PetscInt logFlops;\n PetscFunctionBegin;\n logFlops = 0;\n //Evaluate \\frac{dE^p_n(l)}{dl}\n //The signs of \\mu and \\nu are necessary in order to determine the sign of \\psi\n double signh, signk;\n if(signm*l >= 0)\n signh = 1;\n else\n signh = -1;\n if(signn*l >= 0)\n signk = 1;\n else\n signk = -1;\n \n char t = getLameTypeT(n, p);\n int tp = getLameTypeTp(n, p);\n \n int bsize;\n double *B;\n ierr = getLameCoefficientMatrix(e, t, n, &bsize, &B);CHKERRQ(ierr);\n \n int r = n/2;\n double l2 = l*l; logFlops ++;\n \n int m;\n double psi, psider;\n int type;\n //This comes from Romain Table II\n if(t == 'K') {\n m = r;\n psi = pow(l, n-2*r);\n psider = (n-2*r)*pow(l, n-2*r-1);\n type = 0;\n logFlops += 3;\n }\n else if(t == 'L') {\n m = n-r-1;\n psi = pow(l, 1-n+2*r)*signh*sqrt(fabs(l2 - e->h2)); logFlops += 4;\n psider = (1-n+2*r)*pow(l, -n+2*r)*signh*sqrt(fabs(l2 - e->h2)) + pow(l, 2-n+2*r)*signh/sqrt(fabs(l2 - e->h2)); logFlops += 12;\n type = 1;\n }\n else if(t == 'M') {\n m = n-r-1;\n psi = pow(l, 1-n+2*r)*signk*sqrt(fabs(l2 - e->k2)); logFlops += 4;\n psider = (1-n+2*r)*pow(l, -n+2*r)*signk*sqrt(fabs(l2 - e->k2)) + pow(l, 2-n+2*r)*signk/sqrt(fabs(l2 - e->k2)); logFlops += 12;\n type = 2;\n }\n else if(t == 'N') {\n m = r-1;\n psi = pow(l, n-2*r)*signh*signk*sqrt(fabs((l2 - e->k2)*(l2 - e->h2))); logFlops += 8;\n psider = ((n-2*r)*pow(l, n-2*r-1)*signh*signk*sqrt(fabs((l2 - e->k2)*(l2 - e->h2))) +\n\t pow(l, n-2*r+1)*signh*signk*sqrt(fabs((l2 - e->k2)/(l2 - e->h2))) +\n\t pow(l, n-2*r+1)*signh*signk*sqrt(fabs((l2 - e->h2)/(l2 - e->k2)))); logFlops += 24;\n type = 3;\n }\n else\n printf(\"Invalid Lame type\\n\");\n \n //Romain (30) \\sum^m_{j=0} b_j (1 - \\frac{\\lambda^2}{h^2}) = \\sum^m_{j=0} b_j \\Lambda^j\n double Lambda_Romain = (1.0 - (l2/e->h2)); logFlops += 2; //Romain bottom of p.252\n //b = B[tp]\n double *b = (double*) malloc(sizeof(double)*(m+1));\n memcpy(b, e->Rconsts[n][type]+tp*(m+1), sizeof(double)*(m+1));\n double P = b[m];\n for(int j=m-1; j>-1; --j) {\n P = P*Lambda_Romain + b[j];\n logFlops += 2;\n }\n //P' = \\sum^{m-1}_{k=0} c_k \\Lambda^k where c_k = b_{k+1} (-2 (k+1) \\frac{\\lambda}{h^2}) \n double Pder = b[m]*(-2*m*l/e->h2); logFlops += 4;\n free(b);\n free(B);\n\n *sol = psider*P + psi*Pder;\n \n ierr = PetscLogFlops(logFlops);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"integrand\"\nPetscErrorCode integrand(mpfr_t *x, mpfr_t *val, FuncInfo *ctx)\n{\n PetscErrorCode ierr;\n PetscInt flopCount;\n PetscFunctionBegin;\n flopCount = 0;\n mpfr_t *temp = &((*ctx).e->temp1);\n mpfr_d_div(*temp, 1.0, *x, MPFR_RNDN); flopCount ++;\n double s = mpfr_get_d(*temp, MPFR_RNDZ);\n double E;\n ierr = calcLame((*ctx).e, (*ctx).n, (*ctx).p, s, ctx->signm, ctx->signn, &E);CHKERRQ(ierr);\n mpfr_mul(*temp, *x, *x, MPFR_RNDN);\n mpfr_set(*val, *temp, MPFR_RNDN);\n mpfr_mul_d(*temp, *temp, (*ctx).e->k2, MPFR_RNDN);\n mpfr_mul_d(*val, *val, (*ctx).e->h2, MPFR_RNDN);\n mpfr_d_sub(*temp, 1.0, *temp, MPFR_RNDZ);\n mpfr_d_sub(*val, 1.0, *val, MPFR_RNDZ);\n mpfr_sqrt(*temp, *temp, MPFR_RNDN);\n mpfr_sqrt(*val, *val, MPFR_RNDN);\n mpfr_mul(*val, *temp, *val, MPFR_RNDN);\n mpfr_mul_d(*val, *val, E, MPFR_RNDN);\n mpfr_mul_d(*val, *val, E, MPFR_RNDN); flopCount += 10;\n \n mpfr_d_div(*val, 1.0, *val, MPFR_RNDN); flopCount++;\n //printf(\"\\n\\n\\nVAL: %15.15f\\n\\n\\n\", mpfr_get_d(*val, MPFR_RNDN));\n \n ierr = PetscLogFlops(flopCount);\n PetscFunctionReturn(0);\n}\n\n/*\n void integrand(mpfr_t *x , mpfr_t *val, FuncInfo *ctx)\n {\n double x2 = x*x;\n double s;\n int n = (*ctx).n;\n int p = (*ctx).p;\n \n if(x==0.0)\n s = 1e6;\n else\n s = 1.0/x;\n double E = calcLame((*ctx).e, n, p, s);\n return 1.0 / (E*E*sqrt(1.0 - (*ctx).e->k2*x2)*sqrt(1.0 - (*ctx).e->h2*x2));\n }\n*/\n\n#undef __FUNCT__\n#define __FUNCT__ \"calcI\"\nPetscErrorCode calcI(EllipsoidalSystem *e, int n, int p, double l, int signm, int signn, double *sol)\n{\n PetscErrorCode ierr;\n PetscInt logFlops;\n mpfr_t solution;\n PetscFunctionBegin;\n\n mpfr_init(solution);\n \n logFlops = 0;\n if(l < 0) {\n l *= -1.0;\n logFlops ++;\n }\n //int digits = 14;\n FuncInfo ctx = { e, n, p, signm, signn};\n mpfr_t *a = &(e->tempa);\n mpfr_t *b = &(e->tempb);\n mpfr_set_d(*a, 0.0, MPFR_RNDN);\n mpfr_set_d(*b, 1.0, MPFR_RNDN);\n mpfr_div_d(*b, *b, l, MPFR_RNDN); logFlops++;\n //printf(\"a: %15.15f\\nb: %15.15f\\n\", mpfr_get_d(*a, MPFR_RNDN), mpfr_get_d(*b, MPFR_RNDN));\n\n int err = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*))integrand, e, *a, *b, 14, &solution, &ctx);\n *sol = mpfr_get_d(solution, MPFR_RNDN);\n if(err)\n printf(\"integral failed\\n\");\n //printf(\"the integral is: %15.15f\\n\", *sol);\n\n mpfr_clear(solution);\n ierr = PetscLogFlops(logFlops);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"calcIDerivative\"\nPetscErrorCode calcIDerivative(EllipsoidalSystem *e, int n, int p, double l, int signm, int signn, double *Ideriv)\n{\n PetscErrorCode ierr;\n PetscFunctionBegin;\n \n //Evaluate \\frac{dI^p_n(l)}{dl} = \\frac{-1}{(E^p_n(l))^2 \\sqrt{l^2 - k^2}\\sqrt{l^2 - h^2}}\n double l2 = l*l;\n double k2 = e->k2;\n double h2 = e->h2;\n double E;\n calcLame(e, n, p, l, signm, signn, &E);\n *Ideriv = -1.0 / (E*E*sqrt(l2 - k2)*sqrt(l2 - h2));\n\n ierr = PetscLogFlops(9);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"normFunction1MPFR\"\nPetscErrorCode normFunction1MPFR(mpfr_t *x, mpfr_t *val, FuncInfo2 *ctx)\n{\n PetscErrorCode ierr;\n PetscInt flopCount;\n mpfr_t top;\n PetscFunctionBegin;\n\n mpfr_init(top);\n \n flopCount = 0;\n int n = (*ctx).n;\n int p = (*ctx).p;\n int numeratorType = (*ctx).numeratorType;\n int denomSign = (*ctx).denomSign;\n //double h2 = (*ctx).e->h2;\n //double k2 = (*ctx).e->k2;\n EllipsoidalSystem *e = (*ctx).e;\n\n ierr = CalcLameMPFR((*ctx).e, n, p, *x, 1, 1, &top);\n mpfr_t *temp = &((*ctx).e->temp1);\n mpfr_mul(*temp, *x, *x, MPFR_RNDN);\n mpfr_sub(*val, e->hp_k2, *temp, MPFR_RNDN);\n mpfr_sub(*temp, *temp, e->hp_h2, MPFR_RNDN);\n mpfr_mul(*val, *temp, *val, MPFR_RNDN);\n mpfr_mul_d(*val, *val, (double) denomSign, MPFR_RNDN); flopCount += 5;\n if(mpfr_get_d(*val, MPFR_RNDN) < 0 && fabs(mpfr_get_d(*val, MPFR_RNDN)) < tol) {\n mpfr_mul_d(*val, *val, -1.0, MPFR_RNDN); flopCount++;\n }\n mpfr_sqrt(*temp, *val, MPFR_RNDN);\n mpfr_set(*val, top, MPFR_RNDN);\n mpfr_mul(*val, *val, top, MPFR_RNDN); flopCount += 2;\n flopCount += 3;\n if(numeratorType == 1) {\n mpfr_mul(*val, *val, *x, MPFR_RNDN);\n mpfr_mul(*val, *val, *x, MPFR_RNDN); flopCount += 2;\n }\n //printf(\"val before is %8.8e\\n\", mpfr_get_d(*val, MPFR_RNDN));\n //printf(\"denom before is %8.8e\\n\", mpfr_get_d(*temp, MPFR_RNDN));\n mpfr_div(*val, *val, *temp, MPFR_RNDN); flopCount++;\n //printf(\"val is %8.8e\\n\", mpfr_get_d(*val, MPFR_RNDN));\n\n mpfr_clear(top);\n \n ierr = PetscLogFlops(flopCount);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"normFunction1\"\nPetscErrorCode normFunction1(mpfr_t *x, mpfr_t *val, FuncInfo2 *ctx)\n{\n PetscErrorCode ierr;\n PetscInt flopCount;\n PetscFunctionBegin;\n flopCount = 0;\n \n int n = (*ctx).n;\n int p = (*ctx).p;\n int numeratorType = (*ctx).numeratorType;\n int denomSign = (*ctx).denomSign;\n //double h2 = (*ctx).e->h2;\n //double k2 = (*ctx).e->k2;\n EllipsoidalSystem *e = (*ctx).e;\n double top;\n calcLame((*ctx).e, n, p, mpfr_get_d(*x, MPFR_RNDN), 1, 1, &top);\n mpfr_t *temp = &((*ctx).e->temp1);\n mpfr_mul(*temp, *x, *x, MPFR_RNDN);\n mpfr_sub(*val, e->hp_k2, *temp, MPFR_RNDN);\n mpfr_sub(*temp, *temp, e->hp_h2, MPFR_RNDN);\n mpfr_mul(*val, *temp, *val, MPFR_RNDN);\n mpfr_mul_d(*val, *val, (double) denomSign, MPFR_RNDN); flopCount += 5;\n if(mpfr_get_d(*val, MPFR_RNDN) < 0 && fabs(mpfr_get_d(*val, MPFR_RNDN)) < tol) {\n mpfr_mul_d(*val, *val, -1.0, MPFR_RNDN); flopCount++;\n }\n mpfr_sqrt(*temp, *val, MPFR_RNDN);\n mpfr_set_d(*val, top, MPFR_RNDN);\n mpfr_mul_d(*val, *val, top, MPFR_RNDN); flopCount += 2;\n flopCount += 3;\n if(numeratorType == 1) {\n mpfr_mul(*val, *val, *x, MPFR_RNDN);\n mpfr_mul(*val, *val, *x, MPFR_RNDN); flopCount += 2;\n }\n //printf(\"val before is %8.8e\\n\", mpfr_get_d(*val, MPFR_RNDN));\n //printf(\"denom before is %8.8e\\n\", mpfr_get_d(*temp, MPFR_RNDN));\n mpfr_div(*val, *val, *temp, MPFR_RNDN); flopCount++;\n //printf(\"val is %8.8e\\n\", mpfr_get_d(*val, MPFR_RNDN));\n\n ierr = PetscLogFlops(flopCount);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\nvoid normFunction2(mpfr_t *x, mpfr_t *val, FuncInfo3 *ctx)\n{\n //printf(\"x: %8.8e\\n\", mpfr_get_d(*x, MPFR_RNDN));\n\n //double h2 = (*ctx).e->h2;\n //double k2 = (*ctx).e->k2;\n mpfr_t *temp = &((*ctx).e->temp1);\n EllipsoidalSystem *e = ctx->e;\n mpfr_set(*temp, e->hp_k2, MPFR_RNDN);\n mpfr_sub(*temp, *temp, e->hp_h2, MPFR_RNDN);\n mpfr_mul(*val, *x, e->hp_h2, MPFR_RNDN);\n mpfr_add(*val, *val, *temp, MPFR_RNDN);\n mpfr_sqrt(*val, *val, MPFR_RNDN);\n \n //printf(\"val 1: %8.8e\\n\", mpfr_get_d(*val, MPFR_RNDN));\n\n mpfr_abs(*temp, *x, MPFR_RNDN);\n //printf(\"absx(actual): %8.8e\\n\", mpfr_get_d(*temp, MPFR_RNDN));\n mpfr_sqrt(*temp, *temp, MPFR_RNDN);\n //printf(\"before multiply val 2: %8.8e\\n\", mpfr_get_d(*temp, MPFR_RNDN));\n //printf(\"absx: %8.8e\\n\", mpfr_get_d(*temp, MPFR_RNDN));\n mpfr_mul(*val, *val, *temp, MPFR_RNDN);\n\n //printf(\"val 2: %8.8e\\n\", mpfr_get_d(*val, MPFR_RNDN));\n\n mpfr_set_d(*temp, 1.0, MPFR_RNDN);\n mpfr_sub(*temp, *temp, *x, MPFR_RNDN);\n mpfr_sqrt(*temp, *temp, MPFR_RNDN);\n //printf(\"before multiply val 3: %8.8e\\n\", mpfr_get_d(*temp, MPFR_RNDN));\n mpfr_mul(*val, *val, *temp, MPFR_RNDN);\n //printf(\"val 3(denom): %8.8e\\n\", mpfr_get_d(*val, MPFR_RNDN));\n if((*ctx).numeratorType == 0) {\n //printf(\"numerator is 1.0\\n\");\n mpfr_d_div(*val, 1.0, *val, MPFR_RNDN);\n }\n else\n {\n mpfr_div(*val, *x, *val, MPFR_RNDN);\n //printf(\"numerator is x\\n\");\n }\n //printf(\"val: %8.8e\\n\", mpfr_get_d(*val, MPFR_RNDN));\n \n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"calcNormalizationMPFR\"\nPetscErrorCode calcNormalizationMPFR(EllipsoidalSystem *e, PetscInt n, PetscInt p, mpfr_t *normConst)\n{\n\n PetscErrorCode ierr;\n int err[4];\n mpfr_t integrals[4];\n mpfr_t temp;\n\n PetscFunctionBegin;\n\n mpfr_inits(integrals[0], integrals[1], integrals[2], integrals[3], temp, NULL);\n \n FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 };\n FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 };\n FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 };\n FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 };\n\n mpfr_t *mpfrzero = &(e->mpfrzero);\n mpfr_t *mpfrone = &(e->mpfrone);\n\n \n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, e->hp_h, e->hp_k, e->precision, integrals, &ctx1);\n\n err[1] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, e->hp_h, e->hp_k, e->precision, integrals+1, &ctx2);\n\n err[2] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, *mpfrzero, e->hp_h, e->precision, integrals+2, &ctx3);\n\n err[3] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, *mpfrzero, e->hp_h, e->precision, integrals+3, &ctx4);\n \n\n //*normConst = 8.0*(ints[2]*ints[1] - ints[0]*ints[3]);\n mpfr_mul(*normConst, integrals[2], integrals[1], MPFR_RNDN);\n mpfr_mul(temp, integrals[0], integrals[3], MPFR_RNDN);\n mpfr_sub(*normConst, *normConst, temp, MPFR_RNDN);\n mpfr_mul_d(*normConst, *normConst, 8.0, MPFR_RNDN);\n\n \n \n mpfr_clears(integrals[0], integrals[1], integrals[2], integrals[3], temp, NULL);\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"calcNormalization2MPFR\"\nPetscErrorCode calcNormalization2MPFR(EllipsoidalSystem *e, PetscInt n, PetscInt p, mpfr_t *intVals, mpfr_t *normConst)\n{\n\n PetscErrorCode ierr;\n int err[4];\n mpfr_t integrals[4];\n mpfr_t temp;\n\n PetscFunctionBegin;\n\n mpfr_init(temp);\n \n FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 };\n FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 };\n FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 };\n FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 };\n\n mpfr_t *mpfrzero = &(e->mpfrzero);\n mpfr_t *mpfrone = &(e->mpfrone);\n\n \n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, e->hp_h, e->hp_k, e->precision, intVals, &ctx1);\n\n err[1] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, e->hp_h, e->hp_k, e->precision, intVals+1, &ctx2);\n\n err[2] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, *mpfrzero, e->hp_h, e->precision, intVals+2, &ctx3);\n\n err[3] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, *mpfrzero, e->hp_h, e->precision, intVals+3, &ctx4);\n \n\n //*normConst = 8.0*(ints[2]*ints[1] - ints[0]*ints[3]);\n mpfr_mul(*normConst, intVals[2], intVals[1], MPFR_RNDN);\n mpfr_mul(temp, intVals[0], intVals[3], MPFR_RNDN);\n mpfr_sub(*normConst, *normConst, temp, MPFR_RNDN);\n mpfr_mul_d(*normConst, *normConst, 8.0, MPFR_RNDN);\n\n mpfr_clear(temp);\n\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"calcNormalization\"\nPetscErrorCode calcNormalization(EllipsoidalSystem *e, int n, int p, double *normConst)\n{\n PetscErrorCode ierr;\n \n PetscFunctionBegin;\n\n //double h = e->h;\n //double h2 = e->h2;\n //double k = e->k;\n //double k2 = e->k2;\n //The four integrals making up Romain (51)\n //structs containing f unction info\n FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 };\n FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 };\n FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 };\n FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 };\n\n \n int err[4];\n mpfr_t integrals[4];\n mpfr_inits(integrals[0], integrals[1], integrals[2], integrals[3], NULL);\n\n mpfr_t *mpfrzero = &(e->mpfrzero);\n mpfr_t *mpfrone = &(e->mpfrone);\n \n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, e->hp_h, e->hp_k, 16, integrals, &ctx1);\n\n err[1] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, e->hp_h, e->hp_k, 16, integrals+1, &ctx2);\n\n err[2] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, *mpfrzero, e->hp_h, 16, integrals+2, &ctx3);\n\n err[3] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, *mpfrzero, e->hp_h, 16, integrals+3, &ctx4);\n double ints[4];\n ints[0] = mpfr_get_d(integrals[0], MPFR_RNDN);\n ints[1] = mpfr_get_d(integrals[1], MPFR_RNDN);\n ints[2] = mpfr_get_d(integrals[2], MPFR_RNDN);\n ints[3] = mpfr_get_d(integrals[3], MPFR_RNDN);\n *normConst = 8.0*(ints[2]*ints[1] - ints[0]*ints[3]);\n\n\n mpfr_clears(integrals[0], integrals[1], integrals[2], integrals[3], NULL);\n ierr = PetscLogFlops(4);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n /*\n for(int i=0; i<4; ++i) {\n //printf(\"integrals[i] = %8.8e\\n\", i, integrals[i]);\n if(err[i])\n printf(\"Integral %d failed in calcNormalization\\n\", i);\n }\n\n //The basic elliptic integrals Romain (53)\n //He has an error in the equation, the prefactor should be h/2\n //structs containing function info\n FuncInfo3 ctx20 = { .e = e, .numeratorType = 0, .denomSign = -1 };\n FuncInfo3 ctx21 = { .e = e, .numeratorType = 1, .denomSign = -1 };\n FuncInfo3 ctx30 = { .e = e, .numeratorType = 0, .denomSign = 1 };\n FuncInfo3 ctx31 = { .e = e, .numeratorType = 1, .denomSign = 1 };\n double integrals2[4];\n\n mpfr_t *endpt = &(e->endpt);\n mpfr_set(*endpt, e->hp_k2, MPFR_RNDN);\n mpfr_div(*endpt, *endpt, e->hp_h2, MPFR_RNDN);\n mpfr_d_sub(*endpt, 1.0, *endpt, MPFR_RNDN);\n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *endpt, 14, integrals2, &ctx20);\n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *endpt, 14, integrals2+1, &ctx21);\n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *mpfrone, 14, integrals2+2, &ctx30);\n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *mpfrone, 14, integrals2+3, &ctx31);\n\n //Multiply by prefactor h/2\n for(int i=0; i<4; ++i) {\n //integrals2[i] = .5*h*integrals2[i];\n }\n\n\n for(int i=0; i<4; ++i) {\n if(err[i])\n printf(\"Integral2 %d failed in calcNormalization\\n\", i);\n }\n \n //Solve system for coefficients\n double *M = (double*) malloc(sizeof(double)*4);\n M[0] = integrals2[0]; //integrals2[0]; //transposed for lapack\n M[1] = integrals2[2]; //\n M[2] = integrals2[1]; //\n M[3] = integrals2[3]; //\n\n double *sol = (double*) malloc(sizeof(double)*2);\n sol[0] = integrals[0];\n sol[1] = integrals[2];\n\n //variables to store solutions\n double alpha, beta, A, B;\n\n char tchar = 'N';\n int two = 2;\n int one = 1;\n\n //ipiv pivot (output for dgetrf, input for dgetrs)\n int *ipiv = (int*) malloc(sizeof(int)*2);\n int info;\n\n //first solve\n dgetrf_(&two, &two, M, &two, ipiv, &info);\n dgetrs_(&tchar, &two, &one, M, &two, ipiv, sol, &two, &info);\n alpha = sol[0];\n beta = sol[1];\n\n sol[0] = integrals[1];\n sol[1] = integrals[3];\n\n //second solve\n dgetrs_(&tchar, &two, &one, M, &two, ipiv, sol, &two, &info);\n A = sol[0];\n B = sol[1];\n free(sol);\n free(M);\n free(ipiv);\n //Romain (54)\n //The factor 8 is from Dassios (see discussion in Deng), since we integrate over the whole ellipsoid rather than just one octant\n if(fabs(alpha*B - beta*A) == 0) {\n printf(\"\\n\\nbad\\n\\n\\n\\n\");\n printf(\"alpha*B: %16.16e\\n\", alpha*B);\n printf(\"beta*A: %16.16e\\n\", beta*A);\n return 8 * (PETSC_PI/2.0)*1e-14;\n }\n return 8 * (PETSC_PI/2.0)*(alpha*B - beta*A);\n */\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"calcNormalization2\"\nPetscErrorCode calcNormalization2(EllipsoidalSystem *e, PetscInt n, PetscInt p, double *intVals, double *normConst)\n{\n PetscErrorCode ierr;\n \n PetscFunctionBegin;\n\n //double h = e->h;\n //double h2 = e->h2;\n //double k = e->k;\n //double k2 = e->k2;\n //The four integrals making up Romain (51)\n //structs containing f unction info\n FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 };\n FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 };\n FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 };\n FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 };\n int err[4];\n double integrals[4];\n mpfr_t integ[4];\n mpfr_inits(integ[0], integ[1], integ[2], integ[3], NULL);\n\n mpfr_t *mpfrzero = &(e->mpfrzero);\n mpfr_t *mpfrone = &(e->mpfrone);\n \n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, e->hp_h, e->hp_k, 16, integ, &ctx1);\n integrals[0] = mpfr_get_d(integ[0], MPFR_RNDN);\n intVals[0] = integrals[0];\n \n err[1] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, e->hp_h, e->hp_k, 16, integ+1, &ctx2);\n integrals[1] = mpfr_get_d(integ[1], MPFR_RNDN);\n intVals[1] = integrals[1];\n \n err[2] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, *mpfrzero, e->hp_h, 16, integ+2, &ctx3);\n integrals[2] = mpfr_get_d(integ[2], MPFR_RNDN);\n intVals[2] = integrals[2];\n\n err[3] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, *mpfrzero, e->hp_h, 16, integ+3, &ctx4);\n integrals[3] = mpfr_get_d(integ[3], MPFR_RNDN);\n intVals[3] = integrals[3];\n *normConst = 8.0*(integrals[2]*integrals[1] - integrals[0]*integrals[3]);\n\n mpfr_clears(integ[0], integ[1], integ[2], integ[3], NULL);\n ierr = PetscLogFlops(4);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n /*\n for(int i=0; i<4; ++i) {\n //printf(\"integrals[i] = %8.8e\\n\", i, integrals[i]);\n if(err[i])\n printf(\"Integral %d failed in calcNormalization\\n\", i);\n }\n\n //The basic elliptic integrals Romain (53)\n //He has an error in the equation, the prefactor should be h/2\n //structs containing function info\n FuncInfo3 ctx20 = { .e = e, .numeratorType = 0, .denomSign = -1 };\n FuncInfo3 ctx21 = { .e = e, .numeratorType = 1, .denomSign = -1 };\n FuncInfo3 ctx30 = { .e = e, .numeratorType = 0, .denomSign = 1 };\n FuncInfo3 ctx31 = { .e = e, .numeratorType = 1, .denomSign = 1 };\n double integrals2[4];\n\n mpfr_t *endpt = &(e->endpt);\n mpfr_set(*endpt, e->hp_k2, MPFR_RNDN);\n mpfr_div(*endpt, *endpt, e->hp_h2, MPFR_RNDN);\n mpfr_d_sub(*endpt, 1.0, *endpt, MPFR_RNDN);\n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *endpt, 14, integrals2, &ctx20);\n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *endpt, 14, integrals2+1, &ctx21);\n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *mpfrone, 14, integrals2+2, &ctx30);\n err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *mpfrone, 14, integrals2+3, &ctx31);\n\n //Multiply by prefactor h/2\n for(int i=0; i<4; ++i) {\n //integrals2[i] = .5*h*integrals2[i];\n }\n\n\n for(int i=0; i<4; ++i) {\n if(err[i])\n printf(\"Integral2 %d failed in calcNormalization\\n\", i);\n }\n \n //Solve system for coefficients\n double *M = (double*) malloc(sizeof(double)*4);\n M[0] = integrals2[0]; //integrals2[0]; //transposed for lapack\n M[1] = integrals2[2]; //\n M[2] = integrals2[1]; //\n M[3] = integrals2[3]; //\n\n double *sol = (double*) malloc(sizeof(double)*2);\n sol[0] = integrals[0];\n sol[1] = integrals[2];\n\n //variables to store solutions\n double alpha, beta, A, B;\n\n char tchar = 'N';\n int two = 2;\n int one = 1;\n\n //ipiv pivot (output for dgetrf, input for dgetrs)\n int *ipiv = (int*) malloc(sizeof(int)*2);\n int info;\n\n //first solve\n dgetrf_(&two, &two, M, &two, ipiv, &info);\n dgetrs_(&tchar, &two, &one, M, &two, ipiv, sol, &two, &info);\n alpha = sol[0];\n beta = sol[1];\n\n sol[0] = integrals[1];\n sol[1] = integrals[3];\n\n //second solve\n dgetrs_(&tchar, &two, &one, M, &two, ipiv, sol, &two, &info);\n A = sol[0];\n B = sol[1];\n free(sol);\n free(M);\n free(ipiv);\n //Romain (54)\n //The factor 8 is from Dassios (see discussion in Deng), since we integrate over the whole ellipsoid rather than just one octant\n if(fabs(alpha*B - beta*A) == 0) {\n printf(\"\\n\\nbad\\n\\n\\n\\n\");\n printf(\"alpha*B: %16.16e\\n\", alpha*B);\n printf(\"beta*A: %16.16e\\n\", beta*A);\n return 8 * (PETSC_PI/2.0)*1e-14;\n }\n return 8 * (PETSC_PI/2.0)*(alpha*B - beta*A);\n */\n}\n\n//calculate the eigenvalues of the surface operator\n#undef __FUNCT__\n#define __FUNCT__ \"calcSurfaceOperatorEigenvalues\"\nPetscErrorCode calcSurfaceOperatorEigenvalues(EllipsoidalSystem *e, int n, int p, double l, int signm, int signn, double *sol)\n{\n PetscErrorCode ierr;\n\n PetscFunctionBegin;\n\n double a = e->a;\n double b = e->b;\n double c = e->c;\n double Inp;\n ierr = calcI(e, n, p, l, signm, signn, &Inp);CHKERRQ(ierr);\n double Enp;\n ierr = calcLame(e, n, p, l, signm, signn, &Enp);CHKERRQ(ierr);\n double EnpDer;\n calcLameDerivative(e, n, p, l, signm, signn, &EnpDer);\n\n *sol = (2.0*a*b*c*(EnpDer/a)*Inp*Enp - 1)/2;\n \n ierr = PetscLogFlops(9);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"integrateMPFR\"\nPetscErrorCode integrateMPFR(PetscErrorCode (*f)(mpfr_t *,mpfr_t*,void*), EllipsoidalSystem *e, mpfr_t a, mpfr_t b, int digits, mpfr_t *integral, void *ctx) \n{\n PetscErrorCode ierr;\n PetscInt flopCount;\n PetscFunctionBegin;\n flopCount = 0;\n \n //printf(\"can we get out of here?\\n\");\n const int safetyFactor = 2; /* Calculate abcissa until 2*p digits */\n int p = e->precision; /* Digits of precision in the evaluation */\n int l = 0; /* Level of refinement, h = 2^{-l} */\n mpfr_t *alpha = &(e->alpha); /* Half-width of the integration interval */\n mpfr_t *beta = &(e->beta); /* Center of the integration interval */\n mpfr_t *h = &(e->h_step); /* Step size, length between x_k */\n mpfr_t *osum = &(e->osum); /* Integral on last level */\n mpfr_t *psum = &(e->psum); /* Integral on the level before the last level */\n mpfr_t *sum = &(e->sum); /* Integral on current level */\n mpfr_t *yk = &(e->yk); /* Quadrature point 1 - x_k on reference domain [-1, 1] */\n mpfr_t *lx = &(e->lx);\n mpfr_t *rx = &(e->rx); /* Quadrature points to the left and right of 0 on the real domain [a, b] */\n mpfr_t *wk = &(e->wk); /* Quadrature weight at x_k */\n mpfr_t *lval = &(e->lval);\n mpfr_t *rval = &(e->rval); /* Terms in the quadature *sum to the left and right of 0 */\n mpfr_t *pi2 = &(e->pi2);\n mpfr_t *kh = &(e->kh);\n mpfr_t *msinh = &(e->msinh);\n mpfr_t *mcosh = &(e->mcosh);\n mpfr_t *maxTerm = &(e->maxTerm);\n mpfr_t *curTerm = &(e->curTerm);\n mpfr_t *tmp = &(e->tmp);\n int d; /* Digits of precision in the integral */\n int counter = 1;\n\n if(digits <= 0) {\n printf(\"Please give a positive number of significant digits\\n\");\n return 1;\n }\n\n /* Create high precision storage */\n\n\n /* Initialization */\n mpfr_set(*alpha, b, MPFR_RNDN);\n mpfr_sub(*alpha, *alpha, a, MPFR_RNDN);\n mpfr_mul_d(*alpha, *alpha, 0.5, MPFR_RNDN);\n mpfr_set(*beta, b, MPFR_RNDN);\n mpfr_add(*beta, *beta, a, MPFR_RNDN);\n mpfr_mul_d(*beta, *beta, 0.5, MPFR_RNDN);\n mpfr_set_d(*osum, 0.0, MPFR_RNDN);\n mpfr_set_d(*psum, 0.0, MPFR_RNDN);\n mpfr_set_d(*h, 1.0, MPFR_RNDN);\n mpfr_const_pi(*pi2, MPFR_RNDN);\n mpfr_mul_d(*pi2, *pi2, 0.5, MPFR_RNDN); flopCount += 5;\n\n /* Center term */\n //mpfr_set_d(*lx, 0.5*(b+a), MPFR_RNDN);\n mpfr_set(*lx, b, MPFR_RNDN);\n mpfr_add(*lx, *lx, a, MPFR_RNDN);\n mpfr_mul_d(*lx, *lx, .5, MPFR_RNDN);\n f(lx, sum, ctx);\n mpfr_mul(*sum, *sum, *alpha, MPFR_RNDN);\n mpfr_mul(*sum, *sum, *pi2, MPFR_RNDN); flopCount += 4;\n\n\n //DELETE LATER\n int maxL = 6;\n double *SUMS = (double*) malloc(sizeof(double)*maxL);\n int *insideSums = (int*) malloc(sizeof(int)*maxL);\n\n\n /* */\n do {\n double d1, d2, d3, d4;\n int k = 1;\n\n ++l;\n\n mpfr_set_d(*maxTerm, 0.0, MPFR_RNDN);\n /* PetscPrintf(PETSC_COMM_SELF, \"LEVEL %D sum: %15.15f\\n\", l, sum); */\n //printf(\"LEVEL %d sem: %15.15f\\n\", l, sum);\n /* At each level of refinement, h --> h/2 and sum --> sum/2 */\n mpfr_set(*psum, *osum, MPFR_RNDN);\n mpfr_set(*osum, *sum, MPFR_RNDN);\n mpfr_mul_d(*h, *h, 0.5, MPFR_RNDN);\n mpfr_mul_d(*sum, *sum, 0.5, MPFR_RNDN); flopCount += 2;\n\n do {\n //printf(\"doot\\n\");\n //if(mpfr_number_p(sum) == 0)\n\t//printf(\"at iterations %d sum is %8.8e a: %8.8f b: %8.8f\\n\", k, mpfr_get_d(sum, MPFR_RNDN), a, b);\n mpfr_set_si(*kh, k, MPFR_RNDN);\n mpfr_mul(*kh, *kh, *h, MPFR_RNDN);\n /* Weight */\n mpfr_set(*wk, *h, MPFR_RNDN);\n mpfr_sinh_cosh(*msinh, *mcosh, *kh, MPFR_RNDN);\n mpfr_mul(*msinh, *msinh, *pi2, MPFR_RNDN);\n mpfr_mul(*mcosh, *mcosh, *pi2, MPFR_RNDN);\n mpfr_cosh(*tmp, *msinh, MPFR_RNDN);\n mpfr_sqr(*tmp, *tmp, MPFR_RNDN);\n mpfr_mul(*wk, *wk, *mcosh, MPFR_RNDN);\n mpfr_div(*wk, *wk, *tmp, MPFR_RNDN); flopCount += 8;\n /* Abscissa */\n mpfr_set_d(*yk, 1.0, MPFR_RNDZ);\n mpfr_cosh(*tmp, *msinh, MPFR_RNDN);\n mpfr_div(*yk, *yk, *tmp, MPFR_RNDZ);\n mpfr_exp(*tmp, *msinh, MPFR_RNDN);\n mpfr_div(*yk, *yk, *tmp, MPFR_RNDZ); flopCount += 4;\n /* Quadrature points */\n mpfr_sub_d(*lx, *yk, 1.0, MPFR_RNDZ);\n mpfr_mul(*lx, *lx, *alpha, MPFR_RNDU);\n mpfr_add(*lx, *lx, *beta, MPFR_RNDU);\n mpfr_d_sub(*rx, 1.0, *yk, MPFR_RNDZ);\n mpfr_mul(*rx, *rx, *alpha, MPFR_RNDD);\n mpfr_add(*rx, *rx, *beta, MPFR_RNDD); flopCount += 4;\n //printf(\"poot\\n\");\n /* Evaluation */\n f(lx, lval, ctx);\n //printf(\"lval: %8.8e\\n\", mpfr_get_d(lval, MPFR_RNDN));\n f(rx, rval, ctx);\n //printf(\"rval: %8.8e\\n\", mpfr_get_d(rval, MPFR_RNDN));\n //check if function evaluates to inf or nan\n int update = 1;\n if(mpfr_number_p(*lval) == 0) {\n\tupdate = 0;\n\t//printf(\"lval is nan/inf *lx: %15.15e\\n\", mpfr_get_d(*lx, MPFR_RNDN));\n }\n if(mpfr_number_p(*rval) == 0) {\n\tupdate = 0;\n\t//printf(\"rval is nan/inf\\n\");\n }\n /* Update if function not inf or nan*/\n if(update == 1) {\n\tmpfr_mul(*tmp, *wk, *alpha, MPFR_RNDN);\n\tmpfr_mul(*tmp, *tmp, *lval, MPFR_RNDN);\n\tmpfr_add(*sum, *sum, *tmp, MPFR_RNDN);\n\tmpfr_abs(*tmp, *tmp, MPFR_RNDN);\n\tmpfr_max(*maxTerm, *maxTerm, *tmp, MPFR_RNDN);\n\tmpfr_set(*curTerm, *tmp, MPFR_RNDN);\n\tmpfr_mul(*tmp, *wk, *alpha, MPFR_RNDN);\n\tmpfr_mul(*tmp, *tmp, *rval, MPFR_RNDN);\n\tmpfr_add(*sum, *sum, *tmp, MPFR_RNDN);\n\tmpfr_abs(*tmp, *tmp, MPFR_RNDN);\n\tmpfr_max(*maxTerm, *maxTerm, *tmp, MPFR_RNDN);\n\tmpfr_max(*curTerm, *curTerm, *tmp, MPFR_RNDN); flopCount += 8;\n\tcounter += 2;\n }\n /* if (l == 1) printf(\"k is %d and sum is %15.15f and *wk is %15.15f\\n\", k, sum, *wk); */\n ++k;\n /* Only need to evaluate every other point on refined levels */\n if (l != 1) ++k;\n mpfr_log10(*tmp, *wk, MPFR_RNDN); flopCount++;\n mpfr_abs(*tmp, *tmp, MPFR_RNDN);\n } while (mpfr_get_d(*tmp, MPFR_RNDN) < safetyFactor*p); /* Only need to evaluate sum until weights are < 32 digits\\\n\t\t\t\t\t\t\t of precision */\n SUMS[l-1] = mpfr_get_d(*sum, MPFR_RNDN);\n insideSums[l-1] = counter;\n mpfr_sub(*tmp, *sum, *osum, MPFR_RNDN);\n mpfr_abs(*tmp, *tmp, MPFR_RNDN);\n mpfr_log10(*tmp, *tmp, MPFR_RNDN);\n d1 = mpfr_get_d(*tmp, MPFR_RNDN);\n mpfr_sub(*tmp, *sum, *psum, MPFR_RNDN);\n mpfr_abs(*tmp, *tmp, MPFR_RNDN);\n mpfr_log10(*tmp, *tmp, MPFR_RNDN);\n d2 = mpfr_get_d(*tmp, MPFR_RNDN);\n mpfr_log10(*tmp, *maxTerm, MPFR_RNDN);\n d3 = mpfr_get_d(*tmp, MPFR_RNDN) - p;\n mpfr_log10(*tmp, *curTerm, MPFR_RNDN);\n d4 = mpfr_get_d(*tmp, MPFR_RNDN);\n d = (int) fabs(min(0, max(max(max((d1*d1)/d2, 2*d1), d3), d4))); flopCount += 9;\n\n } while (d < digits && l < maxL);\n\n mpfr_set(*integral, *sum, MPFR_RNDN);\n //*integral = mpfr_get_d(*sum, MPFR_RNDN);\n /* Cleanup */\n //mpfr_clears(*alpha, *beta, h, sum, *osum, *psum, *yk, *wk, *lx, *rx, *tmp, *maxTerm, *curTerm, *pi2, *kh, *msinh, *mcosh, lval, rval, NULL);\n //printf(\"yes we can\\n\");\n //printf(\"levels: %d\\n\", l);\n /*\n if(l == maxL) {\n for(int i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \"shared/libklp_matrix_header.h\"\n#include \"shared/libtpl_header.h\"\n#include \"population_constants.h\"\n#include \"population_params.h\"\n#include \"population_initializers.h\"\n#include \"population_functions.h\"\n\nvoid population_from_row_ordered_transition_matrix(const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, TRANSITION_MATRIX row_transition_matrix) {\n if (parameters.equilibrium) {\n equilibrium_from_row_ordered_transition_matrix(klp_params, parameters, row_transition_matrix);\n } else {\n population_proportion_from_row_ordered_transition_matrix(klp_params, parameters, row_transition_matrix);\n }\n}\n\nvoid equilibrium_from_row_ordered_transition_matrix(const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, TRANSITION_MATRIX row_transition_matrix) {\n EIGENSYSTEM eigensystem;\n \n eigensystem = eigensystem_from_row_ordered_transition_matrix(row_transition_matrix);\n print_equilibrium(eigensystem, klp_params, parameters);\n \n}\n\nvoid population_proportion_from_row_ordered_transition_matrix(const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, TRANSITION_MATRIX row_transition_matrix) {\n EIGENSYSTEM eigensystem;\n \n eigensystem = eigensystem_from_row_ordered_transition_matrix(row_transition_matrix);\n print_population_proportion(eigensystem, klp_params, parameters);\n}\n\nEIGENSYSTEM eigensystem_from_row_ordered_transition_matrix(TRANSITION_MATRIX row_transition_matrix) {\n TRANSITION_MATRIX column_transition_matrix;\n EIGENSYSTEM eigensystem;\n \n column_transition_matrix = transpose_matrix(row_transition_matrix);\n eigensystem = convert_transition_matrix_to_eigenvectors(column_transition_matrix);\n invert_matrix(&eigensystem);\n \n return eigensystem;\n}\n\nTRANSITION_MATRIX convert_structures_to_transition_matrix(const SOLUTION* all_structures, int num_structures) {\n // This code to convert the list of structures to a transition matrix does not ensure that there are only single b.p. moves.\n int i, j;\n double col_sum;\n TRANSITION_MATRIX transition_matrix = init_transition_matrix(num_structures, 'R');\n \n for (i = 0; i < num_structures; ++i) {\n col_sum = 0;\n \n for (j = 0; j < num_structures; ++j) {\n if (i != j) {\n T_COL_ORDER(transition_matrix, i, j) = \\\n MIN(1, exp(-((double)all_structures[j].energy - (double)all_structures[i].energy) / VIENNA_RT));\n \n col_sum += T_COL_ORDER(transition_matrix, i, j);\n#ifdef INSANE_DEBUG\n printf(\"%d\\t%d\\t%.4e\\n\", i, j, T_COL_ORDER(transition_matrix, i, j));\n#endif\n }\n }\n \n#ifdef INSANE_DEBUG\n printf(\"%d col_sum:\\t%.4e\\n\\n\", i, col_sum);\n#endif\n T_COL_ORDER(transition_matrix, i, i) = -col_sum;\n }\n \n return transition_matrix;\n}\n\nEIGENSYSTEM convert_transition_matrix_to_eigenvectors(TRANSITION_MATRIX transition_matrix) {\n // Generates right eigenvectors from a column-ordered transition rate matrix, and saves them in a one-dimensional column-ordered array (eigensystem.vectors).\n int i, j;\n EIGENSYSTEM eigensystem;\n eigensystem = init_eigensystem(transition_matrix.row_length);\n gsl_matrix_view matrix_view = gsl_matrix_view_array(transition_matrix.matrix, eigensystem.length, eigensystem.length);\n gsl_vector_complex* eigenvalues = gsl_vector_complex_alloc(eigensystem.length);\n gsl_matrix_complex* eigenvectors = gsl_matrix_complex_alloc(eigensystem.length, eigensystem.length);\n gsl_eigen_nonsymmv_workspace* workspace = gsl_eigen_nonsymmv_alloc(eigensystem.length);\n gsl_eigen_nonsymmv_params(1, workspace);\n gsl_eigen_nonsymmv(&matrix_view.matrix, eigenvalues, eigenvectors, workspace);\n gsl_eigen_nonsymmv_free(workspace);\n \n for (i = 0; i < eigensystem.length; ++i) {\n eigensystem.values[i] = GSL_REAL(gsl_vector_complex_get(eigenvalues, i));\n gsl_vector_complex_view eigenvector = gsl_matrix_complex_column(eigenvectors, i);\n \n for (j = 0; j < eigensystem.length; ++j) {\n E_COL_ORDER(eigensystem.vectors, i, j, eigensystem.length) = GSL_REAL(gsl_vector_complex_get(&eigenvector.vector, j));\n }\n }\n \n free_transition_matrix(transition_matrix);\n gsl_vector_complex_free(eigenvalues);\n gsl_matrix_complex_free(eigenvectors);\n return eigensystem;\n}\n\nvoid invert_matrix(EIGENSYSTEM* eigensystem) {\n int i, j, signum;\n gsl_matrix* matrix_to_invert = gsl_matrix_alloc(eigensystem->length, eigensystem->length);\n gsl_matrix* inversion_matrix = gsl_matrix_alloc(eigensystem->length, eigensystem->length);\n gsl_permutation* permutation = gsl_permutation_alloc(eigensystem->length);\n \n for (i = 0; i < eigensystem->length; ++i) {\n for (j = 0; j < eigensystem->length; ++j) {\n gsl_matrix_set(matrix_to_invert, i, j, E_ROW_ORDER(eigensystem->vectors, i, j, eigensystem->length));\n }\n }\n \n gsl_linalg_LU_decomp(matrix_to_invert, permutation, &signum);\n gsl_linalg_LU_invert(matrix_to_invert, permutation, inversion_matrix);\n \n for (i = 0; i < eigensystem->length; ++i) {\n for (j = 0; j < eigensystem->length; ++j) {\n E_ROW_ORDER(eigensystem->inverse_vectors, i, j, eigensystem->length) = gsl_matrix_get(inversion_matrix, i, j);\n }\n }\n \n gsl_matrix_free(matrix_to_invert);\n gsl_matrix_free(inversion_matrix);\n gsl_permutation_free(permutation);\n}\n\ndouble probability_at_logtime(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, double timepoint, int start_index, int target_index) {\n // This function is hard-wired to only consider the kinetics for folding from a distribution where p_{0}(start_index) == 1.\n int i;\n double cumulative_probability = 0;\n \n if (klp_params.start_state < 0 || klp_params.end_state < 0) {\n if (klp_params.start_state < 0) {\n fprintf(stderr, \"Error: the starting structure could not be found. Usually this means that you did not specify an explicit starting structure so the empty structure was used, but the energy band was not wide enough for RNAsubopt to sample it.\\n\");\n }\n \n if (klp_params.end_state < 0) {\n fprintf(stderr, \"Error: the ending structure could not be found. Usually this means that you did explicitly provided a suboptimal ending structure, but the energy band was not wide enough for RNAsubopt to sample it.\\n\");\n }\n \n abort();\n }\n \n for (i = 0; i < eigensystem.length; ++i) {\n cumulative_probability +=\n E_ROW_ORDER(eigensystem.vectors, target_index, i, eigensystem.length) *\n E_ROW_ORDER(eigensystem.inverse_vectors, i, start_index, eigensystem.length) *\n exp(eigensystem.values[i] * pow(10, timepoint));\n }\n \n return cumulative_probability;\n}\n\nvoid find_key_structure_indices_in_structure_list(KLP_PARAMS* klp_params, const POPULATION_PARAMS parameters, const SOLUTION* all_structures, int num_structures) {\n int i;\n \n for (i = 0; i < num_structures; ++i) {\n if (klp_params->start_state == -1) {\n if (!strcmp(parameters.start_structure, all_structures[i].structure)) {\n klp_params->start_state = i;\n }\n }\n \n if (klp_params->end_state == -1) {\n if (!strcmp(parameters.end_structure, all_structures[i].structure)) {\n klp_params->end_state = i;\n }\n }\n }\n}\n\nvoid serialize_eigensystem(const EIGENSYSTEM eigensystem, const POPULATION_PARAMS parameters) {\n tpl_node* tpl;\n int i;\n double value, vector, inverse_vector;\n tpl = tpl_map(\"iA(f)A(f)A(f)\", &eigensystem.length, &value, &vector, &inverse_vector);\n tpl_pack(tpl, 0);\n \n for (i = 0; i < eigensystem.length * eigensystem.length; ++i) {\n if (i < eigensystem.length) {\n value = eigensystem.values[i];\n tpl_pack(tpl, 1);\n }\n \n vector = eigensystem.vectors[i];\n inverse_vector = eigensystem.inverse_vectors[i];\n \n tpl_pack(tpl, 2);\n tpl_pack(tpl, 3);\n }\n \n tpl_dump(tpl, TPL_FILE, parameters.filename);\n tpl_free(tpl);\n}\n\nEIGENSYSTEM deserialize_eigensystem(const POPULATION_PARAMS parameters) {\n tpl_node* tpl;\n int i, length;\n double value, vector, inverse_vector;\n EIGENSYSTEM eigensystem;\n \n tpl = tpl_map(\"iA(f)A(f)A(f)\", &length, &value, &vector, &inverse_vector);\n tpl_load(tpl, TPL_FILE, parameters.filename);\n tpl_unpack(tpl, 0);\n \n eigensystem = init_eigensystem(length);\n \n for (i = 0; i < eigensystem.length * eigensystem.length; ++i) {\n if (i < eigensystem.length) {\n tpl_unpack(tpl, 1);\n eigensystem.values[i] = value;\n }\n \n tpl_unpack(tpl, 2);\n tpl_unpack(tpl, 3);\n \n eigensystem.vectors[i] = vector;\n eigensystem.inverse_vectors[i] = inverse_vector;\n }\n \n tpl_free(tpl);\n \n return eigensystem;\n}\n\nvoid ensure_key_structures_and_energies_assigned(POPULATION_PARAMS* parameters) {\n int i, seq_length = strlen(parameters->sequence);\n \n if (parameters->start_structure == NULL) {\n parameters->start_structure = malloc((seq_length + 1) * sizeof(char));\n \n for (i = 0; i < seq_length; ++i) {\n parameters->start_structure[i] = '.';\n }\n \n parameters->start_structure[i] = '\\0';\n }\n \n if (parameters->end_structure == NULL) {\n set_end_structure(parameters);\n }\n}\n\nvoid set_end_structure(POPULATION_PARAMS* parameters) {\n paramT* vienna_params;\n \n vienna_params = init_vienna_params(*parameters);\n parameters->end_structure = malloc((strlen(parameters->sequence) + 1) * sizeof(char));\n fold_par(parameters->sequence, parameters->end_structure, vienna_params, 0, 0);\n}\n\nSOLUTION* sample_structures(const POPULATION_PARAMS parameters) {\n double energy_cap;\n paramT* vienna_params;\n \n vienna_params = init_vienna_params(parameters);\n energy_cap = parameters.energy_cap ? (int)round(parameters.energy_cap * 100) : INF;\n \n return subopt_par(parameters.sequence, parameters.start_structure, vienna_params, energy_cap, 0, 0, NULL);\n}\n\ndouble estimate_equilibrium(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, int eigensystem_index) {\n int i, everything_in_equilibrium = 0;\n double equilibrium_time;\n \n equilibrium_time = soft_bound_for_population_proportion(eigensystem, klp_params, parameters, eigensystem_index, parameters.end_time, 1);\n \n#ifdef INSANE_DEBUG\n printf(\"equilibrium_time: %f\\n\", equilibrium_time);\n#endif\n \n while (equilibrium_time >= parameters.start_time && index_in_equilibrium_within_window(eigensystem, klp_params, parameters, eigensystem_index, equilibrium_time)) {\n equilibrium_time -= parameters.step_size;\n }\n \n#ifdef INSANE_DEBUG\n printf(\"equilibrium_time after backtrack: %f\\n\", equilibrium_time);\n#endif\n \n if (equilibrium_time < parameters.start_time) {\n return NEG_INF(parameters);\n } else {\n while (equilibrium_time <= parameters.end_time) {\n if (parameters.all_subpop_for_eq) {\n everything_in_equilibrium = 1;\n \n for (i = 0; i < eigensystem.length && everything_in_equilibrium; ++i) {\n everything_in_equilibrium = index_in_equilibrium_within_window(eigensystem, klp_params, parameters, i, equilibrium_time);\n }\n } else {\n everything_in_equilibrium = index_in_equilibrium_within_window(eigensystem, klp_params, parameters, eigensystem_index, equilibrium_time);\n }\n \n if (everything_in_equilibrium) {\n return equilibrium_time;\n } else {\n equilibrium_time += parameters.step_size;\n }\n }\n \n return POS_INF(parameters);\n }\n}\n\ndouble soft_bound_for_population_proportion(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, int eigensystem_index, double final_time, int sign) {\n double current_probability, final_probability, current_time, temp_time, last_time = final_time;\n \n if (parameters.soft_bounds) {\n last_time = final_time;\n current_time = parameters.start_time + (parameters.end_time - parameters.start_time) / 2.0;\n current_probability = probability_at_logtime(eigensystem, klp_params, current_time, klp_params.start_state, eigensystem_index);\n final_probability = probability_at_logtime(eigensystem, klp_params, final_time, klp_params.start_state, eigensystem_index);\n \n while (fabs(current_time - last_time) > parameters.step_size) {\n current_probability = probability_at_logtime(eigensystem, klp_params, current_time, klp_params.start_state, eigensystem_index);\n \n#ifdef INSANE_DEBUG\n printf(\"current_time: %+.4f\\tlast_time: %+.4f\\tp(%d, current): %.4f\\tp(%d, target): %.4f\\n\", current_time, last_time, eigensystem_index, current_probability, eigensystem_index, final_probability);\n#endif\n \n temp_time = current_time;\n \n if (fabs(current_probability - final_probability) > parameters.delta) {\n current_time += sign * fabs(last_time - current_time) / 2.0;\n } else {\n current_time -= sign * fabs(last_time - current_time) / 2.0;\n }\n \n last_time = temp_time;\n }\n \n#ifdef INSANE_DEBUG\n printf(\"Bounded at %+f within %f of requested delta, %f\\n\\n\", current_time, fabs(current_probability - final_probability), parameters.delta);\n#endif\n \n return round(current_time / parameters.step_size) * parameters.step_size;\n } else {\n return final_time;\n }\n}\n\nint index_in_equilibrium_within_window(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, int eigensystem_index, double logtime) {\n int i;\n double current_proportion, future_proportion;\n \n current_proportion = probability_at_logtime(\n eigensystem,\n klp_params,\n logtime,\n klp_params.start_state,\n eigensystem_index\n );\n \n for (i = 1; i < parameters.window_size; ++i) {\n future_proportion = probability_at_logtime(\n eigensystem,\n klp_params,\n logtime + parameters.step_size * i,\n klp_params.start_state,\n eigensystem_index\n );\n \n#ifdef INSANE_DEBUG\n printf(\n \"current_time: %f, window_time: %f, index: %d, abs(p(window) - p(current)): %e, within epsilon?: %s\\n\",\n logtime,\n logtime + parameters.step_size * i,\n eigensystem_index,\n fabs(current_proportion - future_proportion),\n fabs(current_proportion - future_proportion) < parameters.epsilon ? \"yes\" : \"no\"\n );\n#endif\n \n if (fabs(current_proportion - future_proportion) > parameters.epsilon) {\n return 0;\n }\n }\n \n return 1;\n}\n\nstatic int compare_tuple(const void* pa, const void* pb) {\n const double* a = *(const double**)pa;\n const double* b = *(const double**)pb;\n \n if (a[0] > b[0]) {\n return 1;\n } else if (a[0] < b[0]) {\n return -1;\n } else {\n return 0;\n }\n}\n\nint* array_of_indices_to_output(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, double logtime) {\n int i, output_size;\n int* id_list;\n double** final_proportions;\n \n switch (parameters.num_subpop_to_show) {\n case -1:\n output_size = 2;\n break;\n \n case 0:\n output_size = eigensystem.length;\n break;\n \n default:\n output_size = parameters.num_subpop_to_show;\n }\n \n#ifdef INSANE_DEBUG\n printf(\"number of subpopulations to output: %d\\n\", output_size);\n#endif\n \n id_list = malloc((output_size + 1) * sizeof(int));\n id_list[0] = output_size;\n \n if (parameters.num_subpop_to_show == -1) {\n id_list[1] = klp_params.end_state;\n id_list[2] = klp_params.start_state;\n } else {\n final_proportions = malloc(eigensystem.length * sizeof(double*));\n \n for (i = 0; i < eigensystem.length; ++i) {\n final_proportions[i] = malloc(2 * sizeof(double));\n }\n \n for (i = 0; i < eigensystem.length; ++i) {\n final_proportions[i][0] = probability_at_logtime(eigensystem, klp_params, logtime, klp_params.start_state, i);\n final_proportions[i][1] = i;\n }\n \n#ifdef INSANE_DEBUG\n printf(\"\\nBefore calling qsort:\\n\\n\");\n \n for (i = 0; i < eigensystem.length; ++i) {\n printf(\"final_proportions[%d]\\t%.8f\\n\", (int)final_proportions[i][1], final_proportions[i][0]);\n }\n \n#endif\n \n qsort(final_proportions, eigensystem.length, sizeof(final_proportions[0]), compare_tuple);\n \n#ifdef INSANE_DEBUG\n printf(\"\\nAfter calling qsort:\\n\\n\");\n \n for (i = 0; i < eigensystem.length; ++i) {\n printf(\"final_proportions[%d]\\t%.8f\\n\", (int)final_proportions[i][1], final_proportions[i][0]);\n }\n \n printf(\"\\nIndices to keep:\\n\\n\");\n#endif\n \n for (i = 1; i <= id_list[0]; ++i) {\n id_list[i] = (int)final_proportions[eigensystem.length - i][1];\n \n#ifdef INSANE_DEBUG\n printf(\"final_proportions[%d]\\t%.8f\\n\", id_list[i], final_proportions[eigensystem.length - i][0]);\n#endif\n }\n }\n \n return id_list;\n}\n\nvoid print_equilibrium(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters) {\n double soft_right_bound, equilibrium_time;\n int i, list_length;\n int* id_list;\n \n soft_right_bound = soft_bound_for_population_proportion(eigensystem, klp_params, parameters, klp_params.end_state, parameters.end_time, 1);\n id_list = array_of_indices_to_output(eigensystem, klp_params, parameters, soft_right_bound);\n list_length = id_list++[0];\n \n printf(\"index\\tlogtime\\n\");\n \n for (i = 0; i < list_length; ++i) {\n equilibrium_time = estimate_equilibrium(eigensystem, klp_params, parameters, id_list[i]);\n \n printf(\"%d\\t\", id_list[i]);\n \n if (equilibrium_time == NEG_INF(parameters)) {\n printf(\"-Infinity\\n\");\n } else if (equilibrium_time == POS_INF(parameters)) {\n printf(\"Infinity\\n\");\n } else {\n printf(\"%+.8f\\n\", equilibrium_time);\n }\n }\n}\n\nvoid print_population_proportion(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters) {\n double current_time, soft_left_bound, soft_right_bound;\n int i, list_length;\n int* id_list;\n \n soft_left_bound = soft_bound_for_population_proportion(eigensystem, klp_params, parameters, klp_params.start_state, parameters.start_time, -1);\n soft_right_bound = soft_bound_for_population_proportion(eigensystem, klp_params, parameters, klp_params.end_state, parameters.end_time, 1);\n id_list = array_of_indices_to_output(eigensystem, klp_params, parameters, soft_right_bound);\n list_length = id_list++[0];\n \n printf(\"logtime\\t\");\n \n for (i = 0; i < list_length; ++i) {\n printf(\"%d\\t\", id_list[i]);\n }\n \n printf(\"\\n\");\n \n for (current_time = soft_left_bound; current_time <= soft_right_bound; current_time += parameters.step_size) {\n printf(\"%+.8f\\t\", current_time);\n \n for (i = 0; i < list_length - 1; ++i) {\n printf(\"%+.8f\\t\", probability_at_logtime(eigensystem, klp_params, current_time, klp_params.start_state, id_list[i]));\n }\n \n printf(\"%+.8f\", probability_at_logtime(eigensystem, klp_params, current_time, klp_params.start_state, id_list[i]));\n \n printf(\"\\n\");\n }\n}\n\nvoid print_array(char* title, double* matrix, int length) {\n int i;\n printf(\"%s\\n\", title);\n \n for (i = 0; i < length; ++i) {\n printf(\"%+.4f\\n\", matrix[i]);\n }\n \n printf(\"\\n\");\n}\n\n\nvoid print_square_matrix(char* title, double* matrix, int length) {\n int i, j;\n printf(\"%s\\n\", title);\n \n for (i = 0; i < length; ++i) {\n for (j = 0; j < length; ++j) {\n printf(\"%+.2e \", E_ROW_ORDER(matrix, i, j, length));\n }\n \n printf(\"\\n\");\n }\n \n printf(\"\\n\");\n}\n\nvoid print_eigenvalues(const EIGENSYSTEM eigensystem) {\n int i;\n \n for (i = 0; i < eigensystem.length; ++i) {\n printf(\"%+.8f\\n\", eigensystem.values[i]);\n }\n}\n", "meta": {"hexsha": "72847042d30fc77feeab1b0544b4745cb3beecf8", "size": 19973, "ext": "c", "lang": "C", "max_stars_repo_path": "src/population/c/population_functions.c", "max_stars_repo_name": "evansenter/hermes", "max_stars_repo_head_hexsha": "8ad3800f98fcfe7fb2e9f57cdf11b18cf781ac2d", "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/population/c/population_functions.c", "max_issues_repo_name": "evansenter/hermes", "max_issues_repo_head_hexsha": "8ad3800f98fcfe7fb2e9f57cdf11b18cf781ac2d", "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/population/c/population_functions.c", "max_forks_repo_name": "evansenter/hermes", "max_forks_repo_head_hexsha": "8ad3800f98fcfe7fb2e9f57cdf11b18cf781ac2d", "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.4131205674, "max_line_length": 253, "alphanum_fraction": 0.6928353277, "num_tokens": 5194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5801680101879397}} {"text": "/* specfunc/coupling.c\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#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\ninline\nstatic\nint locMax3(const int a, const int b, const int c)\n{\n int d = GSL_MAX(a, b);\n return GSL_MAX(d, c);\n}\n\ninline\nstatic\nint locMin3(const int a, const int b, const int c)\n{\n int d = GSL_MIN(a, b);\n return GSL_MIN(d, c);\n}\n\ninline\nstatic\nint locMin5(const int a, const int b, const int c, const int d, const int e)\n{\n int f = GSL_MIN(a, b);\n int g = GSL_MIN(c, d);\n int h = GSL_MIN(f, g);\n return GSL_MIN(e, h);\n}\n\n\n/* See: [Thompson, Atlas for Computing Mathematical Functions] */\n\nstatic\nint\ndelta(int ta, int tb, int tc, gsl_sf_result * d)\n{\n gsl_sf_result f1, f2, f3, f4;\n int status = 0;\n status += gsl_sf_fact_e((ta + tb - tc)/2, &f1);\n status += gsl_sf_fact_e((ta + tc - tb)/2, &f2);\n status += gsl_sf_fact_e((tb + tc - ta)/2, &f3);\n status += gsl_sf_fact_e((ta + tb + tc)/2 + 1, &f4);\n if(status != 0) {\n OVERFLOW_ERROR(d);\n }\n d->val = f1.val * f2.val * f3.val / f4.val;\n d->err = 4.0 * GSL_DBL_EPSILON * fabs(d->val);\n return GSL_SUCCESS;\n}\n\n\nstatic\nint\ntriangle_selection_fails(int two_ja, int two_jb, int two_jc)\n{\n return ((two_jb < abs(two_ja - two_jc)) || (two_jb > two_ja + two_jc));\n}\n\n\nstatic\nint\nm_selection_fails(int two_ja, int two_jb, int two_jc,\n int two_ma, int two_mb, int two_mc)\n{\n return (\n abs(two_ma) > two_ja \n || abs(two_mb) > two_jb\n || abs(two_mc) > two_jc\n || GSL_IS_ODD(two_ja + two_ma)\n || GSL_IS_ODD(two_jb + two_mb)\n || GSL_IS_ODD(two_jc + two_mc)\n || (two_ma + two_mb + two_mc) != 0\n );\n}\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\n\nint\ngsl_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{\n /* CHECK_POINTER(result) */\n\n if(two_ja < 0 || two_jb < 0 || two_jc < 0) {\n DOMAIN_ERROR(result);\n }\n else if ( triangle_selection_fails(two_ja, two_jb, two_jc)\n || m_selection_fails(two_ja, two_jb, two_jc, two_ma, two_mb, two_mc)\n ) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else {\n int jca = (-two_ja + two_jb + two_jc) / 2,\n jcb = ( two_ja - two_jb + two_jc) / 2,\n jcc = ( two_ja + two_jb - two_jc) / 2,\n jmma = ( two_ja - two_ma) / 2,\n jmmb = ( two_jb - two_mb) / 2,\n jmmc = ( two_jc - two_mc) / 2,\n jpma = ( two_ja + two_ma) / 2,\n jpmb = ( two_jb + two_mb) / 2,\n jpmc = ( two_jc + two_mc) / 2,\n jsum = ( two_ja + two_jb + two_jc) / 2,\n kmin = locMax3 (0, jpmb - jmmc, jmma - jpmc),\n kmax = locMin3 (jcc, jmma, jpmb),\n k, sign = GSL_IS_ODD (kmin - jpma + jmmb) ? -1 : 1,\n status = 0;\n double sum_pos = 0.0, sum_neg = 0.0, norm, term;\n gsl_sf_result bc1, bc2, bc3, bcn1, bcn2, bcd1, bcd2, bcd3, bcd4;\n\n status += gsl_sf_choose_e (two_ja, jcc , &bcn1);\n status += gsl_sf_choose_e (two_jb, jcc , &bcn2);\n status += gsl_sf_choose_e (jsum+1, jcc , &bcd1);\n status += gsl_sf_choose_e (two_ja, jmma, &bcd2);\n status += gsl_sf_choose_e (two_jb, jmmb, &bcd3);\n status += gsl_sf_choose_e (two_jc, jpmc, &bcd4);\n \n if (status != 0) {\n OVERFLOW_ERROR (result);\n }\n \n norm = sqrt (bcn1.val * bcn2.val)\n / sqrt (bcd1.val * bcd2.val * bcd3.val * bcd4.val * ((double) two_jc + 1.0));\n\n for (k = kmin; k <= kmax; k++) {\n status += gsl_sf_choose_e (jcc, k, &bc1);\n status += gsl_sf_choose_e (jcb, jmma - k, &bc2);\n status += gsl_sf_choose_e (jca, jpmb - k, &bc3);\n \n if (status != 0) {\n OVERFLOW_ERROR (result);\n }\n \n term = bc1.val * bc2.val * bc3.val;\n \n if (sign < 0) {\n sum_neg += norm * term;\n } else {\n sum_pos += norm * term;\n }\n \n sign = -sign;\n }\n \n result->val = sum_pos - sum_neg;\n result->err = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);\n result->err += 2.0 * GSL_DBL_EPSILON * (kmax - kmin) * fabs(result->val);\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_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{\n return gsl_sf_coupling_6j_e(two_ja, two_jb, two_je, two_jd, two_jc, two_jf, result);\n}\n\n\nint\ngsl_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{\n /* CHECK_POINTER(result) */\n\n if( two_ja < 0 || two_jb < 0 || two_jc < 0\n || two_jd < 0 || two_je < 0 || two_jf < 0\n ) {\n DOMAIN_ERROR(result);\n }\n else if( triangle_selection_fails(two_ja, two_jb, two_jc)\n || triangle_selection_fails(two_ja, two_je, two_jf)\n || triangle_selection_fails(two_jb, two_jd, two_jf)\n || triangle_selection_fails(two_je, two_jd, two_jc)\n ) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else {\n gsl_sf_result n1;\n gsl_sf_result d1, d2, d3, d4, d5, d6;\n double norm;\n int tk, tkmin, tkmax;\n double phase;\n double sum_pos = 0.0;\n double sum_neg = 0.0;\n double sumsq_err = 0.0;\n int status = 0;\n status += delta(two_ja, two_jb, two_jc, &d1);\n status += delta(two_ja, two_je, two_jf, &d2);\n status += delta(two_jb, two_jd, two_jf, &d3);\n status += delta(two_je, two_jd, two_jc, &d4);\n if(status != GSL_SUCCESS) {\n OVERFLOW_ERROR(result);\n }\n norm = sqrt(d1.val) * sqrt(d2.val) * sqrt(d3.val) * sqrt(d4.val);\n \n tkmin = locMax3(0,\n two_ja + two_jd - two_jc - two_jf,\n two_jb + two_je - two_jc - two_jf);\n\n tkmax = locMin5(two_ja + two_jb + two_je + two_jd + 2,\n two_ja + two_jb - two_jc,\n two_je + two_jd - two_jc,\n two_ja + two_je - two_jf,\n two_jb + two_jd - two_jf);\n\n phase = GSL_IS_ODD((two_ja + two_jb + two_je + two_jd + tkmin)/2)\n ? -1.0\n : 1.0;\n\n for(tk=tkmin; tk<=tkmax; tk += 2) {\n double term;\n double term_err;\n gsl_sf_result den_1, den_2;\n gsl_sf_result d1_a, d1_b;\n status = 0;\n\n status += gsl_sf_fact_e((two_ja + two_jb + two_je + two_jd - tk)/2 + 1, &n1);\n status += gsl_sf_fact_e(tk/2, &d1_a);\n status += gsl_sf_fact_e((two_jc + two_jf - two_ja - two_jd + tk)/2, &d1_b);\n status += gsl_sf_fact_e((two_jc + two_jf - two_jb - two_je + tk)/2, &d2);\n status += gsl_sf_fact_e((two_ja + two_jb - two_jc - tk)/2, &d3);\n status += gsl_sf_fact_e((two_je + two_jd - two_jc - tk)/2, &d4);\n status += gsl_sf_fact_e((two_ja + two_je - two_jf - tk)/2, &d5);\n status += gsl_sf_fact_e((two_jb + two_jd - two_jf - tk)/2, &d6);\n\n if(status != GSL_SUCCESS) {\n OVERFLOW_ERROR(result);\n }\n\n d1.val = d1_a.val * d1_b.val;\n d1.err = d1_a.err * fabs(d1_b.val) + fabs(d1_a.val) * d1_b.err;\n\n den_1.val = d1.val*d2.val*d3.val;\n den_1.err = d1.err * fabs(d2.val*d3.val);\n den_1.err += d2.err * fabs(d1.val*d3.val);\n den_1.err += d3.err * fabs(d1.val*d2.val);\n\n den_2.val = d4.val*d5.val*d6.val;\n den_2.err = d4.err * fabs(d5.val*d6.val);\n den_2.err += d5.err * fabs(d4.val*d6.val);\n den_2.err += d6.err * fabs(d4.val*d5.val);\n\n term = phase * n1.val / den_1.val / den_2.val;\n phase = -phase;\n term_err = n1.err / fabs(den_1.val) / fabs(den_2.val);\n term_err += fabs(term / den_1.val) * den_1.err;\n term_err += fabs(term / den_2.val) * den_2.err;\n\n if(term >= 0.0) {\n sum_pos += norm*term;\n }\n else {\n sum_neg -= norm*term;\n }\n\n sumsq_err += norm*norm * term_err*term_err;\n }\n\n result->val = sum_pos - sum_neg;\n result->err = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);\n result->err += sqrt(sumsq_err / (0.5*(tkmax-tkmin)+1.0));\n result->err += 2.0 * GSL_DBL_EPSILON * (tkmax - tkmin + 2.0) * fabs(result->val);\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_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{\n int status = gsl_sf_coupling_6j_e(two_ja, two_jb, two_je, two_jd, two_jc, two_jf, result);\n int phase_sum = (two_ja + two_jb + two_jc + two_jd)/2;\n result->val *= ( GSL_IS_ODD(phase_sum) ? -1.0 : 1.0 );\n return status;\n}\n\n\nint\ngsl_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{\n /* CHECK_POINTER(result) */\n\n if( two_ja < 0 || two_jb < 0 || two_jc < 0\n || two_jd < 0 || two_je < 0 || two_jf < 0\n || two_jg < 0 || two_jh < 0 || two_ji < 0\n ) {\n DOMAIN_ERROR(result);\n }\n else if( triangle_selection_fails(two_ja, two_jb, two_jc)\n || triangle_selection_fails(two_jd, two_je, two_jf)\n || triangle_selection_fails(two_jg, two_jh, two_ji)\n || triangle_selection_fails(two_ja, two_jd, two_jg)\n || triangle_selection_fails(two_jb, two_je, two_jh)\n || triangle_selection_fails(two_jc, two_jf, two_ji)\n ) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else {\n int tk;\n int tkmin = locMax3(abs(two_ja-two_ji), abs(two_jh-two_jd), abs(two_jb-two_jf));\n int tkmax = locMin3(two_ja + two_ji, two_jh + two_jd, two_jb + two_jf);\n double sum_pos = 0.0;\n double sum_neg = 0.0;\n double sumsq_err = 0.0;\n double phase;\n for(tk=tkmin; tk<=tkmax; tk += 2) {\n gsl_sf_result s1, s2, s3;\n double term;\n double term_err;\n int status = 0;\n\n status += gsl_sf_coupling_6j_e(two_ja, two_ji, tk, two_jh, two_jd, two_jg, &s1);\n status += gsl_sf_coupling_6j_e(two_jb, two_jf, tk, two_jd, two_jh, two_je, &s2);\n status += gsl_sf_coupling_6j_e(two_ja, two_ji, tk, two_jf, two_jb, two_jc, &s3);\n\n if(status != GSL_SUCCESS) {\n OVERFLOW_ERROR(result);\n }\n term = s1.val * s2.val * s3.val;\n term_err = s1.err * fabs(s2.val*s3.val);\n term_err += s2.err * fabs(s1.val*s3.val);\n term_err += s3.err * fabs(s1.val*s2.val);\n\n if(term >= 0.0) {\n sum_pos += (tk + 1) * term;\n }\n else {\n sum_neg -= (tk + 1) * term;\n }\n\n sumsq_err += ((tk+1) * term_err) * ((tk+1) * term_err);\n }\n\n phase = GSL_IS_ODD(tkmin) ? -1.0 : 1.0;\n\n result->val = phase * (sum_pos - sum_neg);\n result->err = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);\n result->err += sqrt(sumsq_err / (0.5*(tkmax-tkmin)+1.0));\n result->err += 2.0 * GSL_DBL_EPSILON * (tkmax-tkmin + 2.0) * fabs(result->val);\n\n return GSL_SUCCESS;\n }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\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 EVAL_RESULT(gsl_sf_coupling_3j_e(two_ja, two_jb, two_jc,\n two_ma, two_mb, two_mc,\n &result));\n}\n\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 EVAL_RESULT(gsl_sf_coupling_6j_INCORRECT_e(two_ja, two_jb, two_jc,\n two_jd, two_je, two_jf,\n &result));\n}\n\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 EVAL_RESULT(gsl_sf_coupling_6j_e(two_ja, two_jb, two_jc,\n two_jd, two_je, two_jf,\n &result));\n}\n\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 EVAL_RESULT(gsl_sf_coupling_RacahW_e(two_ja, two_jb, two_jc,\n two_jd, two_je, two_jf,\n &result));\n}\n\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 EVAL_RESULT(gsl_sf_coupling_9j_e(two_ja, two_jb, two_jc,\n two_jd, two_je, two_jf,\n two_jg, two_jh, two_ji,\n &result));\n}\n", "meta": {"hexsha": "9a7140b613a3fdcf4d8015c64a6bad4aca0410ad", "size": 13606, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/specfunc/coupling.c", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/specfunc/coupling.c", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/specfunc/coupling.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 30.9227272727, "max_line_length": 92, "alphanum_fraction": 0.5676907247, "num_tokens": 4646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.580168005300146}} {"text": "#include \n\nint\nmain (void)\n{\n double a_data[] = { 0.18, 0.60, 0.57, 0.96,\n 0.41, 0.24, 0.99, 0.58,\n 0.14, 0.30, 0.97, 0.66,\n 0.51, 0.13, 0.19, 0.85 } ;\n\n double b_data[] = { 1.0, 2.0, 3.0, 4.0 };\n\n gsl_matrix_view m \n = gsl_matrix_view_array(a_data, 4, 4);\n\n gsl_vector_view b\n = gsl_vector_view_array(b_data, 4);\n\n gsl_vector *x = gsl_vector_alloc (4);\n \n int s;\n\n gsl_permutation * p = gsl_permutation_alloc (4);\n\n gsl_linalg_LU_decomp (&m.matrix, p, &s);\n\n gsl_linalg_LU_solve (&m.matrix, p, &b.vector, x);\n\n gsl_vector_fprintf(stdout, x, \"%g\");\n\n gsl_permutation_free (p);\n}\n", "meta": {"hexsha": "c49ab2ef6ae45fd7fd100ad9f7f7b01e5d9770be", "size": 678, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/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/linalg/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/linalg/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.5454545455, "max_line_length": 51, "alphanum_fraction": 0.5634218289, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.579995380089009}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n\nvoid mcmc_con_run()\n{\n char fname_mcmc[100];\n strcpy(fname_mcmc, \"data/mcmc_con.txt\");\n\n printf(\"*******con mcmc\\n\");\n mcmc_con_init();\n if(flag_mcmc==1)\n {\n mcmc_sampling(fname_mcmc, &probability_con);\n mcmc_stats(fname_mcmc);\n }\n else\n {\n nc = nc_lim_low;\n printf(\"reading par.txt\\n\");\n read_input();\n }\n \n reconstruct_con();\n\n memcpy(theta_best_con, theta_best, ntheta*sizeof(double));\n memcpy(theta_best_var_con, theta_best_var, ntheta*2*sizeof(double));\n}\n\nvoid mcmc_con_init()\n{\n int i;\n\n ntheta = 2;\n\n i=0;\n theta_range[i][0] = log(1.0e-6);\n theta_range[i++][1] = log(10.0);\n theta_range[i][0] = log(1.0e-2);\n theta_range[i++][1] = log(1.0e5);\n\n i = 0;\n theta_input[i++] = log(0.1);\n theta_input[i++] = log(100.0);\n\n i = 0;\n sigma_input[i++] = 0.1;\n sigma_input[i++] = 0.5;\n\n i = 0;\n theta_fixed[i++] = 0;\n theta_fixed[i++] = 0;\n\n}\n/*\n * probability for continuum mcmc.\n */\ndouble probability_con(double *theta)//double sigmahat, double taud, double alpha)\n{\n double sigmahat, taud, alpha;\n double prob, prior, lndet, lndet_ICq, sigma;\n double *ybuf, *Larr, *Cq, *ICq, *ave, *yave, *ysub;\n int i, nq, info;\n \n nq = (flag_detrend + 1);\n ybuf = workspace;\n Larr = workspace+ncon_data;\n Cq = Larr + nq*ncon_data;\n ICq = Cq + nq*nq;\n ave = ICq + nq*nq;\n yave = ave + nq;\n ysub = yave + ncon_data;\n \n alpha = 1.0;\n sigmahat = exp(theta[0]);\n taud = exp(theta[1]);\n\n sigma = sigmahat * sqrt(taud / 2.0);\n\n set_covar_mat_con(sigma, taud, alpha);\n \n for(i=0;i log(cad_con) )\n {\n prior = ( log(cad_con) - theta[1]);\n }\n else\n {\n prior += - (log(cad_con) - theta[1]);\n }\n return prob + prior; \n}\n\n/* calculate covariance matrix */\nvoid set_covar_mat_con(double sigma, double tau, double alpha)\n{\n double t1, t2, nerr;\n int i, j;\n \n for(i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ESMCI{\n namespace MapperUtil{\n\n /* A Matrix class\n * The matrix class is used to create an n-dimensional matrix of values\n */\n template\n class Matrix{\n public:\n Matrix(const std::vector &dims, const std::vector &data);\n Matrix(std::initializer_list dims, std::initializer_list data);\n Matrix(const std::vector &dims, const T &val);\n \n /* Get the matrix dimensions */\n std::vector get_dims(void ) const;\n /* Get a reference to the data strored in the matrix */\n const T *get_data_by_ref(void ) const;\n T *get_data_by_ref(void );\n /* Get the data stored in the matrix */\n std::vector get_data(void ) const;\n\n /* Get the transpose of the matrix */\n Matrix transpose(void ) const;\n /* Get the inverse of the matrix */\n Matrix inv(void ) const;\n /* Get the pseudo inverse of the matrix */\n Matrix pinv(void ) const;\n\n /* Returns true if the matrix, m, is equal to this matrix,\n * false otherwise. This function uses a tolerance, tol, to\n * compare the values stored in the matrix (unlike == that\n * does not provide a tolerance)\n */\n bool equals(const Matrix &m, double tol) const;\n\n /* Compare if two matrices are equal */\n template\n friend bool operator==(const Matrix &lhs, const Matrix &rhs);\n /* Compare if all values in the matrix is equal to val */\n template\n friend bool operator==(const Matrix &m, const U &val);\n template\n friend bool operator==(const U &val, const Matrix &m);\n /* Operator to add/subtract/multiply two matrices */\n template\n friend Matrix operator+(const Matrix &lhs, const Matrix &rhs);\n template\n friend Matrix operator-(const Matrix &lhs, const Matrix &rhs);\n template\n friend Matrix operator*(const Matrix &lhs, const Matrix &rhs);\n /* Operator to scale a matrix by a scalar */\n template\n friend Matrix operator*(const Matrix &lhs, const V &rhs);\n template\n friend Matrix operator*(const U &lhs, const Matrix &rhs);\n template\n friend std::ostream& operator<<(std::ostream &ostr, const Matrix &m);\n private:\n std::vector dims_;\n std::vector data_;\n };\n\n template\n Matrix::Matrix(const std::vector &dims, const std::vector &data):dims_(dims),data_(data)\n {}\n\n\n template\n Matrix::Matrix(std::initializer_list dims, std::initializer_list data):dims_(dims.begin(),dims.end()),data_(data.begin(),data.end())\n {}\n\n template\n Matrix::Matrix(const std::vector &dims, const T& val):dims_(dims)\n {\n assert(dims.size() > 0);\n int data_sz = std::accumulate(dims.begin(), dims.end(), 1, std::multiplies());\n assert(data_sz > 0);\n data_.resize(data_sz, val);\n }\n\n template\n std::vector Matrix::get_dims(void ) const\n {\n return dims_;\n }\n\n template\n const T *Matrix::get_data_by_ref(void ) const\n {\n return ((data_.size() > 0 ) ? (&(data_[0])) : NULL);\n }\n\n template\n T *Matrix::get_data_by_ref(void )\n {\n return ((data_.size() > 0 ) ? (&(data_[0])) : NULL);\n }\n\n template\n std::vector Matrix::get_data(void ) const\n {\n return data_;\n }\n\n template\n Matrix Matrix::transpose(void ) const\n {\n assert(dims_.size() <= 2);\n int nelems = static_cast(data_.size());\n if(dims_.size() == 1){\n return Matrix(dims_, data_);\n }\n else{\n std::vector dims(dims_.rbegin(), dims_.rend());\n if((dims_[0] == 1) || dims_[1] == 1){\n return Matrix(dims, data_);\n }\n else{\n // FIXME: Use inplace transpose\n std::vector data(data_.size(), static_cast(0));\n int nrows = dims_[0];\n int ncols = dims_[1];\n int tnrows = ncols;\n int tncols = nrows;\n for(int idx = 0; idx < nelems; idx++){\n int ridx = idx/ncols;\n int cidx = idx - ridx * ncols;\n int tridx = cidx;\n int tcidx = ridx;\n int tidx = tridx * tncols + tcidx;\n data[tidx] = data_[idx];\n }\n return Matrix(dims, data); \n }\n }\n }\n\n /* Calculate the inverse of the matrix using LAPACK */\n inline int LAPACK_Minv(int m, float *A)\n {\n lapack_int n = static_cast(m);\n lapack_int *ipiv = (lapack_int *)calloc(n+1, sizeof(lapack_int));\n lapack_int info;\n /* Calculate LU decomposition of the matrix */\n info = LAPACKE_sgetrf(LAPACK_ROW_MAJOR, n, n, A, n, ipiv);\n /* info == 0 => success */\n if(info < 0){\n std::cout << \"LAPACKE_sgetrf failed, the \"\n << -info << \"th arg in input array, A[\" << -info << \"] = \"\n << A[-info] << \" is invalid\\n\";\n return ESMF_FAILURE;\n }\n else if(info > 0){\n std::cout << \"LAPACKE_sgetrf failed, the U[\"\n << info << \",\" << info << \"] = 0, U is singular and div by zero can occur\"\n << \" if used to solve a system of equations\\n\";\n return ESMF_FAILURE;\n }\n /* Calculate the inverse of the matrix */\n info = LAPACKE_sgetri(LAPACK_ROW_MAJOR, n, A, n, ipiv);\n /* info == 0 => success */\n if(info < 0){\n std::cout << \"LAPACKE_sgetri failed, the \"\n << -info << \"th arg in input array, A[\" << -info << \"] = \"\n << A[-info] << \" is invalid\\n\";\n return ESMF_FAILURE;\n }\n else if(info > 0){\n std::cout << \"LAPACKE_sgetri failed, the U[\"\n << info << \",\" << info << \"] = 0, the matrix is singular and its inverse \"\n << \"cannot be computed\\n\";\n return ESMF_FAILURE;\n }\n free(ipiv);\n\n return ESMF_SUCCESS;\n }\n\n /* Calculate the inverse of the matrix using LAPACK */\n inline int LAPACK_Minv(int m, double *A)\n {\n lapack_int n = static_cast(m);\n lapack_int *ipiv = (lapack_int *)calloc(n+1, sizeof(lapack_int));\n lapack_int info;\n /* Calculate LU decomposition of the matrix */\n info = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, A, n, ipiv);\n /* info == 0 => success */\n if(info < 0){\n std::cout << \"LAPACKE_dgetrf failed, the \"\n << -info << \"th arg in input array, A[\" << -info << \"] = \"\n << A[-info] << \" is invalid\\n\";\n return ESMF_FAILURE;\n }\n else if(info > 0){\n std::cout << \"LAPACKE_dgetrf failed, the U[\"\n << info << \",\" << info << \"] = 0, U is singular and div by zero can occur\"\n << \" if used to solve a system of equations\\n\";\n return ESMF_FAILURE;\n }\n /* Calculate the inverse of the matrix */\n info = LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, A, n, ipiv);\n /* info == 0 => success */\n if(info < 0){\n std::cout << \"LAPACKE_dgetri failed, the \"\n << -info << \"th arg in input array, A[\" << -info << \"] = \"\n << A[-info] << \" is invalid\\n\";\n return ESMF_FAILURE;\n }\n else if(info > 0){\n std::cout << \"LAPACKE_dgetri failed, the U[\"\n << info << \",\" << info << \"] = 0, the matrix is singular and its inverse \"\n << \"cannot be computed\\n\";\n return ESMF_FAILURE;\n }\n free(ipiv);\n\n return ESMF_SUCCESS;\n }\n\n /* Calculate the inverse of the matrix */\n template\n Matrix Matrix::inv(void ) const\n {\n Matrix res = *this;\n if(dims_.size() == 1){\n return res;\n }\n\n // We are only concerned about 2d matrices for now\n assert(dims_.size() == 2);\n assert(std::adjacent_find(dims_.cbegin(), dims_.cend(), std::not_equal_to()) == dims_.cend());\n\n int ret = LAPACK_Minv(res.dims_[0], res.get_data_by_ref());\n //assert(ret == ESMF_SUCCESS);\n if(ret != ESMF_SUCCESS){\n std::cerr << \"Finding matrix inv failed for : \\n\" << *this << \"\\n\";\n std::string err_msg(\"LAPACK routine to find inv failed\");\n throw std::runtime_error(err_msg);\n }\n\n return res;\n }\n\n /* Compute pseudo inverse = Inverse(A_transpose * A) * A_transpose */\n template\n Matrix Matrix::pinv(void ) const\n {\n Matrix trans = transpose();\n try{\n // Left inverse\n return ((trans * (*this)).inv() * trans);\n }\n catch(...){\n // Right inverse\n return (trans * ((*this) * trans).inv());\n }\n }\n\n template\n bool Matrix::equals(const Matrix &m, double tol) const\n {\n std::vector m_dims = m.get_dims();\n std::vector m_data = m.get_data();\n\n if(m_dims != dims_){\n return false;\n }\n\n if(m_data.size() != data_.size()){\n return false;\n }\n\n for(typename std::vector::const_iterator citer1 = m_data.cbegin(),\n citer2 = data_.cbegin();\n (citer1 != m_data.cend()) && (citer2 != data_.cend());\n ++citer1, ++citer2){\n if(fabs(*citer1 - *citer2) > tol){\n return false;\n }\n }\n\n return true;\n }\n\n template\n bool operator==(const Matrix &lhs, const Matrix &rhs)\n {\n if(lhs.dims_ != rhs.dims_){\n return false; \n }\n if(lhs.data_ != rhs.data_){\n return false;\n }\n return true;\n }\n\n template\n bool operator==(const Matrix &m, const T& val)\n {\n for(typename std::vector::const_iterator citer = m.data_.cbegin();\n citer != m.data_.cend(); ++citer){\n if(*citer != val){\n return false;\n }\n }\n return true;\n }\n\n template\n bool operator==(const T &val, const Matrix &m)\n {\n return (m == val);\n }\n\n template\n Matrix operator+(const Matrix &lhs, const Matrix &rhs)\n {\n assert(lhs.dims_.size() == rhs.dims_.size());\n assert(std::equal(lhs.dims_.begin(), lhs.dims_.end(), rhs.dims_.begin()));\n Matrix res = lhs;\n std::transform(res.data_.begin(), res.data_.end(), rhs.data_.begin(),\n res.data_.begin(), std::plus());\n return res;\n }\n\n template\n Matrix operator+(const Matrix &lhs, const V &rhs)\n {\n Matrix res = lhs;\n std::transform(res.data_.begin(), res.data_.end(),\n res.data_.begin(),\n std::bind1st(std::plus(), static_cast(rhs)));\n return res;\n }\n\n template\n Matrix operator+(const U &lhs, const Matrix &rhs)\n {\n return rhs + lhs;\n }\n\n template\n Matrix operator-(const Matrix &lhs, const Matrix &rhs)\n {\n assert(lhs.dims_.size() == rhs.dims_.size());\n assert(std::equal(lhs.dims_.begin(), lhs.dims_.end(), rhs.dims_.begin()));\n Matrix res = lhs;\n std::transform(res.data_.begin(), res.data_.end(), rhs.data_.begin(),\n res.data_.begin(), std::minus());\n return res;\n }\n\n template\n Matrix operator-(const Matrix &lhs, const V &rhs)\n {\n Matrix res = lhs;\n std::transform(res.data_.begin(), res.data_.end(),\n res.data_.begin(),\n std::bind1st(std::minus(), static_cast(rhs)));\n return res;\n }\n\n /* Multiply two matrices using BLAS\n */\n inline int BLAS_Mmult(int m, int n, int k, int alpha,\n const float *A, int lda, const float *B, int ldb,\n int beta, float *C, int ldc)\n {\n /* cblas_sgemm has no return code ! */\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);\n return ESMF_SUCCESS;\n }\n\n /* Multiply two matrices using BLAS\n */\n inline int BLAS_Mmult(int m, int n, int k, int alpha,\n const double *A, int lda, const double *B, int ldb,\n int beta, double *C, int ldc)\n {\n /* cblas_sgemm has no return code ! */\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);\n return ESMF_SUCCESS;\n }\n\n /* Multiply two matrices, currently uses BLAS routines for matrix\n * multiplication\n */\n template\n Matrix operator*(const Matrix &lhs, const Matrix &rhs)\n {\n assert((lhs.dims_.size() > 0) && (rhs.dims_.size() > 0));\n // No tensor products for now\n assert((lhs.dims_.size() <= 2) && (rhs.dims_.size() <= 2));\n assert(lhs.dims_[lhs.dims_.size()-1] == rhs.dims_[0]);\n /* Determine inputs to the BLAS routine to perform\n * matrix multiplication\n */\n int m, n, k, alpha, lda, ldb, beta, ldc;\n alpha = 1;\n beta = 1;\n\n std::vector res_dims;\n if(lhs.dims_.size() == 1){\n res_dims.push_back(lhs.dims_[0]);\n m = 1;\n k = 1;\n n = 1;\n lda = 1;\n ldb = 1;\n ldc = 1;\n }\n else{\n assert(lhs.dims_.size() == 2);\n res_dims.push_back(lhs.dims_[0]);\n res_dims.push_back(rhs.dims_[rhs.dims_.size()-1]);\n m = lhs.dims_[0];\n k = lhs.dims_[lhs.dims_.size() - 1];\n n = rhs.dims_[rhs.dims_.size() - 1];\n lda = k;\n ldb = n;\n ldc = n;\n }\n\n Matrix res(res_dims, 0);\n const T *A = lhs.get_data_by_ref();\n const T *B = rhs.get_data_by_ref();\n T *C = res.get_data_by_ref();\n\n /* Use BLAS for multiplying the two matrices */\n int ret = BLAS_Mmult(m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);\n assert(ret == ESMF_SUCCESS);\n\n return res;\n }\n\n template\n Matrix operator*(const Matrix &lhs, const V &rhs)\n {\n Matrix res = lhs;\n std::transform(res.data_.begin(), res.data_.end(),\n res.data_.begin(),\n std::bind1st(std::multiplies(), static_cast(rhs)));\n return res;\n }\n template\n Matrix operator*(const U &lhs, const Matrix &rhs)\n {\n return rhs * lhs;\n }\n\n template\n std::ostream& operator<<(std::ostream &ostr, const Matrix &m)\n {\n std::vector dim_wgts(m.dims_);\n //std::vector dim_wgts(m.dims_.size(), 0);\n //std::partial_sum(m.dims_.rbegin(), m.dims_.rend(), dim_wgts.rbegin(), std::multiplies());\n std::vector dim_wgts_counter(dim_wgts.size(), 0);\n assert(dim_wgts.size() > 0);\n std::size_t dim_wgts_counter_idx = dim_wgts.size() - 1;\n for(typename std::vector::const_iterator citer = m.data_.cbegin();\n citer != m.data_.cend(); ++citer){\n ostr << *citer << \", \";\n dim_wgts_counter[dim_wgts_counter_idx]++;\n if(dim_wgts_counter[dim_wgts_counter_idx] >= \n dim_wgts[dim_wgts_counter_idx]){\n while(dim_wgts_counter[dim_wgts_counter_idx]>=dim_wgts[dim_wgts_counter_idx]){\n dim_wgts_counter[dim_wgts_counter_idx] = 0;\n ostr << \"\\n\";\n if(dim_wgts_counter_idx > 0){\n dim_wgts_counter[dim_wgts_counter_idx - 1]++;\n dim_wgts_counter_idx--;\n }\n else{\n break;\n }\n }\n\n dim_wgts_counter_idx = dim_wgts.size() - 1;\n }\n }\n return ostr;\n }\n\n } // namespace MapperUtil\n} // namespace ESMCI\n\n#endif //ESMCI_Mat_H\n", "meta": {"hexsha": "f1a67170b579d4f6acee8e4ff417ebcd9972ac04", "size": 16318, "ext": "h", "lang": "C", "max_stars_repo_path": "ESMF/src/Superstructure/Mapper/include/ESMCI_Mat.h", "max_stars_repo_name": "joeylamcy/gchp", "max_stars_repo_head_hexsha": "0e1676300fc91000ecb43539cabf1f342d718fb3", "max_stars_repo_licenses": ["NCSA", "Apache-2.0", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-05T16:48:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-05T16:48:58.000Z", "max_issues_repo_path": "ESMF/src/Superstructure/Mapper/include/ESMCI_Mat.h", "max_issues_repo_name": "joeylamcy/gchp", "max_issues_repo_head_hexsha": "0e1676300fc91000ecb43539cabf1f342d718fb3", "max_issues_repo_licenses": ["NCSA", "Apache-2.0", "MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-04T16:12:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T16:12:02.000Z", "max_forks_repo_path": "ESMF/src/Superstructure/Mapper/include/ESMCI_Mat.h", "max_forks_repo_name": "joeylamcy/gchp", "max_forks_repo_head_hexsha": "0e1676300fc91000ecb43539cabf1f342d718fb3", "max_forks_repo_licenses": ["NCSA", "Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3128712871, "max_line_length": 147, "alphanum_fraction": 0.549515872, "num_tokens": 4395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.57967594563946}} {"text": "// CONSTANTIN MIHAI - 336CA\n// TEMA 2 ASC\n\n#include \n\n#include \"utils.h\"\n\ndouble* copy(int N, double *A) {\n\n\tint i, j;\n\n\tdouble *B = malloc(N * N * sizeof(double));\n\tfor (i = 0; i < N; i++) {\n\t\tfor (j = 0; j < N; j++) {\n\t\t\tB[i * N + j] = A[i * N + j];\n\t\t}\n\t}\n\n\treturn B;\n}\n\ndouble* add_matrix(int N, double *A, double *B) {\n\n\tint i, j;\n\n\tdouble *C = calloc(N * N, sizeof(double));\n\tfor (i = 0; i < N; i++) {\n\t\tfor (j = 0; j < N; j++) {\n\t\t\tC[i * N + j] = A[i * N + j] + B[i * N + j];\n\t\t}\n\t}\n\treturn C;\n}\n\ndouble* my_solver(int N, double *A, double *B) {\n\n\t/*\n\t\tA - matrice superior triunghiulara\n\t\tB - matrice normala\n\t\tVrem C = B * A^t + A^2 * B\n\t*/\n\n\t/*\n\t\tCblasRowMajor - matrice stocata pe o singura linie\n\t\tCblasRight - facem B * A^t\n\t\tCblasUpper - matrice superior triunghiulara\n\t\tCblasTrans - folosim A^t\n\t\tCblasNoTrans - folosim A, nu A^t\n\t\tCblasNonUnit - A nu e matrice unitara\n\t*/\n\n\t// B2 <- B2 * A^t\n\tdouble *B2 = copy(N, B);\n\tcblas_dtrmm(CblasRowMajor, CblasRight, CblasUpper, CblasTrans, CblasNonUnit, N, N, 1.0, A, N, B2, N);\n\n\t// A2 <- A2 * A\n\tdouble *A2 = copy(N, A);\n\tcblas_dtrmm(CblasRowMajor, CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, N, N, 1.0, A, N, A2, N);\n\n\t// B <- A2 * B\n\tcblas_dtrmm(CblasRowMajor, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, N, N, 1.0, A2, N, B, N);\n\n\t// result <- B2 + B\n\tdouble *result = add_matrix(N, B2, B);\n\n\treturn result;\n}\n\n", "meta": {"hexsha": "00c8daf93b6a528bf354c696263d248a1b8727aa", "size": 1399, "ext": "c", "lang": "C", "max_stars_repo_path": "ASC/Teme/tema2/solver_blas.c", "max_stars_repo_name": "mihai-constantin/ACS", "max_stars_repo_head_hexsha": "098c99d82dad8fb5d0e909da930c72f1185a99e2", "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": "ASC/Teme/tema2/solver_blas.c", "max_issues_repo_name": "mihai-constantin/ACS", "max_issues_repo_head_hexsha": "098c99d82dad8fb5d0e909da930c72f1185a99e2", "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": "ASC/Teme/tema2/solver_blas.c", "max_forks_repo_name": "mihai-constantin/ACS", "max_forks_repo_head_hexsha": "098c99d82dad8fb5d0e909da930c72f1185a99e2", "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": 20.2753623188, "max_line_length": 104, "alphanum_fraction": 0.583273767, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5792195555144158}} {"text": "/* SO3blas.c */\n\n// SO(3) Lie group implemented with GNU GSL\n// cf. wikipedia, \"Rotation_group_SO(3)#Infinitesimal_rotations\"\n\n// EY note : 20160519 Bizarrely, matrix multiplication isn't implemented\n// in a straightforward manner with the gsl_matrix class;\n// see blas (which I don't know what it is yet) and dgemm for the libraries\n\n/*\n Compiling advice:\n gcc matrixio.c -lgsl -lgslcblas\n\n */\n\n\n#include \n#include \n#include \n\n// Function prototype\n/* int commute(gsl_matrix_view, gsl_matrix_view); */\n\nvoid commute1(void);\n\n\n// global variables\n\ndouble l_x[] = { 0, 0, 0,\n\t\t 0, 0, -1,\n\t\t 0, 1, 0};\n\ndouble l_y[] = { 0, 0, 1,\n\t\t 0, 0, 0,\n\t\t -1, 0, 0};\n\ndouble l_z[] = { 0, -1, 0,\n\t\t 1, 0, 0,\n\t\t 0, 0, 0};\n// cannot put gsl_matrix view commands in global; I need to check why:\n// error: initializer element is not constant\n\n\nint main(void)\n{\n gsl_matrix_view L_x = gsl_matrix_view_array(l_x,3,3);\n gsl_matrix_view L_y = gsl_matrix_view_array(l_y,3,3);\n gsl_matrix_view L_z = gsl_matrix_view_array(l_z,3,3);\n\n \n printf(\"[ %g, %g, %g]\\n\", l_x[0], l_x[1], l_x[2] );\n printf(\"[ %g, %g, %g]\\n\", l_x[3], l_x[4], l_x[5] );\n printf(\"[ %g, %g, %g]\\n\\n\", l_x[6], l_x[7], l_x[8] );\n\n printf(\"[ %g, %g, %g]\\n\", l_y[0], l_y[1], l_y[2] );\n printf(\"[ %g, %g, %g]\\n\", l_y[3], l_y[4], l_y[5] );\n printf(\"[ %g, %g, %g]\\n\\n\", l_y[6], l_y[7], l_y[8] );\n\n printf(\"[ %g, %g, %g]\\n\", l_z[0], l_z[1], l_z[2] );\n printf(\"[ %g, %g, %g]\\n\", l_z[3], l_z[4], l_z[5] );\n printf(\"[ %g, %g, %g]\\n\\n\", l_z[6], l_z[7], l_z[8] );\n\n\n double xy[] = { 0.00, 0.00, 0.00, \n\t\t 0.00, 0.00, 0.00,\n\t\t 0.00, 0.00, 0.00 };\n \n gsl_matrix_view XY = gsl_matrix_view_array(xy,3,3);\n\n gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,\n\t\t &L_x.matrix,&L_z.matrix,\n\t\t 0.0, &XY.matrix);\n\n printf(\"[ %g, %g, %g ]\\n\", xy[0], xy[1], xy[2]);\n printf(\"[ %g, %g, %g ]\\n\", xy[3], xy[4], xy[5]);\n printf(\"[ %g, %g, %g ]\\n\\n\", xy[6], xy[7], xy[8]);\n\n commute1();\n \n return 0;\n}\n\n\nvoid commute1(void) {\n\n gsl_matrix_view L_x = gsl_matrix_view_array(l_x,3,3);\n gsl_matrix_view L_y = gsl_matrix_view_array(l_y,3,3);\n gsl_matrix_view L_z = gsl_matrix_view_array(l_z,3,3);\n\n\n double xy[] = { 0.00, 0.00, 0.00, \n\t\t 0.00, 0.00, 0.00,\n\t\t 0.00, 0.00, 0.00 };\n \n gsl_matrix_view XY = gsl_matrix_view_array(xy,3,3);\n\n double yx[] = { 0.00, 0.00, 0.00, \n\t\t 0.00, 0.00, 0.00,\n\t\t 0.00, 0.00, 0.00 };\n \n gsl_matrix_view YX = gsl_matrix_view_array(yx,3,3);\n\n\n\n \n gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,\n\t\t &L_x.matrix,&L_y.matrix,\n\t\t 0.0, &XY.matrix);\n\n gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,\n\t\t &L_y.matrix,&L_x.matrix,\n\t\t 0.0, &YX.matrix);\n\n printf(\"[ %g, %g, %g ]\\n\", yx[0], yx[1], yx[2]);\n printf(\"[ %g, %g, %g ]\\n\", yx[3], yx[4], yx[5]);\n printf(\"[ %g, %g, %g ]\\n\", yx[6], yx[7], yx[8]);\n \n \n}\n\n\n/*\n\nint commute(gsl_matrix_view X, gsl_matrix_view Y)\n{\n double xy[] = { 0.00, 0.00, 0.00, \n\t\t 0.00, 0.00, 0.00,\n\t\t 0.00, 0.00, 0.00 };\n\n double yx[] = { 0.00, 0.00, 0.00, \n\t\t 0.00, 0.00, 0.00,\n\t\t 0.00, 0.00, 0.00 };\n\n double bracket[] = { 0.00, 0.00, 0.00, \n\t\t 0.00, 0.00, 0.00,\n\t\t 0.00, 0.00, 0.00 };\n \n gsl_matrix_view XY = gsl_matrix_view_array(xy,3,3);\n gsl_matrix_view YX = gsl_matrix_view_array(yx,3,3);\n gsl_matrix_view Bracket = gsl_matrix_view_array(bracket,3,3); \n\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,1.0,\n\t\t &X.matrix,&Y.matrix,\n\t\t 0.0, &XY.matrix);\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,1.0,\n\t\t &X.matrix,&Y.matrix,\n\t\t 0.0, &XY.matrix);\n gls_blas_dgemm(CblasNoTrans, CblasNoTrans,1.0,\n\t\t &XY.matrix, &YX.matrix,\n\t\t 0.0, &Bracket.matrix);\n \n return 1;\n}\n\n*/\n", "meta": {"hexsha": "3ef1406edfc6f216f12e9ca51c339cae6fe53e3b", "size": 3668, "ext": "c", "lang": "C", "max_stars_repo_path": "gslExamples/SO3blas.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/SO3blas.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/SO3blas.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": 23.5128205128, "max_line_length": 75, "alphanum_fraction": 0.5796074155, "num_tokens": 1583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5792092723370935}} {"text": "/* specfunc/trig.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\n/* sinh(x) series\n * double-precision for |x| < 1.0\n */\ninline\nstatic\nint\nsinh_series(const double x, double * result)\n{\n const double y = x*x;\n const double c0 = 1.0/6.0;\n const double c1 = 1.0/120.0;\n const double c2 = 1.0/5040.0;\n const double c3 = 1.0/362880.0;\n const double c4 = 1.0/39916800.0;\n const double c5 = 1.0/6227020800.0;\n const double c6 = 1.0/1307674368000.0;\n const double c7 = 1.0/355687428096000.0;\n *result = x*(1.0 + y*(c0+y*(c1+y*(c2+y*(c3+y*(c4+y*(c5+y*(c6+y*c7))))))));\n return GSL_SUCCESS;\n}\n\n\n/* cosh(x)-1 series\n * double-precision for |x| < 1.0\n */\ninline\nstatic\nint\ncosh_m1_series(const double x, double * result)\n{\n const double y = x*x;\n const double c0 = 0.5;\n const double c1 = 1.0/24.0;\n const double c2 = 1.0/720.0;\n const double c3 = 1.0/40320.0;\n const double c4 = 1.0/3628800.0;\n const double c5 = 1.0/479001600.0;\n const double c6 = 1.0/87178291200.0;\n const double c7 = 1.0/20922789888000.0;\n const double c8 = 1.0/6402373705728000.0;\n *result = y*(c0+y*(c1+y*(c2+y*(c3+y*(c4+y*(c5+y*(c6+y*(c7+y*c8))))))));\n return GSL_SUCCESS;\n}\n\n\n/* Chebyshev expansion for f(t) = sinc((t+1)/2), -1 < t < 1\n */\nstatic double sinc_data[17] = {\n 1.133648177811747875422,\n -0.532677564732557348781,\n -0.068293048346633177859,\n 0.033403684226353715020,\n 0.001485679893925747818,\n -0.000734421305768455295,\n -0.000016837282388837229,\n 0.000008359950146618018,\n 0.000000117382095601192,\n -0.000000058413665922724,\n -0.000000000554763755743,\n 0.000000000276434190426,\n 0.000000000001895374892,\n -0.000000000000945237101,\n -0.000000000000004900690,\n 0.000000000000002445383,\n 0.000000000000000009925\n};\nstatic cheb_series sinc_cs = {\n sinc_data,\n 16,\n -1, 1,\n 10\n};\n\n\n/* Chebyshev expansion for f(t) = g((t+1)Pi/8), -1val = x * (1.0 - x2/6.0);\n result->err = fabs(x*x2*x2 / 100.0);\n return GSL_SUCCESS;\n }\n else {\n double sgn_result = sgn_x;\n double y = floor(abs_x/(0.25*M_PI));\n int octant = y - ldexp(floor(ldexp(y,-3)),3);\n int stat_cs;\n double z;\n\n if(GSL_IS_ODD(octant)) {\n octant += 1;\n octant &= 07;\n y += 1.0;\n }\n\n if(octant > 3) {\n octant -= 4;\n sgn_result = -sgn_result;\n }\n \n z = ((abs_x - y * P1) - y * P2) - y * P3;\n\n if(octant == 0) {\n gsl_sf_result sin_cs_result;\n const double t = 8.0*fabs(z)/M_PI - 1.0;\n stat_cs = cheb_eval_e(&sin_cs, t, &sin_cs_result);\n result->val = z * (1.0 + z*z * sin_cs_result.val);\n }\n else { /* octant == 2 */\n gsl_sf_result cos_cs_result;\n const double t = 8.0*fabs(z)/M_PI - 1.0;\n stat_cs = cheb_eval_e(&cos_cs, t, &cos_cs_result);\n result->val = 1.0 - 0.5*z*z * (1.0 - z*z * cos_cs_result.val);\n }\n\n result->val *= sgn_result;\n\n if(abs_x > 1.0/GSL_DBL_EPSILON) {\n result->err = fabs(result->val);\n }\n else if(abs_x > 100.0/GSL_SQRT_DBL_EPSILON) {\n result->err = 2.0 * abs_x * GSL_DBL_EPSILON * fabs(result->val);\n }\n else if(abs_x > 0.1/GSL_SQRT_DBL_EPSILON) {\n result->err = 2.0 * GSL_SQRT_DBL_EPSILON * fabs(result->val);\n }\n else {\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n }\n\n return stat_cs;\n }\n }\n}\n\n\nint\ngsl_sf_cos_e(double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n {\n const double P1 = 7.85398125648498535156e-1;\n const double P2 = 3.77489470793079817668e-8;\n const double P3 = 2.69515142907905952645e-15;\n\n const double abs_x = fabs(x);\n\n if(abs_x < GSL_ROOT4_DBL_EPSILON) {\n const double x2 = x*x;\n result->val = 1.0 - 0.5*x2;\n result->err = fabs(x2*x2/12.0);\n return GSL_SUCCESS;\n }\n else {\n double sgn_result = 1.0;\n double y = floor(abs_x/(0.25*M_PI));\n int octant = y - ldexp(floor(ldexp(y,-3)),3);\n int stat_cs;\n double z;\n\n if(GSL_IS_ODD(octant)) {\n octant += 1;\n octant &= 07;\n y += 1.0;\n }\n\n if(octant > 3) {\n octant -= 4;\n sgn_result = -sgn_result;\n }\n\n if(octant > 1) {\n sgn_result = -sgn_result;\n }\n\n z = ((abs_x - y * P1) - y * P2) - y * P3;\n\n if(octant == 0) {\n gsl_sf_result cos_cs_result;\n const double t = 8.0*fabs(z)/M_PI - 1.0;\n stat_cs = cheb_eval_e(&cos_cs, t, &cos_cs_result);\n result->val = 1.0 - 0.5*z*z * (1.0 - z*z * cos_cs_result.val);\n }\n else { /* octant == 2 */\n gsl_sf_result sin_cs_result;\n const double t = 8.0*fabs(z)/M_PI - 1.0;\n stat_cs = cheb_eval_e(&sin_cs, t, &sin_cs_result);\n result->val = z * (1.0 + z*z * sin_cs_result.val);\n }\n\n result->val *= sgn_result;\n\n if(abs_x > 1.0/GSL_DBL_EPSILON) {\n result->err = fabs(result->val);\n }\n else if(abs_x > 100.0/GSL_SQRT_DBL_EPSILON) {\n result->err = 2.0 * abs_x * GSL_DBL_EPSILON * fabs(result->val);\n }\n else if(abs_x > 0.1/GSL_SQRT_DBL_EPSILON) {\n result->err = 2.0 * GSL_SQRT_DBL_EPSILON * fabs(result->val);\n }\n else {\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n }\n\n return stat_cs;\n }\n }\n}\n\n\nint\ngsl_sf_hypot_e(const double x, const double y, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x == 0.0 && y == 0.0) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else {\n const double a = fabs(x);\n const double b = fabs(y);\n const double min = GSL_MIN_DBL(a,b);\n const double max = GSL_MAX_DBL(a,b);\n const double rat = min/max;\n const double root_term = sqrt(1.0 + rat*rat);\n\n if(max < GSL_DBL_MAX/root_term) {\n result->val = max * root_term;\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n OVERFLOW_ERROR(result);\n }\n }\n}\n\n\nint\ngsl_sf_complex_sin_e(const double zr, const double zi,\n gsl_sf_result * szr, gsl_sf_result * szi)\n{\n /* CHECK_POINTER(szr) */\n /* CHECK_POINTER(szi) */\n\n if(fabs(zi) < 1.0) {\n double ch_m1, sh;\n sinh_series(zi, &sh);\n cosh_m1_series(zi, &ch_m1);\n szr->val = sin(zr)*(ch_m1 + 1.0);\n szi->val = cos(zr)*sh;\n szr->err = 2.0 * GSL_DBL_EPSILON * fabs(szr->val);\n szi->err = 2.0 * GSL_DBL_EPSILON * fabs(szi->val);\n return GSL_SUCCESS;\n }\n else if(fabs(zi) < GSL_LOG_DBL_MAX) {\n double ex = exp(zi);\n double ch = 0.5*(ex+1.0/ex);\n double sh = 0.5*(ex-1.0/ex);\n szr->val = sin(zr)*ch;\n szi->val = cos(zr)*sh;\n szr->err = 2.0 * GSL_DBL_EPSILON * fabs(szr->val);\n szi->err = 2.0 * GSL_DBL_EPSILON * fabs(szi->val);\n return GSL_SUCCESS;\n }\n else {\n OVERFLOW_ERROR_2(szr, szi);\n }\n}\n\n\nint\ngsl_sf_complex_cos_e(const double zr, const double zi,\n gsl_sf_result * czr, gsl_sf_result * czi)\n{\n /* CHECK_POINTER(czr) */\n /* CHECK_POINTER(czi) */\n\n if(fabs(zi) < 1.0) {\n double ch_m1, sh;\n sinh_series(zi, &sh);\n cosh_m1_series(zi, &ch_m1);\n czr->val = cos(zr)*(ch_m1 + 1.0);\n czi->val = -sin(zr)*sh;\n czr->err = 2.0 * GSL_DBL_EPSILON * fabs(czr->val);\n czi->err = 2.0 * GSL_DBL_EPSILON * fabs(czi->val);\n return GSL_SUCCESS;\n }\n else if(fabs(zi) < GSL_LOG_DBL_MAX) {\n double ex = exp(zi);\n double ch = 0.5*(ex+1.0/ex);\n double sh = 0.5*(ex-1.0/ex);\n czr->val = cos(zr)*ch;\n czi->val = -sin(zr)*sh;\n czr->err = 2.0 * GSL_DBL_EPSILON * fabs(czr->val);\n czi->err = 2.0 * GSL_DBL_EPSILON * fabs(czi->val);\n return GSL_SUCCESS;\n }\n else {\n OVERFLOW_ERROR_2(czr,czi);\n }\n}\n\n\nint\ngsl_sf_complex_logsin_e(const double zr, const double zi,\n gsl_sf_result * lszr, gsl_sf_result * lszi)\n{\n /* CHECK_POINTER(lszr) */\n /* CHECK_POINTER(lszi) */\n\n if(zi > 60.0) {\n lszr->val = -M_LN2 + zi;\n lszi->val = 0.5*M_PI - zr;\n lszr->err = 2.0 * GSL_DBL_EPSILON * fabs(lszr->val);\n lszi->err = 2.0 * GSL_DBL_EPSILON * fabs(lszi->val);\n }\n else if(zi < -60.0) {\n lszr->val = -M_LN2 - zi;\n lszi->val = -0.5*M_PI + zr;\n lszr->err = 2.0 * GSL_DBL_EPSILON * fabs(lszr->val);\n lszi->err = 2.0 * GSL_DBL_EPSILON * fabs(lszi->val);\n }\n else {\n gsl_sf_result sin_r, sin_i;\n int status;\n gsl_sf_complex_sin_e(zr, zi, &sin_r, &sin_i); /* ok by construction */\n status = gsl_sf_complex_log_e(sin_r.val, sin_i.val, lszr, lszi);\n if(status == GSL_EDOM) {\n DOMAIN_ERROR_2(lszr, lszi);\n }\n }\n return gsl_sf_angle_restrict_symm_e(&(lszi->val));\n}\n\n\nint\ngsl_sf_lnsinh_e(const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x <= 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(fabs(x) < 1.0) {\n double eps;\n sinh_series(x, &eps);\n result->val = log(eps);\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(x < -0.5*GSL_LOG_DBL_EPSILON) {\n result->val = x + log(0.5*(1.0 - exp(-2.0*x)));\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n result->val = -M_LN2 + x;\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\n\nint gsl_sf_lncosh_e(const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(fabs(x) < 1.0) {\n double eps;\n cosh_m1_series(x, &eps);\n return gsl_sf_log_1plusx_e(eps, result);\n }\n else if(x < -0.5*GSL_LOG_DBL_EPSILON) {\n result->val = x + log(0.5*(1.0 + exp(-2.0*x)));\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n result->val = -M_LN2 + x;\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\n\n/*\ninline int gsl_sf_sincos_e(const double theta, double * s, double * c)\n{\n double tan_half = tan(0.5 * theta);\n double den = 1. + tan_half*tan_half;\n double cos_theta = (1.0 - tan_half*tan_half) / den;\n double sin_theta = 2.0 * tan_half / den;\n}\n*/\n\nint\ngsl_sf_polar_to_rect(const double r, const double theta,\n gsl_sf_result * x, gsl_sf_result * y)\n{\n double t = theta;\n int status = gsl_sf_angle_restrict_symm_e(&t);\n double c = cos(t);\n double s = sin(t);\n x->val = r * cos(t);\n y->val = r * sin(t);\n x->err = r * fabs(s * GSL_DBL_EPSILON * t);\n x->err += 2.0 * GSL_DBL_EPSILON * fabs(x->val);\n y->err = r * fabs(c * GSL_DBL_EPSILON * t);\n y->err += 2.0 * GSL_DBL_EPSILON * fabs(y->val);\n return status;\n}\n\n\nint\ngsl_sf_rect_to_polar(const double x, const double y,\n gsl_sf_result * r, gsl_sf_result * theta)\n{\n int stat_h = gsl_sf_hypot_e(x, y, r);\n if(r->val > 0.0) {\n theta->val = atan2(y, x);\n theta->err = 2.0 * GSL_DBL_EPSILON * fabs(theta->val);\n return stat_h;\n }\n else {\n DOMAIN_ERROR(theta);\n }\n}\n\n\nint gsl_sf_angle_restrict_symm_err_e(const double theta, gsl_sf_result * result)\n{\n /* synthetic extended precision constants */\n const double P1 = 4 * 7.8539812564849853515625e-01;\n const double P2 = 4 * 3.7748947079307981766760e-08;\n const double P3 = 4 * 2.6951514290790594840552e-15;\n const double TwoPi = 2*(P1 + P2 + P3);\n\n const double y = GSL_SIGN(theta) * 2 * floor(fabs(theta)/TwoPi);\n double r = ((theta - y*P1) - y*P2) - y*P3;\n\n if(r > M_PI) { r = (((r-2*P1)-2*P2)-2*P3); } /* r-TwoPi */\n else if (r < -M_PI) r = (((r+2*P1)+2*P2)+2*P3); /* r+TwoPi */\n\n result->val = r;\n\n if(fabs(theta) > 0.0625/GSL_DBL_EPSILON) {\n result->val = GSL_NAN;\n result->err = GSL_NAN;\n GSL_ERROR (\"error\", GSL_ELOSS);\n }\n else if(fabs(theta) > 0.0625/GSL_SQRT_DBL_EPSILON) {\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val - theta);\n return GSL_SUCCESS;\n }\n else {\n double delta = fabs(result->val - theta);\n result->err = 2.0 * GSL_DBL_EPSILON * ((delta < M_PI) ? delta : M_PI);\n return GSL_SUCCESS;\n }\n}\n\n\nint gsl_sf_angle_restrict_pos_err_e(const double theta, gsl_sf_result * result)\n{\n /* synthetic extended precision constants */\n const double P1 = 4 * 7.85398125648498535156e-01;\n const double P2 = 4 * 3.77489470793079817668e-08;\n const double P3 = 4 * 2.69515142907905952645e-15;\n const double TwoPi = 2*(P1 + P2 + P3);\n\n const double y = 2*floor(theta/TwoPi);\n\n double r = ((theta - y*P1) - y*P2) - y*P3;\n\n if(r > TwoPi) {r = (((r-2*P1)-2*P2)-2*P3); } /* r-TwoPi */\n else if (r < 0) { /* may happen due to FP rounding */\n r = (((r+2*P1)+2*P2)+2*P3); /* r+TwoPi */\n }\n\n result->val = r;\n\n if(fabs(theta) > 0.0625/GSL_DBL_EPSILON) {\n result->val = GSL_NAN;\n result->err = fabs(result->val);\n GSL_ERROR (\"error\", GSL_ELOSS);\n }\n else if(fabs(theta) > 0.0625/GSL_SQRT_DBL_EPSILON) {\n result->err = GSL_DBL_EPSILON * fabs(result->val - theta);\n return GSL_SUCCESS;\n }\n else {\n double delta = fabs(result->val - theta);\n result->err = 2.0 * GSL_DBL_EPSILON * ((delta < M_PI) ? delta : M_PI);\n return GSL_SUCCESS;\n }\n}\n\n\nint gsl_sf_angle_restrict_symm_e(double * theta)\n{\n gsl_sf_result r;\n int stat = gsl_sf_angle_restrict_symm_err_e(*theta, &r);\n *theta = r.val;\n return stat;\n}\n\n\nint gsl_sf_angle_restrict_pos_e(double * theta)\n{\n gsl_sf_result r;\n int stat = gsl_sf_angle_restrict_pos_err_e(*theta, &r);\n *theta = r.val;\n return stat;\n}\n\n\nint gsl_sf_sin_err_e(const double x, const double dx, gsl_sf_result * result)\n{\n int stat_s = gsl_sf_sin_e(x, result);\n result->err += fabs(cos(x) * dx);\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return stat_s;\n}\n\n\nint gsl_sf_cos_err_e(const double x, const double dx, gsl_sf_result * result)\n{\n int stat_c = gsl_sf_cos_e(x, result);\n result->err += fabs(sin(x) * dx);\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return stat_c;\n}\n\n\n#if 0\nint\ngsl_sf_sin_pi_x_e(const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(-100.0 < x && x < 100.0) {\n result->val = sin(M_PI * x) / (M_PI * x);\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n const double N = floor(x + 0.5);\n const double f = x - N;\n\n if(N < INT_MAX && N > INT_MIN) {\n /* Make it an integer if we can. Saves another\n * call to floor().\n */\n const int intN = (int)N;\n const double sign = ( GSL_IS_ODD(intN) ? -1.0 : 1.0 );\n result->val = sign * sin(M_PI * f);\n result->err = GSL_DBL_EPSILON * fabs(result->val);\n }\n else if(N > 2.0/GSL_DBL_EPSILON || N < -2.0/GSL_DBL_EPSILON) {\n /* All integer-valued floating point numbers\n * bigger than 2/eps=2^53 are actually even.\n */\n result->val = 0.0;\n result->err = 0.0;\n }\n else {\n const double resN = N - 2.0*floor(0.5*N); /* 0 for even N, 1 for odd N */\n const double sign = ( fabs(resN) > 0.5 ? -1.0 : 1.0 );\n result->val = sign * sin(M_PI*f);\n result->err = GSL_DBL_EPSILON * fabs(result->val);\n }\n\n return GSL_SUCCESS;\n }\n}\n#endif\n\n\nint gsl_sf_sinc_e(double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n {\n const double ax = fabs(x);\n\n if(ax < 0.8) {\n /* Do not go to the limit of the fit since\n * there is a zero there and the Chebyshev\n * accuracy will go to zero.\n */\n return cheb_eval_e(&sinc_cs, 2.0*ax-1.0, result);\n }\n else if(ax < 100.0) {\n /* Small arguments are no problem.\n * We trust the library sin() to\n * roughly machine precision.\n */\n result->val = sin(M_PI * ax)/(M_PI * ax);\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n /* Large arguments must be handled separately.\n */\n const double r = M_PI*ax;\n gsl_sf_result s;\n int stat_s = gsl_sf_sin_e(r, &s);\n result->val = s.val/r;\n result->err = s.err/r + 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_s;\n }\n }\n}\n\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_sin(const double x)\n{\n EVAL_RESULT(gsl_sf_sin_e(x, &result));\n}\n\ndouble gsl_sf_cos(const double x)\n{\n EVAL_RESULT(gsl_sf_cos_e(x, &result));\n}\n\ndouble gsl_sf_hypot(const double x, const double y)\n{\n EVAL_RESULT(gsl_sf_hypot_e(x, y, &result));\n}\n\ndouble gsl_sf_lnsinh(const double x)\n{\n EVAL_RESULT(gsl_sf_lnsinh_e(x, &result));\n}\n\ndouble gsl_sf_lncosh(const double x)\n{\n EVAL_RESULT(gsl_sf_lncosh_e(x, &result));\n}\n\ndouble gsl_sf_angle_restrict_symm(const double theta)\n{\n double result = theta;\n EVAL_DOUBLE(gsl_sf_angle_restrict_symm_e(&result));\n}\n\ndouble gsl_sf_angle_restrict_pos(const double theta)\n{\n double result = theta;\n EVAL_DOUBLE(gsl_sf_angle_restrict_pos_e(&result));\n}\n\n#if 0\ndouble gsl_sf_sin_pi_x(const double x)\n{\n EVAL_RESULT(gsl_sf_sin_pi_x_e(x, &result));\n}\n#endif\n\ndouble gsl_sf_sinc(const double x)\n{\n EVAL_RESULT(gsl_sf_sinc_e(x, &result));\n}\n", "meta": {"hexsha": "a604cd86a5a1544802ff1e0e876a1b36b81990fd", "size": 19713, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/trig.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/trig.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/trig.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": 25.5349740933, "max_line_length": 81, "alphanum_fraction": 0.6141632425, "num_tokens": 6917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5789502667723431}} {"text": "/*\n * splinepdf.c: Routines to efficiently sample from a dimension of an\n * N-dimensional spline surface. Uses a Metropolis-Hastings Markov Chain\n * sampler.\n */\n\n#include \n#include \n\n#include \"photospline/splinetable.h\"\n#include \"photospline/bspline.h\"\n#include \"photospline/splinepdf.h\"\n\nvoid logsplinepdf_n_sample(double *result, int results, int burnin,\n double *coords, int dim, struct splinetable *table, int derivatives,\n double (* proposal)(void*), double (* proposal_pdf)(double, double, void*),\n void* proposal_info, const gsl_rng *rng)\n{\n\tint i;\n\tint centers[table->ndim];\n\tdouble val, lastval;\n\tdouble lastlogpdf = -INFINITY, logpdf;\n\tdouble lastproppdf, proppdf;\n\tdouble odds;\n\tdouble mint, maxt;\n#ifdef DEBUG\n\tint accepted=0;\n#endif\n\n\t/* Find the boundaries by choosing the first and last points\n\t * with full support */\n\tmint = table->extents[dim][0];\n\tmaxt = table->extents[dim][1];\n\n\tdo {\n\t\t/*\n\t\t * Get a starting point from the proposal distribution,\n\t\t * making sure the PDF at the starting point is finite\n\t\t * to avoid numerical problems.\n\t\t */\n\n\t\tcoords[dim] = lastval = (*proposal)(proposal_info);\n\n\t\tlastproppdf = (*proposal_pdf)(lastval,lastval,proposal_info);\n\t\tif (tablesearchcenters(table, coords, centers) != 0) {\n\t\t\tlastval = mint-1;\n\t\t\tcontinue;\n\t\t}\n\t\tlastlogpdf = ndsplineeval(table, coords, centers, 0);\n\t\tif (derivatives)\n\t\t\tlastlogpdf += log(ndsplineeval(table, coords, centers,\n\t\t\t derivatives));\n\t} while (isnan(lastlogpdf) || lastval < mint || lastval > maxt);\n\n\tfor (i = -burnin; i/burnin < results; i++) {\n\t\tcoords[dim] = val = (*proposal)(proposal_info);\n\n\t\t/*\n\t\t * If we ended up outside the table, reject the sample\n\t\t * and try again\n\t\t */\n\t\tif (val > maxt || val < mint ||\n\t\t tablesearchcenters(table, coords, centers) != 0) \n\t\t\tgoto reject;\n\t\t\t\n\t\tlogpdf = ndsplineeval(table, coords, centers, 0);\n\t\tif (derivatives)\n\t\t\tlogpdf += log(ndsplineeval(table, coords, centers,\n\t\t\t derivatives));\n\t\tproppdf = (*proposal_pdf)(val,lastval,proposal_info);\n\t\todds = exp(logpdf - lastlogpdf);\n\t\todds *= lastproppdf/proppdf;\n\n\t\tif (odds > 1. || gsl_rng_uniform(rng) < odds) {\n\t\t\t/* Accept this value */\n\t\t\tlastval = val;\n\t\t\tlastlogpdf = logpdf;\n\t\t\tlastproppdf = proppdf;\n\t\t#ifdef DEBUG\n\t\t\taccepted++;\n\t\t#endif\n\t\t}\n\n\t\t/*\n\t\t * Lastval has whatever we decided on now. If the burn-in\n\t\t * period has elapsed, write it to output array.\n\t\t *\n\t\t * NB: This code is used in both the accept and reject\n\t\t * cases.\n\t\t */\n\n\t reject:\n\t\tif (i >= 0 && (i % burnin) == 0)\n\t\t\tresult[i/burnin] = lastval;\n\t}\n#ifdef DEBUG\n\tprintf(\"Efficiency: %e\\n\", (double)(accepted)/(double)(i));\n#endif\n}\n\nvoid splinepdf_n_sample(double *result, int results, int burnin,\n double *coords, int dim, struct splinetable *table, int derivatives,\n double (* proposal)(void*), double (* proposal_pdf)(double, double, void*),\n void *proposal_info, const gsl_rng *rng)\n{\n\tint i;\n\tint centers[table->ndim];\n\tdouble val, lastval;\n\tdouble lastpdf, pdf;\n\tdouble lastproppdf, proppdf;\n\tdouble odds;\n\tdouble mint, maxt;\n#ifdef DEBUG\n\tint accepted=0;\n#endif\n\n\t/* Find the boundaries by choosing the first and last points\n\t * with full support */\n\tmint = table->extents[dim][0];\n\tmaxt = table->extents[dim][1];\n\n\t/* Get a fully-supported starting point from the proposal distribution. */\n\tdo {\n\t\tcoords[dim] = lastval = (*proposal)(proposal_info);\n\t} while (lastval < mint || lastval > maxt ||\n\t tablesearchcenters(table, coords, centers) != 0);\n\n\tlastproppdf = (*proposal_pdf)(lastval,lastval,proposal_info);\n\tlastpdf = ndsplineeval(table, coords, centers, derivatives);\n\n\tfor (i = -burnin; i/burnin < results; i++) {\n\t\tcoords[dim] = val = (*proposal)(proposal_info);\n\n\t\t/*\n\t\t * If we ended up outside the table, reject the sample\n\t\t * and try again\n\t\t */\n\t\tif (val > maxt || val < mint ||\n\t\t tablesearchcenters(table, coords, centers) != 0) \n\t\t\tgoto reject;\n\t\t\t\n\t\tpdf = ndsplineeval(table, coords, centers, derivatives);\n\t\tproppdf = (*proposal_pdf)(val,lastval,proposal_info);\n\t\todds = pdf/lastpdf;\n\t\todds *= lastproppdf/proppdf;\n\n\t\tif (odds > 1. || gsl_rng_uniform(rng) < odds) {\n\t\t\t/* Accept this value */\n\t\t\tlastval = val;\n\t\t\tlastpdf = pdf;\n\t\t\tlastproppdf = proppdf;\n\t\t\t#ifdef DEBUG\n\t\t\t\taccepted++;\n\t\t\t#endif\n\t\t}\n\n\t\t/*\n\t\t * Lastval has whatever we decided on now. If the burn-in\n\t\t * period has elapsed, write it to output array.\n\t\t *\n\t\t * NB: This code is used in both the accept and reject\n\t\t * cases.\n\t\t */\n\n\t reject:\n\t\tif (i >= 0 && (i % burnin) == 0)\n\t\t\tresult[i / burnin] = lastval;\n\t}\n\t#ifdef DEBUG\n\t\tprintf(\"Efficiency: %e\\n\", (double)(accepted)/(double)(i));\n\t#endif\n}\n\n", "meta": {"hexsha": "cd5b4acbe4364ca0ef2e7f77c21a0c594f2d71fe", "size": 4638, "ext": "c", "lang": "C", "max_stars_repo_path": "photospline/private/lib/splinepdf.c", "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_issues_repo_path": "photospline/private/lib/splinepdf.c", "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "photospline/private/lib/splinepdf.c", "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "avg_line_length": 26.6551724138, "max_line_length": 79, "alphanum_fraction": 0.6619232428, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.5788966305837584}} {"text": "#include \n#include \n#include \n#include \"cimple_mpc_computation.h\"\n\n/**\n * Set up weight matrices for the quadratic problem\n */\npolytope * set_cost_function(gsl_matrix *P,\n gsl_vector *q,\n gsl_matrix *L,\n gsl_vector *M,\n current_state *now,\n system_dynamics *s_dyn,\n cost_function *f_cost,\n size_t time_horizon){\n\n size_t N = time_horizon;\n size_t n = s_dyn->A->size1;\n size_t m = s_dyn->B->size2;\n\n\n /*Calculate P and q */\n // |B 0 0 0 0|\n // |AB B 0 0 0|\n // Ct = |A^2B AB B 0 0|\n // |A^3B A^2B AB B 0|\n // |A^4B A^3B A^2B AB B|\n\n // |I 0 0 0 0|\n // |A I 0 0 0|\n // A_K = |A^2 A I 0 0|\n // |A^3 A^2 A I 0|\n // |A^4 A^3 A^2 A I|\n\n // |A |\n // |A^2|\n // A_N = |A^3|\n // |A^4|\n // |A^5|\n\n //P = Q2 + Ct^T.R2.Ct\n //q = {([x^T.A_N^T + (A_K.K_hat)^T].[R2.Ct])+(0.5*r^T.Ct)}^T\n\n // symmetrize\n gsl_matrix * Q2 = gsl_matrix_alloc(N*m, N*m);\n gsl_matrix_view Q_view = gsl_matrix_submatrix(f_cost->Q,(f_cost->Q->size1-N),(f_cost->Q->size2-N),(N),(N));\n gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &Q_view.matrix,&Q_view.matrix, 0.0, Q2);\n gsl_matrix * R2 = gsl_matrix_alloc(N*n, N*n);\n gsl_matrix_view R_view = gsl_matrix_submatrix(f_cost->R,(f_cost->R->size1-N),(f_cost->R->size2-N),(N),(N));\n gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &R_view.matrix,&R_view.matrix, 0.0, R2);\n\n\n //Calculate P\n gsl_matrix * R2_dot_Ct = gsl_matrix_alloc(N*n, N*m);\n gsl_matrix_set_zero(R2_dot_Ct);\n gsl_matrix_view Ct_view = gsl_matrix_submatrix(s_dyn->aux_matrices->Ct,0,0,N,N);\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, R2, &Ct_view.matrix, 0.0, R2_dot_Ct);\n gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &Ct_view.matrix, R2_dot_Ct, 0.0, P);\n gsl_matrix_add(P, Q2);\n\n //Clean up!\n gsl_matrix_free(R2);\n gsl_matrix_free(Q2);\n\n //Calculate q\n gsl_vector_set_zero(q);\n gsl_vector * A_N_dot_x = gsl_vector_alloc(N*n);\n gsl_vector_set_zero(A_N_dot_x);\n gsl_matrix_view A_N_view = gsl_matrix_submatrix(s_dyn->aux_matrices->A_N,0,0,N,1);\n gsl_blas_dgemv(CblasNoTrans, 1.0, &A_N_view.matrix, now->x, 0.0, A_N_dot_x);\n gsl_vector * A_K_dot_K_hat = gsl_vector_alloc(N*n);\n gsl_vector_set_zero(A_K_dot_K_hat);\n gsl_matrix_view A_K_view = gsl_matrix_submatrix(s_dyn->aux_matrices->A_K,0,0,N,N);\n gsl_vector_view K_hat_view = gsl_vector_subvector(s_dyn->aux_matrices->K_hat,0,N);\n gsl_blas_dgemv(CblasNoTrans, 1.0, &A_K_view.matrix, &K_hat_view.vector, 0.0, A_K_dot_K_hat);\n\n //[x^T.A_N^T + (A_K.K_hat)^T]^T\n gsl_vector_add(A_N_dot_x, A_K_dot_K_hat);\n\n //{([x^T.A_N^T + (A_K.K_hat)^T].[R2.Ct])}^T\n //R2_dot_Ct was calculated earlier\n gsl_blas_dgemv(CblasTrans, 1.0, R2_dot_Ct, A_N_dot_x, 0.0, q);\n\n //(0.5*r^T.Ct)\n gsl_vector *Right_side = gsl_vector_alloc(N*m);\n gsl_vector_view r_view = gsl_vector_subvector(f_cost->r,(f_cost->r->size-N),N);\n gsl_blas_dgemv(CblasTrans, 0.5, &Ct_view.matrix, &r_view.vector, 0.0, Right_side);\n gsl_vector_add(q, Right_side);\n\n //Clean up!\n gsl_matrix_free(R2_dot_Ct);\n gsl_vector_free(A_N_dot_x);\n gsl_vector_free(A_K_dot_K_hat);\n gsl_vector_free(Right_side);\n\n\n /*GUROBI Convex Optimization: solve quadratic problem*/\n\n //Minimizing\n polytope * constraints_polytope = polytope_alloc(L->size1, L->size2);\n gsl_matrix_memcpy(constraints_polytope->H,L);\n gsl_vector_memcpy(constraints_polytope->G,M);\n\n //back to gsl polytope\n polytope *opt_constraints = polytope_minimize(constraints_polytope);\n polytope_free(constraints_polytope);\n\n// //Minimizing\n// polytope * constraints_polytope = polytope_alloc(L->size1, L->size2);\n// gsl_matrix_memcpy(constraints_polytope->H,L);\n// gsl_vector_memcpy(constraints_polytope->G,M);\n//\n// printf(\"\\n\\n\\n\\nHALT\\n\\n\\n\\n\\n\");\n// gsl_matrix_print(constraints_polytope->H,\"H\");\n// gsl_vector_print(constraints_polytope->G,\"G\");\n//\n// polytope *opt_constraints = polytope_minimize(constraints_polytope);\n// polytope_free(constraints_polytope);\n//\n//\n// printf(\"\\n\\n\\n\\nNOOOOO\\n\\n\\n\\n\\n\");\n// gsl_matrix_print(opt_constraints->H,\"H\");\n// gsl_vector_print(opt_constraints->G,\"G\");\n//\n// polytope *opt_constraints = polytope_alloc(10,N);\n// gsl_vector_set(opt_constraints->G,0,1);\n// gsl_vector_set(opt_constraints->G,1,-1);\n// gsl_vector_set(opt_constraints->G,2,1);\n// gsl_vector_set(opt_constraints->G,3,-1);\n// gsl_vector_set(opt_constraints->G,4,1);\n// gsl_vector_set(opt_constraints->G,5,-1);\n// gsl_vector_set(opt_constraints->G,6,1);\n// gsl_vector_set(opt_constraints->G,7,-1);\n// gsl_vector_set(opt_constraints->G,8,1);\n// gsl_vector_set(opt_constraints->G,9,-1);\n// gsl_matrix_set(opt_constraints->H,0,0,0.2);\n// gsl_matrix_set(opt_constraints->H,0,1,0);\n// gsl_matrix_set(opt_constraints->H,0,2,0);\n// gsl_matrix_set(opt_constraints->H,0,3,0);\n// gsl_matrix_set(opt_constraints->H,0,4,0);\n//\n// gsl_matrix_set(opt_constraints->H,1,0,-20);\n// gsl_matrix_set(opt_constraints->H,1,1,0);\n// gsl_matrix_set(opt_constraints->H,1,2,0);\n// gsl_matrix_set(opt_constraints->H,1,3,0);\n// gsl_matrix_set(opt_constraints->H,1,4,0);\n// gsl_matrix_set(opt_constraints->H,2,0,0.2);\n// gsl_matrix_set(opt_constraints->H,2,1,0.2);\n// gsl_matrix_set(opt_constraints->H,2,2,0);\n// gsl_matrix_set(opt_constraints->H,2,3,0);\n// gsl_matrix_set(opt_constraints->H,2,4,0);\n//\n// gsl_matrix_set(opt_constraints->H,3,0,-20);\n// gsl_matrix_set(opt_constraints->H,3,1,-20);\n// gsl_matrix_set(opt_constraints->H,3,2,0);\n// gsl_matrix_set(opt_constraints->H,3,3,0);\n// gsl_matrix_set(opt_constraints->H,3,4,0);\n// gsl_matrix_set(opt_constraints->H,4,0,0.2);\n// gsl_matrix_set(opt_constraints->H,4,1,0.2);\n// gsl_matrix_set(opt_constraints->H,4,2,0.2);\n// gsl_matrix_set(opt_constraints->H,4,3,0);\n// gsl_matrix_set(opt_constraints->H,4,4,0);\n//\n// gsl_matrix_set(opt_constraints->H,5,0,-20);\n// gsl_matrix_set(opt_constraints->H,5,1,-20);\n// gsl_matrix_set(opt_constraints->H,5,2,-20);\n// gsl_matrix_set(opt_constraints->H,5,3,0);\n// gsl_matrix_set(opt_constraints->H,5,4,0);\n// gsl_matrix_set(opt_constraints->H,6,0,0.2);\n// gsl_matrix_set(opt_constraints->H,6,1,0.2);\n// gsl_matrix_set(opt_constraints->H,6,2,0.2);\n// gsl_matrix_set(opt_constraints->H,6,3,0.2);\n// gsl_matrix_set(opt_constraints->H,6,4,0);\n//\n// gsl_matrix_set(opt_constraints->H,7,0,-20);\n// gsl_matrix_set(opt_constraints->H,7,1,-20);\n// gsl_matrix_set(opt_constraints->H,7,2,-20);\n// gsl_matrix_set(opt_constraints->H,7,3,-20);\n// gsl_matrix_set(opt_constraints->H,7,4,0);\n// gsl_matrix_set(opt_constraints->H,8,0,0.2);\n// gsl_matrix_set(opt_constraints->H,8,1,0.2);\n// gsl_matrix_set(opt_constraints->H,8,2,0.2);\n// gsl_matrix_set(opt_constraints->H,8,3,0.2);\n// gsl_matrix_set(opt_constraints->H,8,4,0.2);\n//\n// gsl_matrix_set(opt_constraints->H,9,0,-20);\n// gsl_matrix_set(opt_constraints->H,9,1,-20);\n// gsl_matrix_set(opt_constraints->H,9,2,-20);\n// gsl_matrix_set(opt_constraints->H,9,3,-20);\n// gsl_matrix_set(opt_constraints->H,9,4,-20);\n return opt_constraints;\n}\n\n/**\n * Set up GUROBI environment and solve qp\n */\nvoid compute_optimal_control_qp(gsl_matrix *low_u,\n double *low_cost,\n gsl_matrix *P,\n gsl_vector* q,\n polytope *opt_constraints,\n size_t time_horizon,\n size_t n){\n\n\n //Initialization for qp in gurobi\n GRBenv *env = NULL;\n GRBmodel *model = NULL;\n int error = 0;\n double sol[time_horizon];\n int optimstatus;\n double cost;\n\n\n /* Create environment */\n\n error = GRBloadenv(&env, \"qp.log\");\n if (error) goto QUIT;\n error = GRBsetintparam(env, GRB_INT_PAR_OUTPUTFLAG, 0);\n if (error) goto QUIT;\n\n\n /* Create an empty model */\n\n error = GRBnewmodel(env, &model, \"qp\", 0, NULL, NULL, NULL, NULL, NULL);\n if (error) goto QUIT;\n /* Add variables */\n\n error = GRBaddvars(model, (int)time_horizon, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL,\n NULL);\n if (error) goto QUIT;\n\n /* Quadratic objective terms */\n\n error = gsl_matrix_to_qpterm_gurobi(P, model, time_horizon);\n if (error) goto QUIT;\n\n /* Linear objective term */\n\n error = gsl_vector_to_linterm_gurobi(q, model, time_horizon);\n if (error) goto QUIT;\n\n\n /* Add constraints*/\n\n error = polytope_to_constraints_gurobi(opt_constraints,model,time_horizon);\n if (error) goto QUIT;\n /* Optimize model */\n\n error = GRBoptimize(model);\n if (error) goto QUIT;\n\n /* Write model to 'qp.lp' */\n\n error = GRBwrite(model, \"qp.lp\");\n if (error) goto QUIT;\n\n /* Capture solution information */\n\n error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);\n if (error) goto QUIT;\n\n error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &cost);\n if (error) goto QUIT;\n\n error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, (int)time_horizon, sol);\n if (error) goto QUIT;\n\n printf(\"\\nOptimization complete\\n\");\n if (optimstatus == GRB_OPTIMAL) {\n printf(\"\\nOptimal objective: %.4e\\n\", cost);\n\n for(size_t i=0;ix->size;\n size_t N = current_time_horizon;\n\n double low_cost = INFINITY;\n double err_weight = f_cost->distance_error_weight;\n\n //Set start region (depends on conservative path or not)\n polytope *P1;\n\n int start = now->current_abs_state;\n\n if (d_dyn->conservative == 1){\n // Take convex hull or polytope as starting polytope P1\n\n // if convex_hull != NULL => hull was computed => several polytopes in that region\n if (d_dyn->abstract_states_set[start]->convex_hull->H != NULL){\n P1 = d_dyn->abstract_states_set[start]->convex_hull;\n } else{\n P1 = d_dyn->abstract_states_set[start]->cells[0]->polytope_description;\n }\n } else{\n // Take original proposition preserving abstract state as constraint\n // must be single polytope (ensuring convex)\n\n if (d_dyn->original_regions[start]->cells_count == 1){\n P1 = d_dyn->original_regions[start]->cells[0]->polytope_description;\n } else {\n fprintf(stderr, \"\\nIn Region of polytopes(%d): `conservative = False` arg requires that original abstract_states_set be convex\\n\", now->current_abs_state);\n exit(EXIT_FAILURE);\n }\n }\n\n\n //Find optimal path into target region\n //by finding polytope that is easiest to reach in target region\n\n // for each polytope in target region\n for (int i = 0; i < d_dyn->abstract_states_set[target_abs_state]->cells_count; i++){\n polytope *P3 = d_dyn->abstract_states_set[target_abs_state]->cells[i]->polytope_description;\n\n //Finding a path to target region\n if (err_weight > 0){\n //Set r (=xc.R)(from default to polytope specific):\n double *xc = P3->chebyshev_center;\n\n //r[n*(N-1), n*N] += err_weight * xc;\n for (size_t j = n * (N - 1); j < n*N; j++){\n double * element_value = gsl_vector_ptr(f_cost->r, j);\n * element_value += err_weight * xc[i];\n gsl_vector_set(f_cost->r, j, *element_value);\n }\n\n search_better_path(low_u, now,s_dyn, P1, P3,d_dyn->ord, N, f_cost, &low_cost, polytope_list_backup, d_dyn->time_horizon);\n //Reset r vector to default values\n for (size_t j = n * (N - 1); j < n*N; j++){\n double * element_value = gsl_vector_ptr(f_cost->r, j);\n * element_value -= err_weight * xc[i];\n gsl_vector_set(f_cost->r, j, * element_value);\n }\n\n } else{\n search_better_path(low_u, now,s_dyn, P1, P3,d_dyn->ord, N, f_cost, &low_cost, polytope_list_backup, d_dyn->time_horizon);\n }\n }\n\n if (low_cost == INFINITY){\n //raise Exception\n fprintf(stderr, \"\\nget_input: Did not find any trajectory\\n\");\n exit(EXIT_FAILURE);\n }\n\n};\n\n\n/**\n * Calculates (optimal) input to reach desired state (P3) from current state (now) through convex optimization\n */\nvoid search_better_path(gsl_matrix *low_u,\n current_state *now,\n system_dynamics *s_dyn,\n polytope *P1,\n polytope *P3,\n int ord ,\n size_t time_horizon,\n cost_function * f_cost,\n double *low_cost,\n polytope **polytope_list_backup,\n size_t total_time){\n\n //Auxiliary variables\n size_t N = time_horizon;\n size_t n = s_dyn->A->size2;\n size_t m = s_dyn->B->size2;\n\n\n //Build list of polytopes that the state is going to be in in the next N time steps\n polytope **polytope_list = malloc(sizeof(polytope)*(N+1));\n polytope_list[0] = polytope_alloc(P1->H->size1,P1->H->size2);\n gsl_matrix_memcpy(polytope_list[0]->H, P1->H);\n gsl_vector_memcpy(polytope_list[0]->G, P1->G);\n\n for (int i = 1; i < N; i++) {\n polytope_list[i] = polytope_alloc(P1->H->size1,P1->H->size2);\n gsl_matrix_memcpy(polytope_list[i]->H, P1->H);\n gsl_vector_memcpy(polytope_list[i]->G, P1->G);\n }\n polytope_list[N] = polytope_alloc(P3->H->size1, P3->H->size2);\n gsl_matrix_memcpy(polytope_list[N]->H, P3->H);\n gsl_vector_memcpy(polytope_list[N]->G, P3->G);\n\n size_t sum_polytope_sizes = 0;\n for(int i = 0; iH->size1;\n }\n\n polytope *constraints = set_path_constraints(now, s_dyn, polytope_list, N);\n\n //Updating backup list of polytopes\n //If polytope list doesn't have to be initialized completely, old ones have first to be destroyed:\n if(N< total_time) {\n for (size_t i = total_time; i > total_time - N - 1; i--) {\n polytope_free(polytope_list_backup[i]);\n }\n }\n //List is updated (or created, if total_time == N)\n for(size_t i = total_time-N; i< total_time+1; i++){\n size_t k =i-(total_time-N);\n polytope_list_backup[i] = polytope_alloc(polytope_list[k]->H->size1,polytope_list[k]->H->size2);\n gsl_matrix_memcpy(polytope_list_backup[i]->H,polytope_list[k]->H);\n gsl_vector_memcpy(polytope_list_backup[i]->G,polytope_list[k]->G);\n }\n\n for(int i = 0; i< N+1; i++){\n polytope_free(polytope_list[i]);\n }\n free(polytope_list);\n\n\n if (ord == 2){\n gsl_matrix * P = gsl_matrix_alloc(N*m, N*m);\n gsl_vector * q = gsl_vector_alloc(N*m);\n\n polytope *opt_constraints = set_cost_function(P, q, constraints->H, constraints->G, now, s_dyn, f_cost, N);\n compute_optimal_control_qp(low_u, low_cost, P, q, opt_constraints, N, n);\n polytope_free(opt_constraints);\n gsl_vector_free(q);\n gsl_matrix_free(P);\n\n }\n polytope_free(constraints);\n};\n\n\n/**\n * Compute a polytope that constraints the system over the next N time steps to fullfill the GR(1) specifications\n */\npolytope * set_path_constraints(current_state * now,\n system_dynamics * s_dyn,\n polytope **list_polytopes,\n size_t N){\n //Disturbance assumed at every step and full dimension of s_dyn.Wset\n\n // Help variables\n size_t n = s_dyn->A->size2; // State space dimension\n size_t m = s_dyn->B->size2;\n size_t sum_polytope_dim = 0; // Sum of dimension n of all polytopes in the list\n polytope *scaled_W_set = polytope_linear_transform(s_dyn->W_set, s_dyn->E); // multiplication: EW\n\n\n polytope **robust_polytope_list = malloc(sizeof(polytope)*(N+1));\n for(size_t i = 0; i < N+1; i++){\n //Subtract EW of polytope to make them robust against disturbances\n robust_polytope_list[i] = polytope_pontryagin(list_polytopes[i], scaled_W_set);\n sum_polytope_dim += robust_polytope_list[i]->H->size1;\n\n }\n\n /* INITIALIZE MATRICES: Lk, Mk, constraints*/\n polytope *constraints = polytope_alloc(sum_polytope_dim, n*(N+1));\n gsl_matrix_set_zero(constraints->H);\n gsl_vector_set_zero(constraints->G);\n /*\n * |G_0|\n * |G_1|\n *Mk = |G_2| dim[sum_polytope_dim x 1]\n * |G_3|\n * |G_4|\n *\n * with M = |Mk|\n * |Mu|\n * */\n\n /*\n * |H_0 0 0 0 0 |\n * |0 H_1 0 0 0 |\n * constaints->H= |0 0 H_2 0 0 | dim[sum_polytope_dim x n*N]\n * |0 0 0 H_3 0 |\n * |0 0 0 0 H_4|\n * */\n\n //Loop over N and polytopes in parallel\n size_t polytope_count = 0;\n for(int i = 0; iH\n for(size_t j = 0; jH->size1; k++){\n gsl_matrix_set(constraints->H,polytope_count+k, j+(i*n), gsl_matrix_get(robust_polytope_list[i]->H,k,j));\n }\n }\n\n // Build constraints->g\n for(size_t j = 0; jG->size; j++){\n // Set entries Mk[j+polytope_count] = G_i[j]\n gsl_vector_set(constraints->G,j+polytope_count,gsl_vector_get(robust_polytope_list[i]->G,j));\n }\n\n polytope_count += robust_polytope_list[i]->H->size1;\n\n }\n /*Update L and M*/\n\n // Lk = H_constaints->Hdiag.L_default\n gsl_matrix_view L_default_view = gsl_matrix_submatrix(s_dyn->aux_matrices->L_default,0,0,n*(N+1),(m*N)+n);\n gsl_matrix *L_full = gsl_matrix_alloc(sum_polytope_dim, (m*N)+n);\n gsl_vector *M_full = gsl_vector_alloc(sum_polytope_dim);\n gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0, constraints->H, &L_default_view.matrix ,0.0,L_full);\n\n //Update M such that it includes the uncertainty of noise\n gsl_vector_memcpy(M_full, constraints->G);\n\n\n\n // Remove first constraints on x(0) they are obviously already satisfied\n // L_x = L[{(polytope[0]+1),(dim_n(L))},{1,n}]\n gsl_matrix_view L_x = gsl_matrix_submatrix(L_full, robust_polytope_list[0]->H->size1, 0, (L_full->size1)-(robust_polytope_list[0]->H->size1), n);\n // L_u = L[{(polytope[0]+1),(dim_n(L))},{(n+1),(dim_m(L))}]\n gsl_matrix_view L_u = gsl_matrix_submatrix(L_full, robust_polytope_list[0]->H->size1, n, (L_full->size1)-(robust_polytope_list[0]->H->size1), L_full->size2 - n);\n // M_view = M[{(polytope[0]+1),(dim_n(M))}]\n gsl_vector_view M_view = gsl_vector_subvector(M_full, robust_polytope_list[0]->H->size1, M_full->size-robust_polytope_list[0]->H->size1);\n\n //M = M-(L_x.x)\n gsl_vector * L_x_dot_X0 = gsl_vector_alloc((L_full->size1)-(robust_polytope_list[0]->H->size1));\n gsl_blas_dgemv(CblasNoTrans, 1.0, &L_x.matrix, now->x, 0.0, L_x_dot_X0);\n gsl_vector_sub(&M_view.vector, L_x_dot_X0);\n\n polytope * return_constraints = polytope_alloc(constraints->H->size1-robust_polytope_list[0]->H->size1, ((constraints->H->size2)-(robust_polytope_list[0]->H->size2)));\n\n gsl_matrix_memcpy(return_constraints->H, &L_u.matrix);\n gsl_vector_memcpy(return_constraints->G, &M_view.vector);\n //Clean up!\n polytope_free(scaled_W_set);\n polytope_free(constraints);\n for(size_t i = 0; i < N+1; i++){\n polytope_free(robust_polytope_list[i]);\n }\n free(robust_polytope_list);\n gsl_vector_free(L_x_dot_X0);\n\n return return_constraints;\n\n};\n\n", "meta": {"hexsha": "e159a5c488d4a27d94acf5ef227e5ff358228a9a", "size": 21737, "ext": "c", "lang": "C", "max_stars_repo_path": "Interface/Cimple/cimple_mpc_computation.c", "max_stars_repo_name": "shaesaert/TuLiPXML", "max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z", "max_issues_repo_path": "Interface/Cimple/cimple_mpc_computation.c", "max_issues_repo_name": "shaesaert/TuLiPXML", "max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z", "max_forks_repo_path": "Interface/Cimple/cimple_mpc_computation.c", "max_forks_repo_name": "shaesaert/TuLiPXML", "max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z", "avg_line_length": 36.4103852596, "max_line_length": 171, "alphanum_fraction": 0.604867277, "num_tokens": 6469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5788005194971999}} {"text": "//This does CELL (~soma) stage of peephole LSTM (long short-term memory) model.\n//This requires each neuron to have 4 input time series, Xc, Xi, Xf, Xo,\n//where Xc is the usual (or \"cellular\") input and Xi, Xf, Xo the inputs for the input, forget, output gates.\n//Xc, Xi, Xf, Xo are the output of separate linear IN stages (weights and baises).\n//In this version, these are stacked into one matrix\n//For dim=0: X = [Xc; Xi; Xf; Xo]; for dim=1: X = [Xc Xi Xf Xo].\n\n//For dim=0, I[:,t] = sig{Xi[:,t] + Ui*C[:,t-1]}\n// F[:,t] = sig{Xf[:,t] + Uf*C[:,t-1]}\n// O[:,t] = sig{Xo[:,t] + Uo*C[:,t-1]}\n// C[:,t] = F[:,t].*C[:,t-1] + I[:,t].*sig{Xc[t,:]}\n// Y[:,t] = tanh{O[:,t].*C[:,t]}\n//with sizes Xc, Xi, Xf, Xo: N x T\n// Ui, Uf, Uo: N x N\n// Y: N x T\n//\n//For dim=1, I[t,:] = sig{Xi[t,:] + C[t-1,:]*Ui} \n// F[t,:] = sig{Xf[t,:] + C[t-1,:]*Uf} \n// O[t,:] = sig{Xo[t,:] + C[t-1,:]*Uo}\n// C[t,:] = F[t,:].*C[t-1,:] + I[t,:].*sig{Xc[t,:]}\n// Y[t,:] = tanh{O[t,:].*C[t,:]}\n//with sizes Xc, Xi, Xf, Xo: T x N\n// Ui, Uf, Uo: N x N\n// Y: T x N\n//\n//where sig is the logistic (sigmoid) nonlinearity = 1/(1+exp(-x)),\n//I is the input gate, F is the forget gate, O is the output gate,\n//C is the \"cell input activation vector\",\n//H is an intermediate (hidden) vector (sometimes called the \"cell state vector\"),\n//Uc, Ui, Uf, Uo are NxN matrices, and Y is the final output (sometimes called the \"hidden state vector\").\n\n//The tanh is omitted here!! (To allow trying other nonlinearities.)\n\n//Note that, the neurons of a layer are independent only if Uc, Ui, Uf, Uo are diagonal matrices.\n//This is only really a CELL (~soma) stage in that case.\n\n#include \n#include \n#include \n#include \n\n#ifdef I\n #undef I\n#endif\n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint lstm_peephole_s (float *Y, const float *X, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\nint lstm_peephole_d (double *Y, const double *X, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\n\nint lstm_peephole_inplace_s (float *X, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\nint lstm_peephole_inplace_d (double *X, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\n\n\nint lstm_peephole_s (float *Y, const float *X, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim)\n{\n const float o = 1.0f;\n const size_t N2 = 2*N, N3 = 3*N, NT = N*T, NT2 = 2*N*T, NT3 = 3*N*T;\n size_t nT, tN, tN4;\n\n float *C, *I, *F, *O;\n if (!(C=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in lstm_peephole_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(I=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in lstm_peephole_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(F=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in lstm_peephole_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(O=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in lstm_peephole_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n if (dim==0u)\n {\n if (iscolmajor)\n {\n for (size_t n=0u; n\n#include \n#include \n#include \n#include \n#include \n\n#define REAL double\n\n/* [Engeln-Mullges + Uhlig, Alg. 4.42]\n */\n\nint\ngsl_linalg_HH_solve (gsl_matrix * A, const gsl_vector * b, gsl_vector * x)\n{\n if (A->size1 > A->size2)\n {\n /* System is underdetermined. */\n\n GSL_ERROR (\"System is underdetermined\", GSL_EINVAL);\n }\n else if (A->size2 != x->size)\n {\n GSL_ERROR (\"matrix and vector sizes must be equal\", GSL_EBADLEN);\n }\n else\n {\n int status ;\n\n gsl_vector_memcpy (x, b);\n\n status = gsl_linalg_HH_svx (A, x);\n \n return status ;\n }\n}\n\nint\ngsl_linalg_HH_svx (gsl_matrix * A, gsl_vector * x)\n{\n if (A->size1 > A->size2)\n {\n /* System is underdetermined. */\n\n GSL_ERROR (\"System is underdetermined\", GSL_EINVAL);\n }\n else if (A->size2 != x->size)\n {\n GSL_ERROR (\"matrix and vector sizes must be equal\", GSL_EBADLEN);\n }\n else\n {\n const size_t N = A->size1;\n const size_t M = A->size2;\n size_t i, j, k;\n REAL *d = (REAL *) malloc (N * sizeof (REAL));\n\n if (d == 0)\n {\n GSL_ERROR (\"could not allocate memory for workspace\", GSL_ENOMEM);\n }\n\n /* Perform Householder transformation. */\n\n for (i = 0; i < N; i++)\n {\n const REAL aii = gsl_matrix_get (A, i, i);\n REAL alpha;\n REAL f;\n REAL ak;\n REAL max_norm = 0.0;\n REAL r = 0.0;\n\n for (k = i; k < M; k++)\n {\n REAL aki = gsl_matrix_get (A, k, i);\n r += aki * aki;\n }\n\n if (r == 0.0)\n {\n /* Rank of matrix is less than size1. */\n free (d);\n GSL_ERROR (\"matrix is rank deficient\", GSL_ESING);\n }\n\n alpha = sqrt (r) * GSL_SIGN (aii);\n\n ak = 1.0 / (r + alpha * aii);\n gsl_matrix_set (A, i, i, aii + alpha);\n\n d[i] = -alpha;\n\n for (k = i + 1; k < N; k++)\n {\n REAL norm = 0.0;\n f = 0.0;\n for (j = i; j < M; j++)\n {\n REAL ajk = gsl_matrix_get (A, j, k);\n REAL aji = gsl_matrix_get (A, j, i);\n norm += ajk * ajk;\n f += ajk * aji;\n }\n max_norm = GSL_MAX (max_norm, norm);\n\n f *= ak;\n\n for (j = i; j < M; j++)\n {\n REAL ajk = gsl_matrix_get (A, j, k);\n REAL aji = gsl_matrix_get (A, j, i);\n gsl_matrix_set (A, j, k, ajk - f * aji);\n }\n }\n\n if (fabs (alpha) < 2.0 * GSL_DBL_EPSILON * sqrt (max_norm))\n {\n /* Apparent singularity. */\n free (d);\n GSL_ERROR(\"apparent singularity detected\", GSL_ESING);\n }\n\n /* Perform update of RHS. */\n\n f = 0.0;\n for (j = i; j < M; j++)\n {\n f += gsl_vector_get (x, j) * gsl_matrix_get (A, j, i);\n }\n f *= ak;\n for (j = i; j < M; j++)\n {\n REAL xj = gsl_vector_get (x, j);\n REAL aji = gsl_matrix_get (A, j, i);\n gsl_vector_set (x, j, xj - f * aji);\n }\n }\n\n /* Perform back-substitution. */\n\n for (i = N; i > 0 && i--;)\n {\n REAL xi = gsl_vector_get (x, i);\n REAL sum = 0.0;\n for (k = i + 1; k < N; k++)\n {\n sum += gsl_matrix_get (A, i, k) * gsl_vector_get (x, k);\n }\n\n gsl_vector_set (x, i, (xi - sum) / d[i]);\n }\n\n free (d);\n return GSL_SUCCESS;\n }\n}\n\n", "meta": {"hexsha": "6530c96969f538aacc78a2a1a12b380fcc1d5e8c", "size": 4651, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/linalg/hh.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/linalg/hh.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/linalg/hh.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": 25.8388888889, "max_line_length": 81, "alphanum_fraction": 0.4869920447, "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5784356719918167}} {"text": "\n#include \n#include \n\n#include \"fd3sep.h\"\n/* #include \"mxfuns.h\" */\n\n#include \n#include \n#include \n#include \n\n#define SVCUT 1.0e-9\n\n/*************************************************************************/\n\ndouble fd3sep ( long K, long M, long N, double **dftobs, double *sig,\n double **rvm, double **lfm, double **dftmod, double **dftres ) {\n\n long i, j, k, n;\n double s2;\n gsl_matrix *A, *U, *X, *V;\n gsl_vector *S, *w, *b, *x;\n\n /* prepare */\n\n A = gsl_matrix_alloc ( 2*M, 2*K );\n U = gsl_matrix_alloc ( 2*M, 2*K );\n X = gsl_matrix_alloc ( 2*K, 2*K );\n V = gsl_matrix_alloc ( 2*K, 2*K );\n S = gsl_vector_alloc ( 2*K );\n w = gsl_vector_alloc ( 2*K );\n b = gsl_vector_alloc ( 2*M );\n x = gsl_vector_alloc ( 2*K );\n\n /* for each DFT component */\n\n for ( s2 = n = 0 ; n <= N/2 ; n++ ) {\n\n /* assemble data vector and model matrix */\n\n for ( j = 0 ; j < M ; j++ ) {\n double s = *(sig+j);\n gsl_vector_set ( b, 2*j, *(*(dftobs+j)+2*n) /s );\n gsl_vector_set ( b, 2*j+1, *(*(dftobs+j)+2*n+1)/s );\n for ( k = 0 ; k < K ; k++ ) {\n double q, v, fv, rez, imz;\n q = 2.0 * M_PI * ((double)n)/((double)N);\n v = *(*(rvm+k)+j);\n fv = floor(v);\n rez = *(*(lfm+k)+j) *\n ( ((fv+1)-v)*cos(fv*q) + (v-fv)*cos((fv+1)*q) );\n imz = - *(*(lfm+k)+j) *\n ( ((fv+1)-v)*sin(fv*q) + (v-fv)*sin((fv+1)*q) );\n gsl_matrix_set ( A, 2*j, 2*k, rez/s );\n gsl_matrix_set ( A, 2*j, 2*k+1, - imz/s );\n gsl_matrix_set ( A, 2*j+1, 2*k, imz/s );\n gsl_matrix_set ( A, 2*j+1, 2*k+1, rez/s );\n }\n gsl_matrix_memcpy ( U, A );\n }\n\n /* solve for model parameters */\n\n /* gsl_linalg_SV_decomp ( U, V, S, w ); */\n /* gsl_linalg_SV_decomp_mod ( U, X, V, S, w ); */\n /* gsl_linalg_SV_decomp_jacobi ( U, V, S ); */\n\n gsl_linalg_SV_decomp_mod ( U, X, V, S, w );\n for ( k = 0 ; k < 2*K-1 ; k++ )\n if ( gsl_vector_get(S,2*K-1-k)/gsl_vector_get(S,0) < SVCUT )\n gsl_vector_set ( S, 2*K-1-k, 0 );\n gsl_linalg_SV_solve ( U, V, S, b, x );\n\n /* copy to output */\n\n for ( k = 0 ; k < K ; k++ ) {\n *(*(dftmod+k)+2*n ) = gsl_vector_get ( x, 2*k );\n *(*(dftmod+k)+2*n+1) = gsl_vector_get ( x, 2*k+1 );\n }\n\n /* compute s2 */\n\n for ( j = 0 ; j < M ; j++ ) for ( i = 0 ; i < 2 ; i++ ) {\n\n double bc, db, s = *(sig+j);\n\n for ( bc = k = 0 ; k < K ; k++ ) {\n bc += gsl_matrix_get( A, 2*j+i, 2*k ) * gsl_vector_get( x, 2*k );\n bc += gsl_matrix_get( A, 2*j+i, 2*k+1 ) * gsl_vector_get( x, 2*k+1 );\n }\n db = gsl_vector_get ( b, 2*j+i ) - bc;\n s2 += db * db * ( n % ((N+1)/2) ? 2 : 1 );\n *(*(dftres+j)+2*n+i) = db * s;\n\n }\n\n }\n\n /* close */\n\n gsl_matrix_free ( A );\n gsl_matrix_free ( U );\n gsl_matrix_free ( X );\n gsl_matrix_free ( V );\n gsl_vector_free ( S );\n gsl_vector_free ( w );\n gsl_vector_free ( b );\n gsl_vector_free ( x );\n\n return s2;\n\n}\n\n/*************************************************************************/\n\nvoid dft_fwd ( long m, long n, double **mxin, double **mxout ) {\n\n long i, j;\n double a = 1.0 / sqrt(n);\n gsl_fft_real_wavetable * dft_rewt;\n gsl_fft_real_workspace * dft_rews;\n\n dft_rewt = gsl_fft_real_wavetable_alloc (n);\n dft_rews = gsl_fft_real_workspace_alloc (n);\n\n for ( j = 0 ; j < m ; j++ ) {\n for ( i = 0; i < n; i++ ) *(*(mxout+j)+i+1) = a * *(*(mxin+j)+i);\n gsl_fft_real_transform ( *(mxout+j)+1, 1, n, dft_rewt, dft_rews );\n *(*(mxout+j)+0) = *(*(mxout+j)+1);\n *(*(mxout+j)+1) = 0;\n if ( ! n % 2 ) *(*(mxout+j)+n+1) = 0; /* if n even */\n }\n\n gsl_fft_real_wavetable_free ( dft_rewt );\n gsl_fft_real_workspace_free ( dft_rews );\n\n}\n\n/*************************************************************************/\n\nvoid dft_bck ( long m, long n, double **mxin, double **mxout ) {\n\n long i, j;\n double a = 1.0 / sqrt(n);\n gsl_fft_halfcomplex_wavetable * dft_hcwt;\n gsl_fft_real_workspace * dft_rews;\n\n dft_hcwt = gsl_fft_halfcomplex_wavetable_alloc (n);\n dft_rews = gsl_fft_real_workspace_alloc (n);\n\n for ( j = 0 ; j < m ; j++ ) {\n *(*(mxout+j)+0) = *(*(mxin+j)+0) / a;\n for ( i = 1; i < n; i++ ) *(*(mxout+j)+i) = *(*(mxin+j)+i+1) / a;\n gsl_fft_halfcomplex_inverse ( *(mxout+j), 1, n, dft_hcwt, dft_rews );\n }\n\n gsl_fft_halfcomplex_wavetable_free ( dft_hcwt );\n gsl_fft_real_workspace_free ( dft_rews );\n\n}\n\n/*************************************************************************/\n\n", "meta": {"hexsha": "7da8e4fc45683a3f758ed417925c30c6a2badbde", "size": 4767, "ext": "c", "lang": "C", "max_stars_repo_path": "fd3_Jul2014update/fd3sep.c", "max_stars_repo_name": "mrawls/FDBinary-tools", "max_stars_repo_head_hexsha": "26b78a12df53d9a1a477fcf247cbf2dad8c39836", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-25T09:45:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-28T14:43:53.000Z", "max_issues_repo_path": "fd3_Jul2014update/fd3sep.c", "max_issues_repo_name": "mrawls/FDBinary-tools", "max_issues_repo_head_hexsha": "26b78a12df53d9a1a477fcf247cbf2dad8c39836", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fd3_Jul2014update/fd3sep.c", "max_forks_repo_name": "mrawls/FDBinary-tools", "max_forks_repo_head_hexsha": "26b78a12df53d9a1a477fcf247cbf2dad8c39836", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8909090909, "max_line_length": 79, "alphanum_fraction": 0.4665408013, "num_tokens": 1652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5781292856801233}} {"text": "/* specfunc/bessel_Jn.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \"bessel.h\"\n#include \"bessel_amp_phase.h\"\n#include \"bessel_olver.h\"\n#include \n\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\n\nint gsl_sf_bessel_Jn_e(int n, double x, gsl_sf_result * result)\n{\n int sign = 1;\n\n if(n < 0) {\n /* reduce to case n >= 0 */\n n = -n;\n if(GSL_IS_ODD(n)) sign = -sign;\n } \n\n if(x < 0.0) {\n /* reduce to case x >= 0. */\n x = -x;\n if(GSL_IS_ODD(n)) sign = -sign;\n }\n\n /* CHECK_POINTER(result) */\n\n if(n == 0) {\n gsl_sf_result b0;\n int stat_J0 = gsl_sf_bessel_J0_e(x, &b0);\n result->val = sign * b0.val;\n result->err = b0.err;\n return stat_J0;\n }\n else if(n == 1) {\n gsl_sf_result b1;\n int stat_J1 = gsl_sf_bessel_J1_e(x, &b1);\n result->val = sign * b1.val;\n result->err = b1.err;\n return stat_J1;\n }\n else {\n if(x == 0.0) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(x*x < 10.0*(n+1.0)*GSL_ROOT5_DBL_EPSILON) {\n gsl_sf_result b;\n int status = gsl_sf_bessel_IJ_taylor_e((double)n, x, -1, 50, GSL_DBL_EPSILON, &b);\n result->val = sign * b.val;\n result->err = b.err;\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return status;\n }\n else if(GSL_ROOT4_DBL_EPSILON * x > (n*n+1.0)) {\n int status = gsl_sf_bessel_Jnu_asympx_e((double)n, x, result);\n result->val *= sign;\n return status;\n }\n else if(n > 50) {\n int status = gsl_sf_bessel_Jnu_asymp_Olver_e((double)n, x, result);\n result->val *= sign;\n return status;\n }\n else if(x > 1000.0)\n {\n /* We need this to avoid feeding large x to CF1; note that\n * due to the above check, we know that n <= 50.\n */\n int status = gsl_sf_bessel_Jnu_asympx_e((double)n, x, result);\n result->val *= sign;\n return status; \n }\n else {\n double ans;\n double err;\n double ratio;\n double sgn;\n int stat_b;\n int stat_CF1 = gsl_sf_bessel_J_CF1((double)n, x, &ratio, &sgn);\n\n /* backward recurrence */\n double Jkp1 = GSL_SQRT_DBL_MIN * ratio;\n double Jk = GSL_SQRT_DBL_MIN;\n double Jkm1;\n int k;\n\n for(k=n; k>0; k--) {\n Jkm1 = 2.0*k/x * Jk - Jkp1;\n Jkp1 = Jk;\n Jk = Jkm1;\n }\n\n if(fabs(Jkp1) > fabs(Jk)) {\n gsl_sf_result b1;\n stat_b = gsl_sf_bessel_J1_e(x, &b1);\n ans = b1.val/Jkp1 * GSL_SQRT_DBL_MIN;\n err = b1.err/Jkp1 * GSL_SQRT_DBL_MIN;\n }\n else {\n gsl_sf_result b0;\n stat_b = gsl_sf_bessel_J0_e(x, &b0);\n ans = b0.val/Jk * GSL_SQRT_DBL_MIN;\n err = b0.err/Jk * GSL_SQRT_DBL_MIN;\n }\n\n result->val = sign * ans;\n result->err = fabs(err);\n return GSL_ERROR_SELECT_2(stat_CF1, stat_b);\n }\n }\n}\n\n\nint\ngsl_sf_bessel_Jn_array(int nmin, int nmax, double x, double * result_array)\n{\n /* CHECK_POINTER(result_array) */\n\n if(nmin < 0 || nmax < nmin) {\n int n;\n for(n=nmax; n>=nmin; n--) {\n result_array[n-nmin] = 0.0;\n }\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(x == 0.0) {\n int n;\n for(n=nmax; n>=nmin; n--) {\n result_array[n-nmin] = 0.0;\n }\n if(nmin == 0) result_array[0] = 1.0;\n return GSL_SUCCESS;\n }\n else {\n gsl_sf_result r_Jnp1;\n gsl_sf_result r_Jn;\n int stat_np1 = gsl_sf_bessel_Jn_e(nmax+1, x, &r_Jnp1);\n int stat_n = gsl_sf_bessel_Jn_e(nmax, x, &r_Jn);\n int stat = GSL_ERROR_SELECT_2(stat_np1, stat_n);\n\n double Jnp1 = r_Jnp1.val;\n double Jn = r_Jn.val;\n double Jnm1;\n int n;\n\n if(stat == GSL_SUCCESS) {\n for(n=nmax; n>=nmin; n--) {\n result_array[n-nmin] = Jn;\n Jnm1 = -Jnp1 + 2.0*n/x * Jn;\n Jnp1 = Jn;\n Jn = Jnm1;\n }\n }\n else {\n for(n=nmax; n>=nmin; n--) {\n result_array[n-nmin] = 0.0;\n }\n }\n\n return stat;\n }\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_Jn(const int n, const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_Jn_e(n, x, &result));\n}\n", "meta": {"hexsha": "3d5c9581566427aa2aa277597e8ad9b4c440ae33", "size": 5066, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/bessel_Jn.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/specfunc/bessel_Jn.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_Jn.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.33, "max_line_length": 88, "alphanum_fraction": 0.5817212791, "num_tokens": 1681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414786, "lm_q2_score": 0.7154239957834734, "lm_q1q2_score": 0.5781106880088057}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\nint i;\nint max_lines=30;\ndouble xi, yi, x[30], y[30];\n\nconst char* getfield(char* line, int num)\n{\n const char* tok;\n for (tok = strtok(line, \",\");\n tok && *tok;\n tok = strtok(NULL, \";\\n\"))\n {\n if (!--num)\n return tok;\n }\n return NULL;\n}\n\nvoid read_csv(char* filename, int max_lines){\n FILE * f = fopen(filename, \"r\");\n char line[1024];\n int l = 0;\n fgets(line, 1024, f);\n while(fgets(line, 1024, f)){\n char* tmp = strdup(line);\n double y_tmp = atof(getfield(tmp, 2));\n double x_tmp = atof(getfield(tmp, 1));\n if(l < max_lines){\n x[l] = x_tmp;\n y[l] = y_tmp;\n }\n l++;\n\n free(tmp);\n }\n}\n\n\nint\nmain (void)\n{\n read_csv(\"secret_fun.csv\", max_lines);\n\n // printf (\"#m=0,S=17\\n\");\n //\n // for (i = 0; i < max_lines; i++)\n // {\n // // x[i] = i + 0.5 * sin (i);\n // // y[i] = i + cos (i * i);\n // printf (\"%f %f \\n\", x[i], y[i]);\n // }\n\n // printf (\"#m=1,S=0\\n\");\n //\n {\n gsl_interp_accel *acc\n = gsl_interp_accel_alloc ();\n gsl_spline *spline\n = gsl_spline_alloc (gsl_interp_cspline, 30);\n\n gsl_spline_init (spline, x, y, 30);\n\n printf(\"x,y\\n\" );\n for (xi = x[0]; xi < x[29]; xi += 0.01)\n {\n printf(\"%g, \", xi);\n yi = gsl_spline_eval (spline, xi, acc);\n printf (\"%g\\n\", yi);\n }\n gsl_spline_free (spline);\n gsl_interp_accel_free (acc);\n }\n return 0;\n}\n", "meta": {"hexsha": "e18bc7ffab8b8790362d71dfaf013a342a0072d0", "size": 1561, "ext": "c", "lang": "C", "max_stars_repo_path": "lab5/interp.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": "lab5/interp.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": "lab5/interp.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": 19.2716049383, "max_line_length": 50, "alphanum_fraction": 0.5086483024, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.578110674781535}} {"text": "/* specfunc/bessel_Ynu.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \"gsl_sf_bessel.h\"\n\n#include \"error.h\"\n\n#include \"bessel.h\"\n#include \"bessel_olver.h\"\n#include \"bessel_temme.h\"\n\n/* Perform forward recurrence for Y_nu(x) and Y'_nu(x)\n *\n * Y_{nu+1} = nu/x Y_nu - Y'_nu\n * Y'_{nu+1} = -(nu+1)/x Y_{nu+1} + Y_nu\n */\n#if 0\nstatic\nint\nbessel_Y_recur(const double nu_min, const double x, const int kmax,\n const double Y_start, const double Yp_start,\n\t double * Y_end, double * Yp_end)\n{\n double x_inv = 1.0/x;\n double nu = nu_min;\n double Y_nu = Y_start;\n double Yp_nu = Yp_start;\n int k;\n\n for(k=1; k<=kmax; k++) {\n double nuox = nu*x_inv;\n double Y_nu_save = Y_nu;\n Y_nu = -Yp_nu + nuox * Y_nu;\n Yp_nu = Y_nu_save - (nuox+x_inv) * Y_nu;\n nu += 1.0;\n }\n *Y_end = Y_nu;\n *Yp_end = Yp_nu;\n return GSL_SUCCESS;\n}\n#endif\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_bessel_Ynu_e(double nu, double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x <= 0.0 || nu < 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(nu > 50.0) {\n return gsl_sf_bessel_Ynu_asymp_Olver_e(nu, x, result);\n }\n else {\n /* -1/2 <= mu <= 1/2 */\n int N = (int)(nu + 0.5);\n double mu = nu - N;\n\n gsl_sf_result Y_mu, Y_mup1;\n int stat_mu;\n double Ynm1;\n double Yn;\n double Ynp1;\n int n;\n\n if(x < 2.0) {\n /* Determine Ymu, Ymup1 directly. This is really\n * an optimization since this case could as well\n * be handled by a call to gsl_sf_bessel_JY_mu_restricted(),\n * as below.\n */\n stat_mu = gsl_sf_bessel_Y_temme(mu, x, &Y_mu, &Y_mup1);\n }\n else {\n /* Determine Ymu, Ymup1 and Jmu, Jmup1.\n */\n gsl_sf_result J_mu, J_mup1;\n stat_mu = gsl_sf_bessel_JY_mu_restricted(mu, x, &J_mu, &J_mup1, &Y_mu, &Y_mup1);\n }\n\n /* Forward recursion to get Ynu, Ynup1.\n */\n Ynm1 = Y_mu.val;\n Yn = Y_mup1.val;\n for(n=1; n<=N; n++) {\n Ynp1 = 2.0*(mu+n)/x * Yn - Ynm1;\n Ynm1 = Yn;\n Yn = Ynp1;\n }\n\n result->val = Ynm1; /* Y_nu */\n result->err = (N + 1.0) * fabs(Ynm1) * (fabs(Y_mu.err/Y_mu.val) + fabs(Y_mup1.err/Y_mup1.val));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(Ynm1);\n\n return stat_mu;\n }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_Ynu(const double nu, const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_Ynu_e(nu, x, &result));\n}\n", "meta": {"hexsha": "6453ea1ca3a89f16e85f5ad355d85365a0de3003", "size": 3365, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_Ynu.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_Ynu.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_Ynu.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.4924242424, "max_line_length": 100, "alphanum_fraction": 0.6109955423, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5781106698785633}} {"text": "#include \n#include \n#include \n#define COMPEARTH_PRIVATE_DET3X3 1\n#include \"compearth.h\"\n/*\n#ifdef COMPEARTH_USE_MKL\n#include \n#else\n#include \n#endif\n*/\n\n//static double det3x3ColumnMajor(const double *__restrict__ A);\n\n/*!\n * @brief Ensure that U is a rotation matrix with det(U) = 1.\n *\n * @param[in] n Number of rotation matrices.\n * @param[in] Uin Rotation matrices to check. This is an array of dimension\n * [3 x 3 x n] where each [3 x 3] matrix is in column major\n * format.\n * @param[in] Uout Rotation matrices with determinants all positive. This\n * is an array of dimension [3 x 3 x n] where each [3 x 3]\n * matrix is in column major format.\n * \n * @result 0 indicates success.\n *\n * @author Carl Tape and translated to C by Ben Baker\n *\n * @copyright MIT\n *\n */\nint compearth_Udetcheck(const int n,\n const double *__restrict__ Uin,\n double *__restrict__ Uout)\n{\n double det;\n int i, imt;\n // Copy Uin to Uout\n memcpy(Uout, Uin, 9*(size_t) n*sizeof(double));\n //cblas_dcopy(9*n, Uin, 1, Uout, 1);\n // Fix\n for (imt=0; imt\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nclass CochlearModel_1D{\n\nprivate:\n int N;\n double Lb;\n double L;\n double W;\n double H;\n double rho;\n double dx;\n vector x;\n\n vector ch_damp;\n\n vector k1;\n double m1;\n vector c1;\n vector k2;\n double m2;\n vector c2;\n vector k3;\n vector c3;\n vector k4;\n vector c4;\n\n vector k1k3;\n vector c1c3;\n vector k2k3;\n vector c2c3;\n\n double g;\n double b;\n vector gamma;\n\n double dt;\n double beta;\n\n vector Gohc(vector uc);\n vector dGohc(vector uc, vector vc);\n void get_g(vector vb, vector ub, vector vt, vector ut, vector& gb, vector& gt);\n\npublic:\n CochlearModel_1D(int num_segment, vector gamma_given)\n {\n N = num_segment;\n Lb = 3.5;\n L = 0.1;\n W = 0.1;\n H = 0.1;\n rho = 1.0;\n dx = Lb/N;\n \n m1 = 3e-3;\n m2 = 0.5e-3;\n for (int ii = 0; ii < N; ii++){\n x.push_back(dx * ii);\n// ch_damp.push_back(2.8 * exp(-0.1*x[ii]));\n ch_damp.push_back(1.0);\n\n k1.push_back(2.2e8 * exp(-3 * x[ii]));\n c1.push_back(6 + 670 * exp(-1.5 * x[ii]) * ch_damp[ii]);\n k2.push_back(1.4e6 * exp(-3.3 * x[ii]));\n c2.push_back(4.4 * exp(-1.65 * x[ii]) * ch_damp[ii]);\n k3.push_back(2.0e6 * exp(-3 * x[ii]));\n c3.push_back(0.8 * exp(-0.6 * x[ii]) * ch_damp[ii]);\n k4.push_back(1.15e8 * exp(-3 * x[ii]));\n c4.push_back(440.0 * exp(-1.5 * x[ii]) * ch_damp[ii]);\n\n k1k3.push_back(k1[ii] + k3[ii]);\n c1c3.push_back(c1[ii] + c3[ii]);\n k2k3.push_back(k2[ii] + k3[ii]);\n c2c3.push_back(c2[ii] + c3[ii]);\n gamma.push_back(gamma_given[ii]);\n }\n g = 1;\n b = 0.4;\n dt = 10e-6;\n beta = 50e-7;\n }\n\n void solve_time_domain(vector f, vector >& mat_vb, vector >& mat_ub, vector >& mat_p);\n};", "meta": {"hexsha": "d43435ded6ac56cb12ccac80da4415117b2c2f6e", "size": 2346, "ext": "h", "lang": "C", "max_stars_repo_path": "cpp/fft/CochlearModel_1D_fft.h", "max_stars_repo_name": "y-muraka/Human-Cochlear-Model", "max_stars_repo_head_hexsha": "8f430f461e633b18d36134644baa7631b3853f26", "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": "cpp/fft/CochlearModel_1D_fft.h", "max_issues_repo_name": "y-muraka/Human-Cochlear-Model", "max_issues_repo_head_hexsha": "8f430f461e633b18d36134644baa7631b3853f26", "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": "cpp/fft/CochlearModel_1D_fft.h", "max_forks_repo_name": "y-muraka/Human-Cochlear-Model", "max_forks_repo_head_hexsha": "8f430f461e633b18d36134644baa7631b3853f26", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T12:10:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T12:10:18.000Z", "avg_line_length": 25.5, "max_line_length": 142, "alphanum_fraction": 0.5349531117, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5780818665827367}} {"text": "/*\n\tSimbicon 1.5 Controller Editor Framework, \n\tCopyright 2009 Stelian Coros, Philippe Beaudoin and Michiel van de Panne.\n\tAll rights reserved. Web: www.cs.ubc.ca/~van/simbicon_cef\n\n\tThis file is part of the Simbicon 1.5 Controller Editor Framework.\n\n\tSimbicon 1.5 Controller Editor Framework is free software: you can \n\tredistribute it and/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tSimbicon 1.5 Controller Editor Framework is distributed in the hope \n\tthat it will be useful, but WITHOUT ANY WARRANTY; without even the \n\timplied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \n\tSee the GNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with Simbicon 1.5 Controller Editor Framework. \n\tIf not, see .\n*/\n\n#pragma once\n\n#include \n#include \n#include \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/*====================================================================================================================================================================*\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 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 virtual ~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=0\n /// @param n Specifies the number of coumns of the matrix A. n>=0\n /// @param alpha Real scalar.\n /// @param x Pointer to real vector x.\n /// @param incx Increment of the vector x. x!=0\n /// @param y Pointer to real vector y.\n /// @param incy Increment of the vector y. y!=0\n /// @param A Pointer to real m-by-n matrix A.\n /// @param ldA Column length of matrix A. ldA>=m.\n /// @ingroup BLAS\n\n template \n int GER(int_t m, int_t n, real_t alpha, real_t *x, int_t incx, real_t *y, int_t incy, real_t *A, int_t ldA)\n {\n const real_t zero(0.0);\n int_t i,j,kx,jy,ix;\n if(m<0)\n return -1;\n else if(n<0)\n return -2;\n else if(incx==0)\n return -5;\n else if(incy==0)\n return -7;\n else if(ldA0)?0:(1-n)*incy;\n kx=(incx>0)?0:(1-m)*incx;\n \n if(incx==1)\n {\n for(j=0;j\n\n template <> int GER(int_t m, int_t n, float alpha, float *x, int_t incx, float *y, int_t incy, float *A, int_t ldA)\n {\n if(m<0)\n return -1;\n else if(n<0)\n return -2;\n else if(incx==0)\n return -5;\n else if(incy==0)\n return -7;\n else if(ldA int GER(int_t m, int_t n, double alpha, double *x, int_t incx, double *y, int_t incy, double *A, int_t ldA)\n {\n if(m<0)\n return -1;\n else if(n<0)\n return -2;\n else if(incx==0)\n return -5;\n else if(incy==0)\n return -7;\n else if(ldA\n#include \n\n#include \"csm_all.h\"\n\nint minmax(int from, int to, int x) {\n\treturn GSL_MAX(GSL_MIN(x,to),from);\n}\n\nvoid possible_interval(\n\tconst double *p_i_w, LDP ld, \n\tdouble max_angular_correction_deg, double max_linear_correction, int*from, int*to, int*start_cell) \n{\n\tdouble angle_res = (ld->max_theta-ld->min_theta)/ld->nrays;\n\n\t/* Delta for the angle */\n\tdouble delta = fabs(deg2rad(max_angular_correction_deg)) +\n\t fabs(atan(max_linear_correction/norm_d(p_i_w)));\n\n\t/* Dimension of the cell range */\n\tint range = (int) ceil(delta/angle_res);\n\n\t/* To be turned into an interval of cells */\n\tdouble start_theta = atan2(p_i_w[1], p_i_w[0]);\n\t\n\t/* Make sure that start_theta is in the interval [min_theta,max_theta]. \n\t For example, -1 is not in [0, 2pi] */\n\tif(start_thetamin_theta) start_theta += 2*M_PI;\n\tif(start_theta>ld->max_theta) start_theta -= 2*M_PI;\n\t\n\t*start_cell = (int)\n\t\t((start_theta - ld->min_theta) / (ld->max_theta-ld->min_theta) * ld->nrays);\n\n\t*from = minmax(0,ld->nrays-1, *start_cell-range);\n\t*to = minmax(0,ld->nrays-1, *start_cell+range);\n\n\tif(0)\n\tprintf(\"from: %d to: %d delta: %f start_theta: %f min/max theta: [%f,%f] range: %d start_cell: %d\\n\",\n\t\t*from, *to,\n\t\tdelta,start_theta,ld->min_theta,ld->max_theta, range, *start_cell);\n}\n\n\n\n\nint distance_counter = 0;\n\ndouble distance_squared_d(const double a[2], const double b[2]) {\n\tdistance_counter++;\n\tdouble x = a[0]-b[0];\n\tdouble y = a[1]-b[1];\n\treturn x*x + y*y;\n}\n\ndouble distance_d(const double a[2], const double b[2]) {\n\treturn sqrt(distance_squared_d(a,b));\n}\n\n\nint is_nan(double v) {\n\treturn v == v ? 0 : 1;\n}\n\nint any_nan(const double *d, int n) {\n\tint i; for(i=0;i +M_PI) res[2] -= 2*M_PI;\n\twhile(res[2] < -M_PI) res[2] += 2*M_PI;\n}\n\ndouble square(double x) {\n\treturn x*x;\n}\n\ndouble angleDiff(double a, double b) {\n\tdouble t = a - b;\n\twhile(t<-M_PI) t+= 2*M_PI;\n\twhile(t>M_PI) t-= 2*M_PI;\n\treturn t;\n}\n\nvoid projection_on_line_d(const double a[2],\n\tconst double b[2],\n\tconst double p[2],\n\tdouble res[2], double *distance)\n{\n\tdouble t0 = a[0]-b[0];\n\tdouble t1 = a[1]-b[1];\n\tdouble one_on_r = 1 / sqrt(t0*t0+t1*t1);\n\t/* normal */\n\tdouble nx = t1 * one_on_r ;\n\tdouble ny = -t0 * one_on_r ;\n\tdouble c= nx, s = ny; \n\tdouble rho = c*a[0]+s*a[1];\n\n\tres[0] = c*rho + s*s*p[0] - c*s*p[1] ;\n\tres[1] = s*rho - c*s*p[0] + c*c*p[1] ;\t\n\t\n\tif(distance)\n\t\t*distance = fabs(rho-(c*p[0]+s*p[1]));\n}\n\nvoid projection_on_segment_d(\n\tconst double a[2],\n\tconst double b[2],\n\tconst double x[2],\n\tdouble proj[2]) \n{\n\tprojection_on_line_d(a,b,x,proj,0);\n\tif ((proj[0]-a[0])*(proj[0]-b[0]) +\n\t (proj[1]-a[1])*(proj[1]-b[1]) < 0 ) {\n\t\t/* the projection is inside the segment */\n\t} else \n\t\tif(distance_squared_d(a,x) < distance_squared_d(b,x)) \n\t\t\tcopy_d(a,2,proj);\n\t\telse\n\t\t\tcopy_d(b,2,proj);\n}\n\n\ndouble dist_to_segment_squared_d(const double a[2], const double b[2], const double x[2]) {\n\tdouble projection[2];\n\tprojection_on_segment_d(a, b, x, projection);\n\tdouble distance_sq_d = distance_squared_d(projection, x);\n\treturn distance_sq_d;\n}\n\ndouble dist_to_segment_d(const double a[2], const double b[2], const double x[2]) {\n\tdouble proj[2]; double distance;\n\tprojection_on_line_d(a,b,x,proj, &distance);\n\tif ((proj[0]-a[0])*(proj[0]-b[0]) +\n\t (proj[1]-a[1])*(proj[1]-b[1]) < 0 ) {\n\t\t/* the projection is inside the segment */\n\t\treturn distance;\n\t} else \n\t\treturn sqrt(GSL_MIN( distance_squared_d(a,x), distance_squared_d(b,x)));\n}\n\nint count_equal(const int*v, int n, int value) {\n\tint num = 0, i;\n\tfor(i=0;i=2*M_PI) t-=2*M_PI;\n\treturn t;\n}\n\ndouble dot_d(const double p[2], const double q[2]);\n\n\ndouble dot_d(const double p[2], const double q[2]) {\n\treturn p[0]*q[0] + p[1]*q[1];\n}\n\n/* Executes ray tracing for a segment. p0 and p1 are the segments extrema, eye is the position\nof the eye, and direction is the direction of the ray coming out of the eye. Returns true\nif the ray intersects the segment, and in that case *range contains the length of the ray. */\nint segment_ray_tracing(const double p0[2], const double p1[2], const double eye[2], double direction, double*range) {\n\t\n\t*range = NAN;\n\t\n\t// p0 - p1\n\tdouble arrow[2] = {p1[0]-p0[0],p1[1]-p0[1]};\n\t// Normal to segment line\n\tdouble S[2] = { -arrow[1], arrow[0]};\n\t// Viewing direction\n\tdouble N[2] = { cos(direction), sin(direction)};\n\t// If S*N = 0 then they cannot cross\n\tdouble S_dot_N = dot_d(S,N);\n\tif( S_dot_N == 0) return 0;\n\t// Rho of the line in polar coordinates (multiplied by |S|)\n\tdouble line_rho = dot_d(p0,S);\n\t// Rho of the eye (multiplied by |S|)\n\tdouble eye_rho = dot_d(eye,S);\n\t// Black magic\n\tdouble dist = (line_rho - eye_rho) / S_dot_N;\n\tif(dist<=0) return 0;\n\t\n\t// Now we check whether the crossing point\n\t// with the line lies within the segment\n\t\n\t// Crossing point\n\tdouble crossing[2] = {eye[0] + N[0]*dist, eye[1]+N[1]*dist};\n\t// Half of the segment\n\tdouble midpoint[2] = { 0.5*(p1[0]+p0[0]),0.5*(p1[1]+p0[1])};\n\t\n\tdouble seg_size = distance_d(p0, p1);\n\tdouble dist_to_midpoint = distance_d(crossing, midpoint);\n\t\n\tif(dist_to_midpoint > seg_size/2 )\n\t\treturn 0;\n\t\n\t*range = dist;\n\treturn 1;\n}\n\ndouble segment_alpha(const double p0[2], const double p1[2]) {\n\tdouble arrow[2] = {p1[0]-p0[0],p1[1]-p0[1]};\n\t// Normal to segment line\n\tdouble S[2] = { -arrow[1], arrow[0]};\n\treturn atan2(S[1], S[0]);\n}\n\n\nstatic char tmp_buf[1024];\nconst char* friendly_pose(const double*pose) {\n\tsprintf(tmp_buf, \"(%4.2f mm, %4.2f mm, %4.4f deg)\",\n\t\t1000*pose[0],1000*pose[1],rad2deg(pose[2]));\n\treturn tmp_buf;\n}\n\n\ndouble max_in_array(const double*v, int n) {\n\tassert(n>0);\n\tdouble m = v[0];\n\tint i; \n\tfor(i=0;im) m = v[i];\n\treturn m;\n}\n", "meta": {"hexsha": "275aabf2e00d4e4951cd4d13855f07b72f0ae3b9", "size": 7099, "ext": "c", "lang": "C", "max_stars_repo_path": "src/csm/sm/csm/math_utils.c", "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "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/csm/sm/csm/math_utils.c", "max_issues_repo_name": "alecone/ROS_project", "max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "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/csm/sm/csm/math_utils.c", "max_forks_repo_name": "alecone/ROS_project", "max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2633451957, "max_line_length": 118, "alphanum_fraction": 0.6403718834, "num_tokens": 2462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5780154334338203}} {"text": "/**\n * Copyright 2016 José Manuel Abuín Mosquera \n * \n * This file is part of Matrix Market Suite.\n *\n * Matrix Market Suite is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Matrix Market Suite is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Matrix Market Suite. If not, see .\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"LUDecomposition.h\"\n\nvoid usageLUDecomposition(){\n\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"Usage: MM-Suite LUDecomposition [options] \\n\");\n\tfprintf(stderr, \"\\nInput/output options:\\n\\n\");\n\tfprintf(stderr, \" -o STR Output file name. Default: stdout\\n\");\n\tfprintf(stderr, \" -r Input format is row per line. Default: False\\n\");\n\tfprintf(stderr, \"\\n\");\n\n}\n\nint LUDecomposition(int argc, char *argv[]) {\n\n\tint \t\t\tret_code = 1;\n\tint \t\t\toption;\n\n\tunsigned long \t\t*II;\n\t\n\tunsigned long \t\t*J;\n\tdouble \t\t\t*values;\n\t\n\tunsigned long \t\tM;\n\tunsigned long \t\tN;\n\tunsigned long long \tnz;\n\t\n\tint\t\t\t_M;\n\tint\t\t\t_N;\n\t\n\t\n\tchar\t\t\t*outputFileName = NULL;\n\t\n\tchar\t\t\t*inputMatrixFile = NULL;\n\t\n\tint\t\t\tinputFormatRow = 0;\n\t\n\t\n\twhile ((option = getopt(argc, argv,\"ro:\")) >= 0) {\n\t\tswitch (option) {\n\t\t\tcase 'o' : \n\t\t\t\t//free(outputFileName);\n\t\t\t\t\n\t\t\t\toutputFileName = (char *) malloc(sizeof(char)*strlen(optarg)+1);\n\t\t\t\tstrcpy(outputFileName,optarg);\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'r':\n\t\t\t\tinputFormatRow = 1;\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tdefault: break;\n\t\t}\n\t\n\t}\n\t\n\tif ((optind + 1 > argc) || (optind + 2 <= argc)) {\n\t\tusageLUDecomposition();\n\t\treturn 0;\n\t}\n\t\n\tif(outputFileName == NULL) {\n\t\toutputFileName = (char *) malloc(sizeof(char)*7);\n\t\tsprintf(outputFileName,\"stdout\");\n\t}\n\t\n\tinputMatrixFile = (char *)malloc(sizeof(char)*strlen(argv[optind])+1);\n\t\n\tstrcpy(inputMatrixFile,argv[optind]);\n\n\t\n\t//Read matrix\n\tif(inputFormatRow){\n\t\n\t\tif(!readDenseCoordinateMatrixRowLine(inputMatrixFile,&II,&J,&values,&M,&N,&nz)){\n\t\t\tfprintf(stderr, \"[%s] Can not read Matrix\\n\",__func__);\n\t\t\treturn 0;\n\t\t}\n\t\n\t}\n\telse {\n\t\tif(!readDenseCoordinateMatrix(inputMatrixFile,&II,&J,&values,&M,&N,&nz)){\n\t\t\tfprintf(stderr, \"[%s] Can not read Matrix\\n\",__func__);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t\n\t_M = (int) M;\n\t_N = (int) N;\n\t\n\tint ipiv[_M];\n\t\n\t/*\n\tlapack_int LAPACKE_dgetrf( int matrix_layout, lapack_int m, lapack_int n,\n double* a, lapack_int lda, lapack_int* ipiv );\n\t*/\n\t\n ret_code = LAPACKE_dgetrf(LAPACK_ROW_MAJOR,_M,_N, values,_N, ipiv);\n\t\n\tif(inputFormatRow){\n\t\twriteLUCoordinateMatrixRowLine(outputFileName, values,M,N,nz, ipiv);\n\t}\n\telse{\n\t\twriteLUCoordinateMatrix(outputFileName, values,M,N,nz, ipiv);\n\t}\n\t\n\t\n\t//writeDenseCoordinateMatrix(\"stdout\",values,M,N,nz);\n\tif(!ret_code)\n\t\treturn 1;\n\telse\n\t\treturn 0;\n\t\n\n}\n", "meta": {"hexsha": "b5ce4d4327e97835f94d0f300fcbe0171bc0f2f2", "size": 3262, "ext": "c", "lang": "C", "max_stars_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/LUDecomposition.c", "max_stars_repo_name": "vkeller/math-454", "max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z", "max_issues_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/LUDecomposition.c", "max_issues_repo_name": "vkeller/math-454", "max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/LUDecomposition.c", "max_forks_repo_name": "vkeller/math-454", "max_forks_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8111888112, "max_line_length": 88, "alphanum_fraction": 0.6557326793, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.5779468789068635}} {"text": "/*\n * Tema 2 ASC\n * 2020 Spring\n */\n#include \n#include \"utils.h\"\n\n#define IDX2L(i, j, N) (((i) * (N)) + (j))\n\n/* \n * Add your BLAS implementation here\n */\n\ndouble* my_solver(int N, double *A, double *B) {\n\tint i, j;\n\tdouble alpha = 1.0;\n\t/* Calculate the final result in C matrix */\n\tdouble *C = calloc(N * N, sizeof(double));\n\tif (C == NULL) {\n\t\treturn NULL;\n\t}\n\t/* Calculate the B*At part in D */\n\tdouble *D = calloc(N * N, sizeof(double));\n\tif (D == NULL) {\n\t\treturn NULL;\n\t}\n\t/* Calculate the A * A in A_square */\n\tdouble *A_square = calloc(N * N, sizeof(double));\n\tif (A_square == NULL) {\n\t\treturn NULL;\n\t}\n\t\n\t/* Copy B matrix in D matrix */\n\tfor (i = 0; i != N; i++) {\n\t\tfor (j = 0; j != N; j++) {\n\t\t\tD[IDX2L(i, j, N)] = B[IDX2L(i, j, N)];\n\t\t}\n\t}\n\t/* Copy A matrix in A_square matrix */\n\tfor (i = 0; i != N; i++) {\n\t\tfor (j = 0; j != N; j++) {\n\t\t\tif ( i <= j) {\n\t\t\t\tA_square[IDX2L(i, j, N)] = A[IDX2L(i, j, N)];\n\t\t\t}\n\t\t}\n\t}\n\t/* \n\t * Multiply matrixes B * At, where At is A transposed\n\t * The result is saved in D matrix\n\t */\n\tcblas_dtrmm(CblasRowMajor, CblasRight, CblasUpper, CblasTrans,\n\t\t\t\tCblasNonUnit, N, N, alpha, A, N, D, N);\n\t/* \n\t * Multiply matrixes A * A, saved result in A_square\n\t * Matrix A_square is a triangular matrix\n\t */\n\tcblas_dtrmm(CblasRowMajor, CblasRight, CblasUpper, CblasNoTrans,\n\t\t\t CblasNonUnit, N, N, alpha, A, N, A_square, N);\n\n\t/* \n\t * Multiply matrixes A_square * B, where A_square = A * A\n\t * The result is saved in B matrix\n\t */\n\tcblas_dtrmm(CblasRowMajor, CblasLeft, CblasUpper, CblasNoTrans,\n\t\t\t\tCblasNonUnit, N, N, alpha, A_square, N, B, N);\n\n\t/* Add matrixes D and B, save the result in C matrix */\n\tfor (i = 0; i != N; i++) {\n\t\tfor (j = 0; j != N; j++) {\n\t\t\tC[IDX2L(i, j, N)] = D[IDX2L(i, j, N)] + B[IDX2L(i, j, N)];\n\t\t}\n\t}\n\t/* Free memory from D and A_square */\n\tfree(D);\n\tfree(A_square);\n\tprintf(\"BLAS SOLVER\\n\");\n\treturn C;\n}\n", "meta": {"hexsha": "5f9fe694ad35a52e1bb0854923524020964775c6", "size": 1886, "ext": "c", "lang": "C", "max_stars_repo_path": "solver_blas.c", "max_stars_repo_name": "vladutmargineanu/Code-Optimization", "max_stars_repo_head_hexsha": "169787108fd241de041e5846d4f33f9773e8ba9a", "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": "solver_blas.c", "max_issues_repo_name": "vladutmargineanu/Code-Optimization", "max_issues_repo_head_hexsha": "169787108fd241de041e5846d4f33f9773e8ba9a", "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": "solver_blas.c", "max_forks_repo_name": "vladutmargineanu/Code-Optimization", "max_forks_repo_head_hexsha": "169787108fd241de041e5846d4f33f9773e8ba9a", "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.8734177215, "max_line_length": 65, "alphanum_fraction": 0.5768822906, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.577923966498471}} {"text": "/* bccgls.c\n $Revision: 281 $ $Date: 2006-12-13 09:03:53 -0800 (Wed, 13 Dec 2006) $\n\n ----------------------------------------------------------------------\n This file is part of BCLS (Bound-Constrained Least Squares).\n\n Copyright (C) 2006 Michael P. Friedlander, Department of Computer\n Science, University of British Columbia, Canada. All rights\n reserved. E-mail: .\n\n BCLS is free software; you can redistribute it and/or modify it\n under the terms of the GNU Lesser General Public License as\n published by the Free Software Foundation; either version 2.1 of the\n License, or (at your option) any later version.\n\n BCLS is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General\n Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with BCLS; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n ----------------------------------------------------------------------\n\n*/\n/*!\n \\file\n This file implements conjugate gradients for the normal equations\n (CGLS).\n*/\n\n#include \n#include \n#include \n#include \n\n#include \"bcls.h\"\n#include \"bclib.h\"\n#include \"bccgls.h\"\n\n/*!\n\n \\brief Mat-vec routine called by CGLS.\n \n CGLS call this routine, which in turn calls bcls_aprod:\n - If mode == BCLS_PROD_A, y = A dxFree.\n - else if mode == BCLS_PROD_At, dxFree = A'y.\n\n This routine is declared \"static\" so that it won't be confused with\n the user's own Aprod routine.\n \n \\param[in,out] ls BCLS solver context.\n \\param[in] mode Specifies if the product with A or A' is required.\n \\param[in] m Number of rows in A.\n \\param[in] nFree Length of dxFree (and ix which is recovered via ls).\n \\param[in,out] dxFree RHS or LHS (depending on the mode).\n \\param[in,out] y RHS or LHS (depending on the mode).\n\n*/\nstatic void\naprod_free( BCLS *ls, const int mode, const int m, const int nFree,\n\t double dxFree[], double y[] )\n{\n int *ix = ls->ix;\n double *dx = ls->dx; // Used as workspace.\n\n assert( mode == BCLS_PROD_A || mode == BCLS_PROD_At );\n\n if (mode == BCLS_PROD_A) {\n\n bcls_scatter( nFree, ix, dxFree, dx ); // dx(ix) = dxFree.\n\tbcls_aprod( ls, BCLS_PROD_A, nFree, ix, dx, y );// y = A dx.\n\n } else {\n\t\n\tbcls_aprod( ls, BCLS_PROD_At, nFree, ix, dx, y );// dx = A' y.\n bcls_gather( nFree, ix, dx, dxFree ); // dxFree = dx(ix);\n }\n\n return;\n}\n\n/*!\n\n \\brief CG for least squares.\n\n This routine implements CG for solving the symmetric linear system\n\n ( N'N + damp I ) x = N'r + c\n\n where N is an m-by-n submatrix of the general matrix A. This\n implementation is adapted from Hestenes and Stiefel's CG for\n least-squares method to accomodate the damping term and the\n additional vector on the RHS. (See, eg, Bjork, Numerical Methods\n for Least-Squares Problems, 1996, p. 289.)\n\n \\param[in,out] ls BCLS solver context.\n \\param[in] m No. of rows in A.\n \\param[in] n No. of cols in A.\n \\param[in] kmax Maximum no. of CG iterations.\n \\param[in] tol Required optimality tolerance:\n - norm( A'A x - A'b ) / norm(A'b)\n \\param[in] damp Regularization term on x.\n \\param[in] c Additional vector (set NULL if not present).\n \\param[out] x Solution vector.\n \\param[in,out] r On entry, r must be defined.\\n\n On exit, r is the residual.\n \\param[in,out] s Work vector.\n \\param[in,out] p Work vector.\n \\param[out] itns No. of CG iterations.\n \\param[out] opt Relative residual (see tol, above).\n \\param[in] nout File for log output (set NULL if not needed).\n\n \\returns\n - 0: Required accuracy was achieved.\n - 1: The iteration limit (kmax) was reached.\n - 2: N'N appears to be singular.\n \n \\todo Update normx rather than recompute at each iteration.\n\n*/\nstatic int\nbcls_cgls( BCLS *ls, int m, int n, int kmax, double tol, double damp,\n\t double c[], double x[], double r[], double s[], double p[],\n\t int *itns, double *opt, FILE *nout )\n{ \n int\n k = 0, info = 0, converged = 0, unstable = 0;\n double\n xmax = 0.0, resNE, Arnorm, Arnorm0,\n normp, norms, normx = 0.0, alpha, beta,\n gamma, gamma1, delta;\n const int\n damped = damp > 0.0;\n const double\n eps = DBL_EPSILON;\n\n // Initialize.\n bcls_dload( n, 0.0, x, 1 ); // x = 0\n aprod_free( ls, BCLS_PROD_At, m, n, s, r ); // s = A'r\n if (c) \n cblas_daxpy( n, 1.0, c, 1, s, 1 ); // s += c\n cblas_dcopy( n, s, 1, p, 1 ); // p = s\n Arnorm0 = cblas_dnrm2( n, s, 1 );\n gamma = Arnorm0 * Arnorm0;\n\n if (nout) {\n fprintf(nout,\"\\n CGLS:\\n\");\n fprintf(nout,\" Rows............. %8d\\t\", m);\n fprintf(nout,\" Columns.......... %8d\\n\", n);\n fprintf(nout,\" Optimality tol... %8.1e\\t\", tol);\n fprintf(nout,\" Iteration limit.. %8d\\n\", kmax);\n fprintf(nout,\" Damp............. %8.1e\\t\", damp);\n fprintf(nout,\" Linear term...... %8s\\n\",\n (c) ? \"yes\" : \"no\" );\n fprintf(nout, \"\\n\\n%5s %17s %17s %9s %10s\\n\",\n \"k\", \"x(1)\",\"x(n)\",\"normx\",\"resNE\");\n fprintf(nout, \"%5d %17.10e %17.10e %9.2e %10.2e\\n\",\n k, x[0], x[n-1], normx, 1.0 );\n }\n // -----------------------------------------------------------------\n // Main loop.\n // -----------------------------------------------------------------\n while ( k < kmax && !converged && !unstable ) {\n\n k++;\n\n aprod_free( ls, BCLS_PROD_A, m, n, p, s ); // s = A p\n\n norms = cblas_dnrm2( m, s, 1 );\n delta = norms * norms;\n if (damped) {\n normp = cblas_dnrm2( n, p, 1 );\n delta += damp * normp * normp;\n }\n if (delta <= eps)\n delta = eps;\n\n alpha = gamma / delta;\n\n cblas_daxpy( n, alpha, p, 1, x, 1 ); // x = x + alpha*p\n cblas_daxpy( m, -alpha, s, 1, r, 1 ); // r = r - alpha*s\n aprod_free( ls, BCLS_PROD_At, m, n, s, r ); // s = A'r\n if (damped)\n cblas_daxpy( n, -damp, x, 1, s, 1 ); // s += - damp*x\n if (c)\n cblas_daxpy( n, 1.0, c, 1, s, 1 ); // s += c\n\n Arnorm = cblas_dnrm2( n, s, 1 );\n gamma1 = gamma;\n gamma = Arnorm * Arnorm;\n beta = gamma / gamma1;\n \n cblas_dscal( n, beta, p, 1 ); // p = beta*p\n cblas_daxpy( n, 1.0, s, 1, p, 1); // p += s \n\n // Check convergence.\n normx = cblas_dnrm2( n, x, 1 );\n xmax = fmax( xmax, normx );\n converged = Arnorm <= Arnorm0 * tol;\n unstable = normx * tol >= 1.0;\n\n // Output.\n resNE = Arnorm / Arnorm0;\n if (nout)\n fprintf(nout, \"%5d %17.10e %17.10e %9.2e %10.2e\\n\",\n k, x[0], x[n-1], normx, resNE );\n \n } // while\n\n double shrink = normx / xmax;\n if (converged)\n info = 0;\n else if (k >= kmax)\n info = 1;\n else if (shrink <= sqrt(tol))\n info = 2;\n\n // Output.\n if (nout) fprintf(nout,\"\\n\");\n *itns = k;\n *opt = resNE;\n return info;\n}\n\n/*!\n\n \\brief Compute a Newton step using CGLS.\n\n See the description of #bcls_newton_step.\n\n \\param[in,out] ls BCLS solver context\n \\param[in] m No. of rows in A.\n \\param[in] nFree No. of free columns, i.e., no. of cols in N.\n \\param[in] ix Index of vars for which a Newton step is computed.\n \\param[in] damp Regularization term on dxFree.\n \\param[in] itnLim Maximum no. of CG iterations.\n \\param[in] tol Required optimality tolerance:\n - norm( N'N x - N'b ) / norm(N'b).\n \\param[in] dxFree Newton direction in the free vars (len = nFree).\n \\param[in] x Current iterate.\n \\param[in] c Linear term. (Set to NULL if not present.)\n \\param[in,out] r On entry, r is current residual: r = b - Ax. \\n\n Will be used as workspace.\n \\param[in] itns No. of CG iterations.\n \\param[in] opt Relative residual (see tol, above).\n\n \\return The termination flag returned by #bcls_cgls.\n\n*/\nint\nbcls_newton_step_cgls( BCLS *ls, int m, int nFree, int ix[], double damp,\n int itnLim, double tol, double dxFree[], double x[],\n double c[], double r[], int *itns, double *opt )\n{\n int\n j;\n double\n *u;\n const double\n damp2 = damp*damp;\n\n if (c) {\n u = ls->wrk_u;\n bcls_gather( nFree, ix, c, u ); // u = c(ix).\n cblas_dscal( nFree, -1.0, u, 1 ); // u = - c(ix).\n if ( damp > 0.0 ) // u += - damp2 x(ix).\n for (j = 0; j < nFree; j++)\n u[j] -= damp2 * x[ix[j]];\n }\n else\n u = NULL;\n\n return bcls_cgls( ls, m, nFree, itnLim, tol, damp2,\n u, dxFree, r, ls->wrk_v, ls->wrk_w,\n itns, opt, ls->minor_file );\n}\n", "meta": {"hexsha": "31624219b8b8f3ba347d6a67c50d9d0f22e6244e", "size": 9407, "ext": "c", "lang": "C", "max_stars_repo_path": "bcls-0.1/src/bccgls.c", "max_stars_repo_name": "echristakopoulou/glslim", "max_stars_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-16T01:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:45:41.000Z", "max_issues_repo_path": "bcls-0.1/src/bccgls.c", "max_issues_repo_name": "echristakopoulou/glslim", "max_issues_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bcls-0.1/src/bccgls.c", "max_forks_repo_name": "echristakopoulou/glslim", "max_forks_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T07:46:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T13:00:19.000Z", "avg_line_length": 33.5964285714, "max_line_length": 77, "alphanum_fraction": 0.5265228022, "num_tokens": 2905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5778940224341788}} {"text": "#include \n#include /*per sin i cos*/\n#include /*pel malloc i calloc*/\n#include \n#include \n#include \n#include \n#include \n#include \"memory.h\"\n\n// what data to save\nint writeData; /* command line input */\n\n// simulation run time\ndouble tStop; /* command line input */\n \n//capacitance\ndouble c=1.;\n\n// leak\ndouble glk=1;\ndouble vlk=-70;\n\n// Na channel\ndouble gna=37;\ndouble vna=55;\n\n// Na activation [m]\ndouble thetam=30;\ndouble sm=15;\n\n// Na inactivation [h]\ndouble thetah=-39;\ndouble sh=3.1;\ndouble tauh0=1;\ndouble tauh1=500;\ndouble thh=57;\ndouble sigmah=3;\n\n// K channel\ndouble gk=45;\ndouble vk=-80;\n\n// K activation\ndouble thetan=-32.;\ndouble sn=-8.;\ndouble taun0=1;\ndouble taun1=100.;\ndouble thn=80.;\ndouble sigman=26.;\n\n// A channel\ndouble ga; /* command line input */\n\n// A activation [a]\ndouble taua = 2;\ndouble thetaa = -50; \ndouble sigmaa = 20;\n\n// A inactivation [b]\ndouble taub=150;\ndouble thetab=-70;\ndouble sigmab=-6;\n\n// kinetics rescaling\ndouble phi=0.75;\n\n// synapse \ndouble vsyne = 0.;\ndouble vsyni = -85.;\ndouble gsyne, gsyni; /* command line input */\ndouble rsyne, rsyni; /* command line input */\ndouble betae = .2;\ndouble betai = .18;\ndouble te, ti, teNext,tiNext; /* synapse event times */\n\ndouble v,m,b,n,a,se,si;\ndouble minf,hinf,ninf,binf,ainf;\ndouble tauh,taun,taua;\ndouble ina,ik,ilk,ia,isyne,isyni;\ndouble alphae;\n \n//double twopi=8*atan(1.);\ndouble twopi=3.1415926535;\n\nint func (double t, const double x[], double dx[], void *params);\n\nint jac (double t, const double y[], double *dfdy, double dfdt[], void *params);\n\n\nint main(int argc, char *argv[]){\n\n double *x,*dx;\n double vlast,tspike;\n double si0;\n double rand;\n int ndim=6;\n int i;\n FILE *output;\n double tol=1.0e-5;\n double mu; \n \n //const gsl_odeiv_step_type * T = gsl_odeiv_step_rk8pd; // Runge-Kutta Prince-Dormand 8-9.\n //const gsl_odeiv_step_type * T = gsl_odeiv_step_rk2imp; // Runge-Kutta 2 implicit.\n const gsl_odeiv_step_type * T = gsl_odeiv_step_rk4imp; // Runge-Kutta 4 implicit.\n //const gsl_odeiv_step_type * T = gsl_odeiv_step_bsimp; // Burlirsch-Stoer implicit.. Need jacobian!\n //const gsl_odeiv_step_type * T = gsl_odeiv_step_gear1; // Gear 1 implicit.\n //const gsl_odeiv_step_type * T = gsl_odeiv_step_gear2; // Gear 2 implicit.\n\n gsl_odeiv_step * s = gsl_odeiv_step_alloc (T, ndim);\n gsl_odeiv_control * c = gsl_odeiv_control_y_new (tol, 0.0);\n gsl_odeiv_evolve * e = gsl_odeiv_evolve_alloc (ndim);\n\n gsl_odeiv_system sys = {func, jac, ndim, &mu};\n \n /* Random generator stuff */\n const gsl_rng_type *U;\n gsl_rng *r;\n gsl_rng_env_setup();\n U = gsl_rng_default;\n r = gsl_rng_alloc (U);\n \n\n /* Parameters From Command Line */ \n writeData = atof(argv[1]); \n tStop = atof(argv[2]); \n ga = atof(argv[3]); \n gsyne = atof(argv[4]); \n gsyni = atof(argv[5]); \n rsyne = atof(argv[6]); \n rsyni = atof(argv[7]); \n\n double t, tf;\n double h = 1.e-3;\n int status;\n \n char name1[100];\n int number1,number2,number3;\n int ncount=0; \n int nite;\n double sum;\n\n if (writeData==1){ /* save all data */\n sprintf(name1, \"data1cpt_ga%g_ge%g_gi%g_re%.1f_ri%g.txt\",ga,gsyne, gsyni, rsyne,rsyni);}\n else if (writeData==2){ /* save spikes */\n sprintf(name1, \"spike1cpt_ga%g_ge%g_gi%g_re%.1f_ri%g.txt\",ga,gsyne, gsyni, rsyne,rsyni);} \n output=fopen(name1, \"w\");\n\n /*open the data file*/\n output=fopen(name1, \"w\");\n if (output==NULL){\n printf(\"Error in opening data file\\n\");\n exit(1);\n }\n\n/*memory allocation*/\nx = new_vector(0, ndim-1);\ndx = new_vector(0, ndim-1); \n\n/*Initial point*/\ndouble v0=-70;\nx[0]=v0; /* v */\nx[1]=1./(1.+exp((v0-thetan)/sn)); /* n */\nx[2]=1/(1+exp(-(v0-thetaa)/sigmaa)); /* a */\nx[3]=1/(1+exp(-(v0-thetab)/sigmab)); /* b */\nx[4]=0; /* se */\nx[5]=0; /* si */\n\n/*integrate*/\n\nt=0.;\nnite=0.;\nvlast=v0;\nte = 0;\nti = -999.; tiNext = 1000./rsyni; si0 = 0;\nte = -999.; rand =gsl_ran_flat(r, 0,1); teNext = -1000.*log(1-rand)/(rsyne);\nif (teNext=-10)&&(vlast<-10)){ \n ncount++;\t\n tspike=t;\n if (writeData==2){ /* save spikes */\n fprintf(output,\" %.5f %.5f\",tspike, si0); fprintf(output, \"\\n\");\n }\n }\n\n vlast=x[0];\n\n nite++;\n }\n\n // generate next excitatory event\n if (tf>=teNext){ \n te = teNext;\n rand=gsl_ran_flat(r, 0,1); teNext+=-1000.*log(1-rand)/(rsyne); \n\n // for instantaneous rise se\n x[4]=1.; // ceiling at 1\n\n si0 = x[5]; // si value at the excitatory event onset\n if (writeData==2){fprintf(output,\" %.5f %.5f \",-tf, x[5]); fprintf(output, \"\\n\");} /* save excitatory events */\n }\n\n // generate next inhibitory event\n if (tf>=tiNext){tiNext+=1000./rsyni; x[5]=1.;} // ceiling at 1 \n if (teNextminf instantaneous\nn = x[1];\na = x[2] ; // 1/(1+exp(-(v-thetaa)/sigmaa)); // a->ainf instantaneous\nb = x[3];\nse= x[4];\nsi= x[5];\n\n// currents\nm3=m*m*m;\nn4=n*n*n*n;\na3=a*a*a;\nina= gna*m3*(1-n)*(v-vna);\nik = gk*n4*(v-vk);\nia = ga*a3*b*(v-vk);\nilk= glk*(v-vlk);\nisyne = gsyne*se*(v-vsyne);\nisyni = gsyni*si*(v-vsyni);\n\n\n/* update voltage */\ndx[0] = - (ilk + ina + ik + ia + isyni + isyne)/c;\n\n/* update n gating */\nninf=1./(1.+exp((v-thetan)/sn));\ntaun=taun0+taun1/(1+exp((v+thn)/sigman));\ndx[1]=phi*(ninf-n)/taun;\n\n/* update a gating */\nainf = 1/(1+exp(-(v-thetaa)/sigmaa));\ndx[2] = (ainf-a)/taua;\n\n/* update b gating */\nbinf = 1./(1+exp(-(v-thetab)/sigmab));\ndx[3]=(binf-b)/taub;\n\n/* update excitation */\ndx[4] = -betae*se; // instantaneous rise, exponential decay\n\n/* update inhibition */\ndx[5] = -betai*si;\n\n return GSL_SUCCESS;\n}\n\n\n\n\n\n\n\n/* The jacobian\n * In case we wanna use implict Burslish-Stoer methods\n */\nint jac (double t, const double y[], double *dfdy, double dfdt[], void *params)\n{\n double mu = *(double *)params;\n gsl_matrix_view dfdy_mat = gsl_matrix_view_array (dfdy, 2, 2);\n gsl_matrix * m = &dfdy_mat.matrix;\n\n // Si usamos Burlish-Stoer tenemos de dar el Jacobiano\n /*gsl_matrix_set (m, 0, 0, 0.0);\n gsl_matrix_set (m, 0, 1, 1.0);\n gsl_matrix_set (m, 1, 0, -2.0*mu*y[0]*y[1] - 1.0);\n gsl_matrix_set (m, 1, 1, -mu*(y[0]*y[0] - 1.0));*/\n\n // Si usamos otro método podemos dejar el jacobiano\n // todo a cero.\n gsl_matrix_set (m, 0, 0, 0.0);\n gsl_matrix_set (m, 0, 0, 0.0);\n gsl_matrix_set (m, 0, 0, 0.0);\n gsl_matrix_set (m, 0, 0, 0.0);\n dfdt[0] = 0.0;\n dfdt[1] = 0.0;\n \n return GSL_SUCCESS;\n}\n\n\n", "meta": {"hexsha": "21bc5b237b990651842b5e17719571e78410adde", "size": 7504, "ext": "c", "lang": "C", "max_stars_repo_path": "ga.c", "max_stars_repo_name": "jgoldwyn/Gain-Control-With-IA", "max_stars_repo_head_hexsha": "bb6fa4caca128688c30213dd260a25d613bfb8cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-19T04:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-19T04:03:31.000Z", "max_issues_repo_path": "ga.c", "max_issues_repo_name": "jgoldwyn/Gain-Control-With-IA", "max_issues_repo_head_hexsha": "bb6fa4caca128688c30213dd260a25d613bfb8cf", "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": "ga.c", "max_forks_repo_name": "jgoldwyn/Gain-Control-With-IA", "max_forks_repo_head_hexsha": "bb6fa4caca128688c30213dd260a25d613bfb8cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-27T02:59:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-27T02:59:15.000Z", "avg_line_length": 22.6024096386, "max_line_length": 116, "alphanum_fraction": 0.6068763326, "num_tokens": 2739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5778850323102679}} {"text": "#include // per utilizzare variabili di tipo pthread_t\r\n#include // utilità generale (allocazione, controllo processi, etc.)\r\n#include // per utilizzo dei thread\r\n#include // per elaborazione su stringhe\r\n#include \r\n\r\n#include // per usare i vettori\r\n#include // per usare le matrici\r\n\r\n#include // per calcolare autovalori e autovettori\r\n\r\n#include // per usare funzioni di probabilità\r\n\r\n#include // per usare funzioni su matrici\r\n#include // per usare le permutazioni\r\n\r\n#define debug 0 // variabile per settare le stampe di controllo\r\n#define troncamento 100 // per approssimazione alla 3° cifra significativa dopo la virgola\r\n\r\nint controllo = 1; // variabile per verificare la chiamata di funzioni\r\n\r\ndouble **data_set_origine, **data_set, **data_compression, **autovettori;\r\ndouble *autovalori;\r\nint dimensione = 0;\r\n\r\nstruct registro{ // puntatori alle celle per eseguire il prodotto matriciale A*B\r\n\tdouble *mtx_1, *mtx_2; //mtx_1: riga di A, mtx_2: colonna di B\r\n\tint *indici; // posizione in cui salvare il singolo valore dell'operazione\r\n} catalogo;\r\n\r\nstruct gsl{ // puntatori agli autovalori e autovettori di tipo gsl\r\n\tgsl_vector *vector; // autovalori\r\n\tgsl_matrix *matrix; // autovettori\r\n} puntatori_gsl;\r\n\r\nvoid stampa(int tipo, double **mt1, double *mt2, char nome[], int nr, int nc){ // il tipo indica che tipo di stampa effettuo\r\n\tint i,j = 0; \r\n\tswitch(tipo){\r\n\t\tcase 0: //stampa dimensione\r\n\t\t\tprintf(\"%s: %d \\n\", nome, nr); //Dimensioni \r\n\t\tbreak;\r\n\t\tcase 1: //stampa la matrice con il proprio nome\r\n\t\t\tprintf(\"Stampa matrice %s: \\n\", nome);\r\n\t\t\tfor(i = 0; i < nr; i++){\r\n\t\t\t\tfor(j = 0; j < nc; j++){\r\n\t\t\t\t\tif(j == 0){\r\n\t\t\t\t\t\tprintf(\"| \");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tprintf(\"%2.2f\\t\", mt1[i][j]);\r\n\t\t\t\t\tif(j == nc-1){\r\n\t\t\t\t\t\tprintf(\"|\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tprintf(\"\\n\");\r\n\t\t\t}\r\n\t\tbreak;\r\n\t\tcase 2://stampa media in forma estesa\r\n\t\t\tprintf(\"Stampa valor medio: \\n\");\r\n\t\t\tfor(i = 0; i < nr; i++){\r\n\t\t\t\tprintf(\"media[%d]=%2.2f \\n\", i, mt2[i]);\r\n\t\t\t}\r\n\t\tbreak;\r\n\t\tcase 3: //stampa gli autovalori in forma matriciale\r\n\t\t\tprintf(\"Stampa autovalori(covarianza): \\n\");\r\n\t\t\tfor(i = 0; i < dimensione; i++){\r\n\t\t\t\tif(i == 0){\r\n\t\t\t\t\tprintf(\"| \");\r\n\t\t\t\t}\r\n\t\t\t\tprintf(\"%2.4g\\t\", autovalori[i]);\r\n\t\t\t\tif(i == dimensione-1){\r\n\t\t\t\t\tprintf(\"| \\n\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\tbreak;\r\n\t\tcase 5: //stampa errori verifica\r\n\t\t\tprintf(\"Errore la verifica non è andata a buon fine\\n\");\r\n\t\t\tprintf(\"La matrice Verifica è diversa dalla matrice di partenza \\n\");\r\n\t\tbreak;\r\n\t\tcase 6://stampa matrici monodimensionali in maniera estesa\r\n\t\t\tprintf(\"Stampa Matrice Estesa %s: \\n\", nome);\r\n\t\t\tfor(i = 0; i < dimensione; i++){\r\n\t\t\t\tprintf(\"%s[%d]=%2.2f \\n\", nome, i, mt2[i]);\r\n\t\t\t}\r\n\t\tbreak;\r\n\t\tcase 7: //stampa matrici bidimensionali in maniera estesa\r\n\t\t\tprintf(\"Stampa Matrice Estesa %s : \\n\", nome);\r\n\t\t\tfor(i = 0; i < dimensione; i++){\r\n\t\t\t\tfor(j = 0; j < dimensione; j++){\r\n\t\t\t\t\tprintf(\"%s[%d][%d]=%2.2f \\n\", nome, i, j, mt1[i][j]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\tbreak;\r\n\t}\r\n\tprintf(\"\\n\");\r\n}\r\n\r\nvoid *thread_function(void *candidato){ // singola iterazione del prodotto matriciale\r\n\tint i = 0;\r\n int *indici;\r\n\tdouble *mtx_1, *mtx_2;\r\n\tstruct registro *catalogo;\r\n\t\r\n\t// casting degli argomenti della thread_function\r\n\tcatalogo=(struct registro*)candidato;\r\n\tmtx_1=catalogo->mtx_1;\r\n\tmtx_2=catalogo->mtx_2;\r\n\tindici=catalogo->indici;\r\n\t\r\n\t/*\r\n\t\tesecuzione del prodotto matriciale (a singoli elementi): si esegue il singolo prodotto, il risultato\r\n\t\tlo si salva sulla posizione corrente del'array tmp[0]; infine si somma il precedente risultato al valore presente\r\n\t\tnella cella 0 di tmp (tmp[0][0] svolgerà il ruolo di sommatore, senza dover creare una variabile temporanea).\r\n\t*/\r\n\tfor(i=0; i0){\r\n\t\t\tmtx_1[0]=mtx_1[0]+mtx_1[i];\r\n\t\t\tif(debug==1){printf(\"somma: %2.2f\\n\", mtx_1[0]);}\r\n\t\t}\r\n\t} i=0;\r\n\t\r\n\t// inserimento della somma nell'apposita cella della matrice globale: data_compression\r\n\tdata_compression[indici[0]][indici[1]]=mtx_1[0];\t\r\n\tif(debug==1){\r\n\t\tprintf(\"data_compression[%d][%d]=%2.2f\\n\", indici[0], indici[1], data_compression[indici[0]][indici[1]]);\r\n\t}\r\n\t\r\n\treturn NULL;\r\n}\r\n\r\ndouble *media(int nrighe){ // media sulle righe del data set\r\n\tint i, j = 0;\r\n\tdouble somma = 0;\r\n\tdouble *media;\r\n\t\r\n\tmedia=malloc(nrighe*sizeof(double)); // alloccamento dinamico\r\n\tif(media==NULL){printf(\"ERRORE: media non alloccata.\\n\");}\r\n\t\r\n\tfor(i=0; i 47) && (((int)stringa[i]) < 58))){\r\n\t\t\tset=1; //dico che erano caratteri \r\n\t\t\tbuf[j]=stringa[i]; //salvo il numero\r\n\t\t\tj++; //incremento il puntatore\r\n\t\t}else{\r\n\t\t\tset=0;\r\n\t\t}\r\n\t\tif((set==0 && last_set==1) || (set==1 && i == (strlen(stringa)-1))){ //controllo se ho letto tutto il numero\r\n\t\t\ta=atof(buf); //converto la stringa in un double\r\n\t\t\tdata_set_origine[riga][k]=a; //salvo il numero\r\n\t\t\tk++; //incremento la colonna\r\n\t\t\tstrcpy(buf, \"\"); //svuoto il buf\r\n\t\t\tj=0;//pongo il puntatore del buf a 0 così da poter leggere il numero seguente\r\n\t\t}\r\n\t\tlast_set=set; //dico qual'era il valore precedente\r\n\t}\r\n}\r\n\r\nint colonne(char stringa[]){ //conto il numero di colonne\r\n\tint set=0, last_set=0; //variabili per puntare il carattere e il penultimo carattere\r\n\tint i, j=0; //variabili locali, j è il numero di colonne\r\n\t\r\n\tfor(i = 0; i < strlen(stringa); i++){\r\n\t\t/*controllo se il carattere in questione è un numero, il segno + o -, oppure il .*/\r\n\t\tif( (((int)stringa[i]) == 43) || (((int)stringa[i]) == 45) || (((int)stringa[i]) == 46) || ((((int)stringa[i]) > 47) && (((int)stringa[i]) < 58))){ \r\n\t\t\tset=1; \r\n\t\t}else{\r\n\t\t\tset=0;\r\n\t\t}\r\n\t\tif((last_set == 1 && set == 0)||(set == 1 && i == (strlen(stringa) -1))){ //controllo se ho finito di leggere il numero\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tlast_set=set;\r\n\t}\r\n\treturn j; //ritorno il numero di colonne\r\n}\r\n\r\nint lettura(){ // funzione per leggere il file in input\r\n\tFILE *fp; // file per la lettura\r\n\tchar pathname[1000]; //percorso file\r\n\tchar buf[2000]; \r\n\tchar *s;\r\n\tint i=0, nrighe=0, ncolonne=1;\r\n\tint j=0;\r\n\t\r\n\t/*prendo in ingresso il nome del file*/\r\n\tprintf(\"Inserisci l'indirizzo del file: \\n\");\r\n\tscanf(\"%s\", pathname);\r\n\tif( (fp = fopen(pathname, \"r\")) == NULL ){ // apro il file e controllo se è avvenuto con successo\r\n\t\tprintf(\"ERRORE - lettura: apertura file %s fallito.\\n\", pathname);\r\n\t\texit(0);\r\n\t}\r\n\t\r\n\t/*inizio la lettura del file*/\r\n\twhile(1){ // conto il numero di righe e colonne\r\n\t\tstpcpy(buf, \"\");\r\n\t\ts = fgets(buf, sizeof(buf), fp); \r\n\t\tif(s == NULL) break; // se la linea è vuota ho letto tutto il file\r\n\t\tnrighe++; // conto le righe\r\n\t\tif(j == 0){\r\n\t\t\tncolonne=colonne(buf);\r\n\t\t\tj++;\r\n\t\t}\r\n\t}\r\n\t\r\n\tdata_set_origine=malloc(nrighe*sizeof(double*));//allocco la memoria del data set\r\n\tdata_set=malloc(ncolonne*sizeof(double*));\r\n\t\r\n\tif(data_set == NULL){ \r\n\t\tprintf(\"ERRORE - lettura: data_set non alloccato.\\n\"); \r\n\t\texit(0);\r\n\t}\r\n\t\r\n\tif(data_set_origine == NULL){ \r\n\t\tprintf(\"ERRORE - lettura: data_set non alloccato.\\n\"); \r\n\t\texit(0);\r\n\t}\r\n\t\r\n\tfor(i = 0; i < nrighe; i++){//alloco tutta la memoria\r\n\t\tdata_set_origine[i]=malloc(ncolonne*sizeof(double));\r\n\t\tdata_set[i]=malloc(nrighe*sizeof(double));\r\n\t\t\r\n\t\tif(data_set[i] == NULL){\r\n\t\t\tprintf(\"ERRORE - lettura: data_set[%d] non alloccato.\\n\", i); \r\n\t\t\texit(0);\r\n\t\t}\r\n\t\t\r\n\t\tif(data_set_origine[i] == NULL){\r\n\t\t\tprintf(\"ERRORE - lettura: data_set_origine[%d] non alloccato.\\n\", i); \r\n\t\t\texit(0);\r\n\t\t}\r\n\t}\r\n\t\r\n\trewind(fp);\r\n\t\r\n\tfor(i = 0; i < nrighe; i++){\t\r\n\t\tstpcpy(buf, \"\");\r\n\t\ts = fgets(buf, sizeof(buf), fp); \r\n\t\tottieni(buf, i);\r\n\t}\r\n\t\r\n\tfclose(fp);\r\n\t\r\n\ttrasponi(nrighe, ncolonne);\r\n\t\r\n\tdimensione = nrighe;\r\n\treturn ncolonne;\r\n}\r\n\r\nint main(int argc, char **argv){\r\n\tint nrighe, i, j = 0; //variabili di gestione \r\n\tdouble *valor_medio, **matrice_covarianza, **sottrazione, **verifica; //array per il salvataggio dei dati\r\n\tstruct gsl pointer_gsl; //inizializzazione struttura\r\n\t\r\n\tif(debug){printf(\"MODALITA' DEBUG ATTIVA\\n\");}\r\n\t \r\n\tnrighe=lettura(); // apertura e lettura del data set, nrighe=ncolonne perchè abbiamo trasposto la matrice\r\n\t\r\n\tstampa(0, NULL, NULL, \"nrighe\", nrighe, 0);\r\n\tstampa(0, NULL, NULL, \"Dimensione del Data_set\", dimensione, 0); // stampa dimensioni del data set\r\n\t\r\n\t//stampa(1, data_set_origine, NULL, \"Data Set\", dimensione, nrighe);\r\n\tstampa(1, data_set, NULL, \"Data Set Trasposto\", nrighe, dimensione);\r\n\t\r\n\t// alloccamento dinamico\r\n\tdata_compression=malloc(nrighe*sizeof(double*));\r\n\tif(data_compression==NULL){printf(\"ERRORE - main: data_compression non alloccato.\\n\"); exit(0);}\r\n\tfor(i=0; i\n#include \n#include \n#include \n#include \n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\n\nstatic double atanint_data[21] = {\n 1.91040361296235937512,\n -0.4176351437656746940e-01,\n 0.275392550786367434e-02,\n -0.25051809526248881e-03,\n 0.2666981285121171e-04,\n -0.311890514107001e-05,\n 0.38833853132249e-06,\n -0.5057274584964e-07,\n 0.681225282949e-08,\n -0.94212561654e-09,\n 0.13307878816e-09,\n -0.1912678075e-10,\n 0.278912620e-11,\n -0.41174820e-12,\n 0.6142987e-13,\n -0.924929e-14,\n 0.140387e-14,\n -0.21460e-15,\n 0.3301e-16,\n -0.511e-17,\n 0.79e-18,\n};\nstatic cheb_series atanint_cs = {\n atanint_data,\n 20,\n -1, 1,\n 10\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_atanint_e(const double x, gsl_sf_result * result)\n{\n const double ax = fabs(x);\n const double sgn = GSL_SIGN(x);\n\n /* CHECK_POINTER(result) */\n\n if(ax == 0.0) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(ax < 0.5*GSL_SQRT_DBL_EPSILON) {\n result->val = x;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(ax <= 1.0) {\n const double t = 2.0 * (x*x - 0.5);\n gsl_sf_result result_c;\n cheb_eval_e(&atanint_cs, t, &result_c);\n result->val = x * result_c.val;\n result->err = x * result_c.err;\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(ax < 1.0/GSL_SQRT_DBL_EPSILON) {\n const double t = 2.0 * (1.0/(x*x) - 0.5);\n gsl_sf_result result_c;\n cheb_eval_e(&atanint_cs, t, &result_c);\n result->val = sgn * (0.5*M_PI*log(ax) + result_c.val/ax);\n result->err = result_c.err/ax + fabs(result->val*GSL_DBL_EPSILON);\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n result->val = sgn * (0.5*M_PI*log(ax) + 1.0 / ax);\n result->err = 2.0 * fabs(result->val * GSL_DBL_EPSILON);\n return GSL_SUCCESS;\n }\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_atanint(const double x)\n{\n EVAL_RESULT(gsl_sf_atanint_e(x, &result));\n}\n", "meta": {"hexsha": "166c4f8dea02052ef4eb2b67e1100d778327baaa", "size": 3021, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/atanint.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/atanint.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/atanint.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.0431034483, "max_line_length": 81, "alphanum_fraction": 0.6547500828, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5773761396270293}} {"text": "/*\nHow to use blas and lapack with the standard\ninterfaces provided by their respective projects, repectively through\n`cblas.h` and `lapacke.h`\n*/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n/**\n * assert two integers are equal\n * if not, print them to stderr and assert false\n */\nvoid assert_eqi(int i1, int i2) {\n if (i1 != i2) {\n fprintf(stderr, \"%d\\n%d\\n\\n\\n\", i1, i2);\n assert(false);\n }\n}\n\n/**\n * assert two doubles are equal within err precision\n * if not, print them to stderr\n */\nvoid assert_eqd(double d1, double d2, double err) {\n if (fabs(d1 - d2) > err) {\n fprintf(stderr, \"%f\\n%f\\n\\n\\n\", d1, d2);\n assert(false);\n }\n}\n\n/** print an array of doubles to stderr */\nvoid print_vecd(int n, double * v) {\n int i;\n for (i=0; i err)\n return false\n return true;\n}\n\nvoid assert_eqvd(int n, double * v1, double * v2, double err){\n if(eq_vecd(n, v1, v2, err) != true){\n print_vecd(n, v1);\n print_vecd(n, v2);\n }\n}\n*/\n\nint main(void) {\n int info, ipiv2[2];\n float err = 1e-6;\n float x2[2], b2[2], c2[2];\n float a2x2[2][2];\n\n\t/* cblas */\n\t{\n x2[0] = 1.0;\n x2[1] = -2.0;\n assert_eqd(cblas_snrm2(2, x2, 1), sqrt(5.0), err);\n }\n\n\t/* lapacke */\n\t{\n\t\t/*\n\t\tsgesv\n\n\t\tMatrix vector multiply.\n\t\t*/\n\t\t{\n\t\t\ta2x2[0][0] = 1.0;\n\t\t\ta2x2[1][0] = 2.0;\n\t\t\ta2x2[0][1] = 3.0;\n\t\t\ta2x2[1][1] = 4.0;\n\t\t\tb2[0] = 5.;\n\t\t\tb2[1] = 11.;\n\n\t\t\tinfo = LAPACKE_sgesv(\n\t\t\t\tLAPACK_COL_MAJOR,\n\t\t\t\t2,\n\t\t\t\t1,\n\t\t\t\t&a2x2[0][0],\n\t\t\t\t2,\n\t\t\t\t&ipiv2[0],\n\t\t\t\t&b2[0],\n\t\t\t\t2\n\t\t\t);\n\t\t\tc2[0] = 1.0;\n\t\t\tc2[1] = 2.0;\n\t\t\tassert_eqi(info, 0);\n\t\t\tassert_eqd(b2[0], c2[0], err);\n\t\t\tassert_eqd(b2[1], c2[1], err);\n\t\t}\n }\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "0d37554076a40f5c114f8d8e0dc95db158ee77b2", "size": 1969, "ext": "c", "lang": "C", "max_stars_repo_path": "awesome/c_cpp/cpp-cheat/lapack/c.c", "max_stars_repo_name": "liujiamingustc/phd", "max_stars_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T03:01:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:02:55.000Z", "max_issues_repo_path": "awesome/c_cpp/cpp-cheat/lapack/c.c", "max_issues_repo_name": "liujiamingustc/phd", "max_issues_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "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": "awesome/c_cpp/cpp-cheat/lapack/c.c", "max_forks_repo_name": "liujiamingustc/phd", "max_forks_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "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": 17.7387387387, "max_line_length": 69, "alphanum_fraction": 0.5363128492, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5773307638523548}} {"text": "#include \n#include \n#include \n#include \n\n#include \n\n#define SLICE\t360\n\nint *jac;\n\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\nvoid draw_differential_eq_plot(void);\nvoid draw_lattice(void);\n\ntypedef struct _xy_plot xy_plot;\nstruct _xy_plot\n{\n\tdouble x;\n\tdouble y;\n};\n\nxy_plot plot_res[1001];\n\nvoid display(void)\n{\n\tglClearColor(0.0, 0.0, 0.0, 1.0);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\tglLoadIdentity();\n\n\tglColor3f(1, 0, 0);\n\n\tglBegin(GL_LINE_LOOP);\n\tglVertex3f(100.0, 0.0, 0.0);\n glVertex3f(-100.0, 0.0, 0.0);\n glEnd();\n\n glColor3f(0.0, 1.0, 0.0);\n\n glBegin(GL_LINE_LOOP);\n glVertex3f(0.0, 100.0, 0.0);\n glVertex3f(0.0, -100.0, 0.0);\n glEnd();\n\n\tdraw_differential_eq_plot();\n\tdraw_lattice();\n\tglutSwapBuffers();\n}\n\nvoid reshape(int w, int h)\n{\n GLfloat n_range = 100.0f;\n\n if(h == 0)\n h = 1;\n\n glViewport(0, 0, w, h);\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n\n#if 0\n if(w <= h)\n glOrtho(-n_range, n_range, -n_range * h / w, n_range * h / w, -n_range, n_range);\n else\n glOrtho(-n_range * w / h, n_range * w / h, -n_range, n_range, -n_range, n_range);\n#endif\n\n\tglOrtho(-10, 10, -0.5, 0.5, -1, 1);\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n}\n\nint calc_vertices_num(void)\n{\n\tdouble tmin = 0.0, tmax = 10.0, delta_t = 0.01;\n\treturn (tmax - tmin) / delta_t;\n}\n\nvoid calc_differential_eq(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 const gsl_odeiv_step_type *type_ptr = gsl_odeiv_step_rkf45;\n\n gsl_odeiv_step *step_ptr = gsl_odeiv_step_alloc (type_ptr, dimension);\n gsl_odeiv_control *control_ptr = gsl_odeiv_control_y_new (eps_abs, eps_rel);\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\tint cnt = 0;\n\tint vertex_num = calc_vertices_num();\n#if 0\n\tdouble res_x[vertex_num + 1] = {0};\n\tdouble res_y[vertex_num + 1] = {0};\n\n\tdouble *res_x = (double *)malloc(sizeof(double) * (vertex_num + 1));\n\tdouble *res_y = (double *)malloc(sizeof(double) * (vertex_num + 1));\n#endif\n\n my_system.function = rhs;\t/* the right-hand-side functions dy[i]/dt */\n my_system.jacobian = NULL;\n my_system.dimension = dimension;\t/* number of diffeq's */\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 = 0.01;\n\n y[0] = 0.16;\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 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\n\t\tplot_res[cnt].x = t;\n\t\tplot_res[cnt].y = y[0];\n printf (\"%.5e %.5e %.5e\\n\", t, plot_res[cnt].x, plot_res[cnt].y); /* print at t=t_next */\n\n\t\tcnt++;\n }\n\n gsl_odeiv_evolve_free (evolve_ptr);\n gsl_odeiv_control_free (control_ptr);\n gsl_odeiv_step_free (step_ptr);\n}\n\nvoid draw_lattice(void)\n{\n\tint i;\n\n\tglColor3f(1, 1, 0);\n\tglBegin(GL_LINES);\n\t\tfor (i = 1; i <= 10; i++)\n\t\t{\n\t\t\tglVertex2f(i, -0.01);\n\t\t\tglVertex2f(i, 0.01);\n\t\t}\n\tglEnd();\n}\n\nvoid draw_differential_eq_plot(void)\n{\n\tfloat t = -100.0, step = 0.01;\n\tfloat x = 0, x2 = 0, y2, cx, cy;\n\tfloat tmp;\n\tint cache = 0;\n\tint i;\n\n\tglBegin(GL_LINES);\n\t//for(; ; t += step)\n\tfor (i = 0; i < 1000; i++)\n\t{\n\t\tx2 = plot_res[i].x;\n\t\ty2 = plot_res[i].y;\n\n\t\tif(cache)\n\t\t{\n\t\t\tglVertex2f(cx, cy);\t// 이전값\n\t\t\tglVertex2f(x2, y2);\t// 현재값\n\t\t}\n\n\t\tcache = 1;\n\t\tcx = x2;\n\t\tcy = y2;\n\t\tprintf(\"t = %f, y2 = %f\\n\", x2, y2);\n\t}\n\tglEnd();\n\n}\n\n\nint main (int argc, char **argv)\n{\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_DOUBLE);\n\tglutInitWindowSize(800, 800);\n\tglutInitWindowPosition(0, 0);\n\tglutCreateWindow(\"Digital Signal Processing\");\n\n\tcalc_differential_eq();\n\n\tglutDisplayFunc(display);\n\tglutReshapeFunc(reshape);\n\tglutMainLoop();\n\n return 0;\n}\n\n/*************************** rhs ****************************/\n/* \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 \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 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\n\t// 10 * y'' + 10 * y' + 90 * y = 0\n\t// y'' + y' + 9 * y = 0\n\t// y'' = - y' - 9 * y\n\t// 파이썬의 dsolve가 자체적으로 표준형을 만들어주는 반면\n\t// GSL의 경우 성능은 더 좋지만 이와 같은 작업을 사용자에게 위임하고 있음\n\tf[0] = y[1];\n\tf[1] = -y[1] - 9 * y[0];\n\n return GSL_SUCCESS;\t\t/* GSL_SUCCESS defined in gsl/errno.h as 0 */\n}\n\n/*************************** Jacobian ****************************/\n/*\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": "6fccc436c5e21a8ff8f650398441749dd77e3e56", "size": 6838, "ext": "c", "lang": "C", "max_stars_repo_path": "ch5/src/main/second_ode_plot.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_plot.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_plot.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": 24.8654545455, "max_line_length": 154, "alphanum_fraction": 0.5720971044, "num_tokens": 2505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5772491584512868}} {"text": "/* roots/demo1.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 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 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n\n#include \"demof.h\"\n#include \"demof.c\"\n\nint\nmain ()\n{\n int status;\n int iterations = 0, max_iterations = 100;\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 s = gsl_root_fdfsolver_alloc (gsl_root_fdfsolver_newton);\n gsl_root_fdfsolver_set (s, &FDF, x);\n\n printf (\"using %s method\\n\", gsl_root_fdfsolver_name (s));\n\n printf (\"%-5s %10s %10s %10s %10s\\n\",\n \"iter\", \"root\", \"actual\", \"err\", \"err(est)\");\n do\n {\n iterations++;\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, 0.001);\n\n if (status == GSL_SUCCESS)\n printf (\"Converged:\\n\");\n\n printf (\"%5d %10.7f %10.7f %+10.7f %10.7f\\n\",\n iterations, x, r_expected, x - r_expected, x - x0);\n }\n while (status == GSL_CONTINUE && iterations < max_iterations);\n\n}\n", "meta": {"hexsha": "9d8eb47c66051195b19f17792124063dcd295d55", "size": 2000, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/roots/demo1.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/roots/demo1.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/roots/demo1.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": 29.8507462687, "max_line_length": 81, "alphanum_fraction": 0.668, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5767488997104623}} {"text": "#include \n\n#define kl 2\n#define ll 3\n#define alpha 1\n\ndouble potential(double x) {\n return 0.5 * pow(alpha, 2) *\n (kl * (kl - 1) / pow(sin(alpha * x), 2) +\n ll * (ll - 1) / pow(cos(alpha * x), 2));\n}\ndouble ground_state_energy() { return 0.5 * pow(alpha, 2) * pow(kl + ll, 2); }\ndouble exact(double x) {\n return pow(cos(alpha * x), ll) * pow(sin(alpha * x), kl) /\n sqrt(3.0 * M_PI / 512.0);\n}\n\n#undef V0\n#undef kl\n#undef ll\n#undef alpha\n", "meta": {"hexsha": "051556f888518cc9a20d2a8920ea7bbae1ecb6b1", "size": 485, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/sin_potential.h", "max_stars_repo_name": "slrodini/nnDE_public", "max_stars_repo_head_hexsha": "49d02c4c8a36993613aabc8b76b85537ebda6c82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/sin_potential.h", "max_issues_repo_name": "slrodini/nnDE_public", "max_issues_repo_head_hexsha": "49d02c4c8a36993613aabc8b76b85537ebda6c82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/sin_potential.h", "max_forks_repo_name": "slrodini/nnDE_public", "max_forks_repo_head_hexsha": "49d02c4c8a36993613aabc8b76b85537ebda6c82", "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.0454545455, "max_line_length": 78, "alphanum_fraction": 0.5690721649, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5766334852670674}} {"text": "#include \n#include \n#include \n//#include \n\ndouble f(double d, void* fdata){\n double * double_fdata = (double*) fdata;\n\n double par_obs = double_fdata[0];\n double var_par = double_fdata[1];\n double DM = double_fdata[2];\n double var_DM = double_fdata[3];\n double par_offset = double_fdata[4];\n double L = double_fdata[5];\n\n //printf(\"Data = %f, %f, %f, %f, %f\\n\", d, par_corrected, var_par, DM, var_DM);\n return pow(d, 2) * exp(-0.5 * (2*d/L + pow(par_obs - (1./d + par_offset), 2.)/var_par + pow(DM - (5*log10(d) - 5), 2.)/var_DM));\n}\n\ndouble integrate_likelihood(const double xmin, const double xmax, double *fdata, double rel_tolerance) {\n gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);\n\n gsl_function F;\n F.function = &f;\n F.params = fdata;\n\n double result, err;\n\n gsl_integration_qag (&F, xmin, xmax, 0, rel_tolerance, 1000, 1, w, &result, &err);\n\n gsl_integration_workspace_free (w);\n \n return result;\n}\n", "meta": {"hexsha": "39a501157c9988963fe9b843ae8d77d45887f03e", "size": 1035, "ext": "c", "lang": "C", "max_stars_repo_path": "likelihood_function_quad.c", "max_stars_repo_name": "vickyscowcroft/bayesian_pl_fitting", "max_stars_repo_head_hexsha": "83463b58d1518f7bb970d7975092917eb2304229", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T11:10:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T10:51:28.000Z", "max_issues_repo_path": "likelihood_function_quad.c", "max_issues_repo_name": "vickyscowcroft/bayesian_pl_fitting", "max_issues_repo_head_hexsha": "83463b58d1518f7bb970d7975092917eb2304229", "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": "likelihood_function_quad.c", "max_forks_repo_name": "vickyscowcroft/bayesian_pl_fitting", "max_forks_repo_head_hexsha": "83463b58d1518f7bb970d7975092917eb2304229", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-12T10:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-12T10:58:47.000Z", "avg_line_length": 29.5714285714, "max_line_length": 132, "alphanum_fraction": 0.652173913, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.5765863977601476}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nint\nmain(void)\n{\n const size_t N = 10000;\n double *data = malloc(N * sizeof(double));\n gsl_rstat_quantile_workspace *work_25 = gsl_rstat_quantile_alloc(0.25);\n gsl_rstat_quantile_workspace *work_50 = gsl_rstat_quantile_alloc(0.5);\n gsl_rstat_quantile_workspace *work_75 = gsl_rstat_quantile_alloc(0.75);\n gsl_rng *r = gsl_rng_alloc(gsl_rng_default);\n double exact_p25, exact_p50, exact_p75;\n double val_p25, val_p50, val_p75;\n size_t i;\n\n /* add data to quantile accumulators; also store data for exact\n * comparisons */\n for (i = 0; i < N; ++i)\n {\n data[i] = gsl_ran_rayleigh(r, 1.0);\n gsl_rstat_quantile_add(data[i], work_25);\n gsl_rstat_quantile_add(data[i], work_50);\n gsl_rstat_quantile_add(data[i], work_75);\n }\n\n /* exact values */\n gsl_sort(data, 1, N);\n exact_p25 = gsl_stats_quantile_from_sorted_data(data, 1, N, 0.25);\n exact_p50 = gsl_stats_quantile_from_sorted_data(data, 1, N, 0.5);\n exact_p75 = gsl_stats_quantile_from_sorted_data(data, 1, N, 0.75);\n\n /* estimated values */\n val_p25 = gsl_rstat_quantile_get(work_25);\n val_p50 = gsl_rstat_quantile_get(work_50);\n val_p75 = gsl_rstat_quantile_get(work_75);\n\n printf (\"The dataset is %g, %g, %g, %g, %g, ...\\n\",\n data[0], data[1], data[2], data[3], data[4]);\n\n printf (\"0.25 quartile: exact = %.5f, estimated = %.5f, error = %.6e\\n\",\n exact_p25, val_p25, (val_p25 - exact_p25) / exact_p25);\n printf (\"0.50 quartile: exact = %.5f, estimated = %.5f, error = %.6e\\n\",\n exact_p50, val_p50, (val_p50 - exact_p50) / exact_p50);\n printf (\"0.75 quartile: exact = %.5f, estimated = %.5f, error = %.6e\\n\",\n exact_p75, val_p75, (val_p75 - exact_p75) / exact_p75);\n\n gsl_rstat_quantile_free(work_25);\n gsl_rstat_quantile_free(work_50);\n gsl_rstat_quantile_free(work_75);\n gsl_rng_free(r);\n free(data);\n\n return 0;\n}\n", "meta": {"hexsha": "85c192ab8fab71a4ed240fd6575cee6b9836b104", "size": 2040, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/rquantile.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/rquantile.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/rquantile.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": 33.4426229508, "max_line_length": 74, "alphanum_fraction": 0.6843137255, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5763685930953963}} {"text": "#include \n#include \n#include \n#include \n\n#pragma comment(lib,\"gsl\")\n\nint main(int argc, char** argv)\n{\n gsl_complex a,b;\n GSL_SET_COMPLEX(&a,3,4);//a=3+4i\n GSL_SET_COMPLEX(&b,6,8);//b=6+8i\n gsl_complex c = gsl_complex_add(a,b);\n printf(\"a+b\\treal : %f image : %f\\n\",c.dat[0],c.dat[1]);\n c = gsl_complex_sub(a,b);\n printf(\"a-b\\treal : %f image : %f\\n\",c.dat[0],c.dat[1]);\n c = gsl_complex_mul(a,b);\n printf(\"a*b\\treal : %f image : %f\\n\",c.dat[0],c.dat[1]);\n c = gsl_complex_div(a,b);\n printf(\"a/b\\treal : %f image : %f\\n\",c.dat[0],c.dat[1]);\n // system(\"PAUSE\");\n return 0;\n}", "meta": {"hexsha": "ebe8710f9613cca702bb7b3fec438e7310961d35", "size": 675, "ext": "c", "lang": "C", "max_stars_repo_path": "Sources/CLibrary/GSL/gsl_complex.c", "max_stars_repo_name": "wurui1994/test", "max_stars_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-12-19T09:15:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-30T13:02:00.000Z", "max_issues_repo_path": "Sources/CLibrary/GSL/gsl_complex.c", "max_issues_repo_name": "wurui1994/test", "max_issues_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f", "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": "Sources/CLibrary/GSL/gsl_complex.c", "max_forks_repo_name": "wurui1994/test", "max_forks_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2018-04-10T13:25:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T01:51:03.000Z", "avg_line_length": 29.347826087, "max_line_length": 60, "alphanum_fraction": 0.5911111111, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5763384815754085}} {"text": "/* specfunc/hermite.c\n * \n * Copyright (C) 2011, 2012, 2013, 2014 Konrad Griessinger\n * (konradg(at)gmx.net)\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/*----------------------------------------------------------------------*\n * \"The purpose of computing is insight, not numbers.\" - R.W. Hamming *\n * Hermite polynomials, Hermite functions *\n * and their respective arbitrary derivatives *\n *----------------------------------------------------------------------*/\n\n/* TODO:\n * - array functions for derivatives of Hermite functions\n * - asymptotic approximation for derivatives of Hermite functions\n * - refine existing asymptotic approximations, especially around x=sqrt(2*n+1) or x=sqrt(2*n+1)*sqrt(2), respectively\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n#include \"eval.h\"\n\n#define pow2(n) (gsl_sf_pow_int(2,n))\n\n/* Evaluates the probabilists' Hermite polynomial of order n at position x using upward recurrence. */\nstatic int \ngsl_sf_hermite_prob_iter_e(const int n, const double x, gsl_sf_result * result)\n{\n result->val = 0.;\n result->err = 0.;\n\n if(n < 0) {\n DOMAIN_ERROR(result);\n }\n else if(n == 0) {\n result->val = 1.;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else if(n == 1) {\n result->val = x;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else if(x == 0.){\n if(GSL_IS_ODD(n)){\n result->val = 0.;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else{\n if(n < 301){\n\t/*\n\tdouble f;\n\tint j;\n\tf = (GSL_IS_ODD(n/2)?-1.:1.);\n\tfor(j=1; j < n; j+=2) {\n\t f*=j;\n\t}\n\tresult->val = f;\n\tresult->err = 0.;\n\t*/\n\tif(n < 297){\n\t gsl_sf_doublefact_e(n-1, result);\n\t (GSL_IS_ODD(n/2)?result->val = -result->val:1.);\n\t}\n\telse if (n == 298){\n\t result->val = (GSL_IS_ODD(n/2)?-1.:1.)*1.25527562259930633890922678431e304;\n\t result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\t}\n\telse{\n\t result->val = (GSL_IS_ODD(n/2)?-1.:1.)*3.7532741115719259533385880851e306;\n\t result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\t}\n }\n else{\n\tresult->val = (GSL_IS_ODD(n/2)?GSL_NEGINF:GSL_POSINF);\n\tresult->err = GSL_POSINF;\n }\n return GSL_SUCCESS;\n }\n }\n/*\n else if(x*x < 4.0*n && n > 100000) {\n // asymptotic formula\n double f = 1.0;\n int j;\n if(GSL_IS_ODD(n)) {\n f=gsl_sf_fact((n-1)/2)*gsl_sf_pow_int(2,n/2)*M_SQRT2/M_SQRTPI;\n }\n else {\n for(j=1; j < n; j+=2) {\n\tf*=j;\n }\n }\n return f*exp(x*x/4)*cos(x*sqrt(n)-(n%4)*M_PI_2)/sqrt(sqrt(1-x*x/4.0/n));\n // return f*exp(x*x/4)*cos(x*sqrt(n)-n*M_PI_2)/sqrt(sqrt(1-x*x/4.0/n));\n }\n*/\n else{\n /* upward recurrence: He_{n+1} = x He_n - n He_{n-1} */\n\n double p_n0 = 1.0; /* He_0(x) */\n double p_n1 = x; /* He_1(x) */\n double p_n = p_n1;\n\n double e_n0 = GSL_DBL_EPSILON;\n double e_n1 = fabs(x)*GSL_DBL_EPSILON;\n double e_n = e_n1;\n\n int j=0, c=0;\n\n for(j=1; j <= n-1; j++){\n if (gsl_isnan(p_n) == 1){\n\tbreak;\n }\n p_n = x*p_n1-j*p_n0;\n p_n0 = p_n1;\n p_n1 = p_n;\n\n e_n = (fabs(x)*e_n1+j*e_n0);\n e_n0 = e_n1;\n e_n1 = e_n;\n\n while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 0.5;\n\tp_n1 *= 0.5;\n\tp_n = p_n1;\n\te_n0 *= 0.5;\n\te_n1 *= 0.5;\n\te_n = e_n1;\n\tc++;\n }\n\n while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 2.0;\n\tp_n1 *= 2.0;\n\tp_n = p_n1;\n\te_n0 *= 2.0;\n\te_n1 *= 2.0;\n\te_n = e_n1;\n\tc--;\n }\n }\n\n /*\n // check to see that the correct values are computed, even when overflow strikes in the end; works, thus very large results are accessible by determining mantissa and exponent separately\n double lg2 = 0.30102999566398119521467838;\n double ln10 = 2.3025850929940456840179914546843642076011014886;\n printf(\"res= %g\\n\", p_n*pow(10.,((lg2*c)-((long)(lg2*c)))) );\n printf(\"res= %g * 10^(%ld)\\n\", p_n*pow(10.,((lg2*c)-((long)(lg2*c))))/pow(10.,((long)(log(fabs(p_n*pow(10.,((lg2*c)-((long)(lg2*c))))))/ln10))), ((long)(log(fabs(p_n*pow(10.,((lg2*c)-((long)(lg2*c))))))/ln10))+((long)(lg2*c)) );\n */\n\n result->val = pow2(c)*p_n;\n result->err = pow2(c)*e_n + fabs(result->val)*GSL_DBL_EPSILON;\n /* result->err = e_n + n*fabs(p_n)*GSL_DBL_EPSILON;\n no idea, where the factor n came from => removed\n */\n\n if (gsl_isnan(result->val) != 1){\n return GSL_SUCCESS;\n }\n else{\n return GSL_ERANGE;\n }\n }\n}\n\n/* Approximatively evaluates the probabilists' Hermite polynomial of order n at position x.\n * An approximation depending on the x-range (see Szego, Gabor (1939, 1958, 1967), Orthogonal Polynomials, American Mathematical Society) is used. */\nstatic int \ngsl_sf_hermite_prob_appr_e(const int n, const double x, gsl_sf_result * result)\n{\n /* Plancherel-Rotach approximation (note: Szego defines the Airy function differently!) */\n const double aizero1 = -2.3381074104597670384891972524467; /* first zero of the Airy function Ai */\n double z = fabs(x)*M_SQRT1_2;\n double f = 1.;\n int j;\n for(j=1; j <= n; j++) {\n f*=sqrt(j);\n }\n if (z < sqrt(2*n+1.)+aizero1/M_SQRT2/pow(n,1/6.)){\n double phi = acos(z/sqrt(2*n+1.));\n result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*pow(2./n,0.25)/sqrt(M_SQRTPI*sin(phi))*sin(M_PI*0.75+(0.5*n+0.25)*(sin(2*phi)-2*phi))*exp(0.5*z*z);\n result->err = 2. * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if (z > sqrt(2*n+1.)-aizero1/M_SQRT2/pow(n,1/6.)){\n double phi = acosh(z/sqrt(2*n+1.));\n result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*pow(n,-0.25)/M_SQRT2/sqrt(M_SQRT2*M_SQRTPI*sinh(phi))*exp((0.5*n+0.25)*(2*phi-sinh(2*phi)))*exp(0.5*z*z);\n result->err = 2. * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else{\n gsl_sf_result Ai;\n gsl_sf_airy_Ai_e((z-sqrt(2*n+1.))*M_SQRT2*pow(n,1/6.),0,&Ai);\n result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*sqrt(M_SQRTPI*M_SQRT2)*pow(n,-1/12.)*Ai.val*exp(0.5*z*z);\n result->err = f*sqrt(M_SQRTPI*M_SQRT2)*pow(n,-1/12.)*Ai.err*exp(0.5*z*z) + GSL_DBL_EPSILON*fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\n/* Evaluates the probabilists' Hermite polynomial of order n at position x.\n * For small n upward recurrence is employed, while for large n and NaNs from the iteration an approximation depending on the x-range (see Szego, Gabor (1939, 1958, 1967), Orthogonal Polynomials, American Mathematical Society) is used. */\nint \ngsl_sf_hermite_prob_e(const int n, const double x, gsl_sf_result * result)\n{\n if( (x==0. || n<=100000) && (gsl_sf_hermite_prob_iter_e(n,x,result)==GSL_SUCCESS) ){\n return GSL_SUCCESS;\n }\n else{\n return gsl_sf_hermite_prob_appr_e(n,x,result);\n }\n}\n\ndouble gsl_sf_hermite_prob(const int n, const double x)\n{\n EVAL_RESULT(gsl_sf_hermite_prob_e(n, x, &result));\n}\n\n/* Evaluates the m-th derivative of the probabilists' Hermite polynomial of order n at position x.\n * The direct formula He^{(m)}_n = n!/(n-m)!*He_{n-m}(x) (where He_j(x) is the j-th probabilists' Hermite polynomial and He^{(m)}_j(x) its m-th derivative) is employed. */\nint\ngsl_sf_hermite_prob_der_e(const int m, const int n, const double x, gsl_sf_result * result)\n{\n if(n < 0 || m < 0) {\n DOMAIN_ERROR(result);\n }\n else if(n < m) {\n result->val = 0.;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else{\n double f = gsl_sf_choose(n,m)*gsl_sf_fact(m);\n gsl_sf_result He;\n gsl_sf_hermite_prob_e(n-m,x,&He);\n result->val = He.val*f;\n result->err = He.err*f + GSL_DBL_EPSILON*fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\ndouble\ngsl_sf_hermite_prob_der(const int m, const int n, const double x)\n{\n EVAL_RESULT(gsl_sf_hermite_prob_der_e(m, n, x, &result));\n}\n\n/* Evaluates the physicists' Hermite polynomial of order n at position x.\n * For small n upward recurrence is employed, while for large n and NaNs from the iteration an approximation depending on the x-range (see Szego, Gabor (1939, 1958, 1967), Orthogonal Polynomials, American Mathematical Society) is used. */\nint\ngsl_sf_hermite_phys_e(const int n, const double x, gsl_sf_result * result)\n{\n result->val = 0.;\n result->err = 0.;\n\n if(n < 0) {\n DOMAIN_ERROR(result);\n }\n else if(n == 0) {\n result->val = 1.;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else if(n == 1) {\n result->val = 2.0*x;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else if(x == 0.){\n if(GSL_IS_ODD(n)){\n result->val = 0.;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else{\n if(n < 269){\n\tdouble f = pow2(n/2);\n\tgsl_sf_doublefact_e(n-1, result);\n\tresult->val *= f;\n\tresult->err *= f;\n\t(GSL_IS_ODD(n/2)?result->val = -result->val:1.);\n\t/*\n\tdouble f;\n\tint j;\n\tf = (GSL_IS_ODD(n/2)?-1.:1.);\n\tfor(j=1; j < n; j+=2) {\n\t f*=2*j;\n\t}\n\tresult->val = f;\n\tresult->err = 0.;\n\t*/\n }\n else{\n\tresult->val = (GSL_IS_ODD(n/2)?GSL_NEGINF:GSL_POSINF);\n\tresult->err = GSL_POSINF;\n }\n return GSL_SUCCESS;\n }\n }\n /*\n else if(x*x < 2.0*n && n > 100000) {\n // asymptotic formula\n double f = 1.0;\n int j;\n if(GSL_IS_ODD(n)) {\n f=gsl_sf_fact((n-1)/2)*gsl_sf_pow_int(2,n)/M_SQRTPI;\n }\n else {\n for(j=1; j < n; j+=2) {\n\tf*=j;\n }\n f*=gsl_sf_pow_int(2,n/2);\n }\n return f*exp(x*x/2)*cos(x*sqrt(2.0*n)-(n%4)*M_PI_2)/sqrt(sqrt(1-x*x/2.0/n));\n // return f*exp(x*x/2)*cos(x*sqrt(2.0*n)-n*M_PI_2)/sqrt(sqrt(1-x*x/2.0/n));\n }\n */\n else if (n <= 100000){\n /* upward recurrence: H_{n+1} = 2x H_n - 2j H_{n-1} */\n\n double p_n0 = 1.0; /* H_0(x) */\n double p_n1 = 2.0*x; /* H_1(x) */\n double p_n = p_n1;\n\n double e_n0 = GSL_DBL_EPSILON;\n double e_n1 = 2.*fabs(x)*GSL_DBL_EPSILON;\n double e_n = e_n1;\n\n int j=0, c=0;\n\n for(j=1; j <= n-1; j++){\n if (gsl_isnan(p_n) == 1){\n\tbreak;\n }\n p_n = 2.0*x*p_n1-2.0*j*p_n0;\n p_n0 = p_n1;\n p_n1 = p_n;\n\n e_n = 2.*(fabs(x)*e_n1+j*e_n0);\n e_n0 = e_n1;\n e_n1 = e_n;\n\n while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 0.5;\n\tp_n1 *= 0.5;\n\tp_n = p_n1;\n\te_n0 *= 0.5;\n\te_n1 *= 0.5;\n\te_n = e_n1;\n\tc++;\n }\n\n while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 2.0;\n\tp_n1 *= 2.0;\n\tp_n = p_n1;\n\te_n0 *= 2.0;\n\te_n1 *= 2.0;\n\te_n = e_n1;\n\tc--;\n }\n }\n\n result->val = pow2(c)*p_n;\n result->err = pow2(c)*e_n + fabs(result->val)*GSL_DBL_EPSILON;\n /* result->err = e_n + n*fabs(p_n)*GSL_DBL_EPSILON;\n no idea, where the factor n came from => removed */\n if (gsl_isnan(result->val) != 1){\n return GSL_SUCCESS;\n }\n }\n\n /* the following condition is implied by the logic above */\n {\n /* Plancherel-Rotach approximation (note: Szego defines the Airy function differently!) */\n const double aizero1 = -2.3381074104597670384891972524467; /* first zero of the Airy function Ai */\n double z = fabs(x);\n double f = 1.;\n int j;\n for(j=1; j <= n; j++) {\n f*=sqrt(j);\n }\n if (z < sqrt(2*n+1.)+aizero1/M_SQRT2/pow(n,1/6.)){\n double phi = acos(z/sqrt(2*n+1.));\n result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*(GSL_IS_ODD(n)?M_SQRT2:1.)*pow2(n/2)*pow(2./n,0.25)/sqrt(M_SQRTPI*sin(phi))*sin(M_PI*0.75+(0.5*n+0.25)*(sin(2*phi)-2*phi))*exp(0.5*z*z);\n result->err = 2. * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if (z > sqrt(2*n+1.)-aizero1/M_SQRT2/pow(n,1/6.)){\n double phi = acosh(z/sqrt(2*n+1.));\n result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*(GSL_IS_ODD(n)?1.:M_SQRT1_2)*pow2(n/2)*pow(n,-0.25)/sqrt(M_SQRT2*M_SQRTPI*sinh(phi))*exp((0.5*n+0.25)*(2*phi-sinh(2*phi)))*exp(0.5*z*z);\n result->err = 2. * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else{\n gsl_sf_result Ai;\n gsl_sf_airy_Ai_e((z-sqrt(2*n+1.))*M_SQRT2*pow(n,1/6.),0,&Ai);\n result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*(GSL_IS_ODD(n)?M_SQRT2:1.)*sqrt(M_SQRTPI*M_SQRT2)*pow2(n/2)*pow(n,-1/12.)*Ai.val*exp(0.5*z*z);\n result->err = f*(GSL_IS_ODD(n)?M_SQRT2:1.)*pow2(n/2)*sqrt(M_SQRTPI*M_SQRT2)*pow(n,-1/12.)*Ai.err*exp(0.5*z*z) + GSL_DBL_EPSILON*fabs(result->val);\n return GSL_SUCCESS;\n }\n }\n}\n\ndouble\ngsl_sf_hermite_phys(const int n, const double x)\n{\n EVAL_RESULT(gsl_sf_hermite_phys_e(n, x, &result));\n}\n\n/* Evaluates the m-th derivative of the physicists' Hermite polynomial of order n at position x.\n * The direct formula H^{(m)}_n = 2**m*n!/(n-m)!*H_{n-m}(x) (where H_j(x) is the j-th physicists' Hermite polynomial and H^{(m)}_j(x) its m-th derivative) is employed. */\nint \ngsl_sf_hermite_phys_der_e(const int m, const int n, const double x, gsl_sf_result * result)\n{\n if(n < 0 || m < 0) {\n DOMAIN_ERROR(result);\n }\n else if(n < m) {\n result->val = 0.;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else{\n double f = gsl_sf_choose(n,m)*gsl_sf_fact(m)*pow2(m);\n gsl_sf_result H;\n gsl_sf_hermite_phys_e(n-m,x,&H);\n result->val = H.val*f;\n result->err = H.err*f + GSL_DBL_EPSILON*fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\ndouble\ngsl_sf_hermite_phys_der(const int m, const int n, const double x)\n{\n EVAL_RESULT(gsl_sf_hermite_phys_der_e(m, n, x, &result));\n}\n\n/* Evaluates the Hermite function of order n at position x.\n * For large n an approximation depending on the x-range (see Szego, Gabor (1939, 1958, 1967), Orthogonal Polynomials, American Mathematical Society) is used, while for small n the direct formula via the probabilists' Hermite polynomial is applied. */\nint\ngsl_sf_hermite_func_e(const int n, const double x, gsl_sf_result * result)\n{\n /*\n if (x*x < 2.0*n && n > 100000){\n // asymptotic formula\n double f = 1.0;\n int j;\n // return f*exp(x*x/4)*cos(x*sqrt(n)-n*M_PI_2)/sqrt(sqrt(1-x*x/4.0/n));\n return cos(x*sqrt(2.0*n)-(n%4)*M_PI_2)/sqrt(sqrt(0.5*n/M_PI*(1-0.5*x*x/n)))/M_PI;\n }\n */\n if (n < 0){\n DOMAIN_ERROR(result);\n }\n else if(n == 0 && x != 0.) {\n result->val = exp(-0.5*x*x)/sqrt(M_SQRTPI);\n result->err = GSL_DBL_EPSILON*fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(n == 1 && x != 0.) {\n result->val = M_SQRT2*x*exp(-0.5*x*x)/sqrt(M_SQRTPI);\n result->err = GSL_DBL_EPSILON*fabs(result->val);\n return GSL_SUCCESS;\n }\n else if (x == 0.){\n if (GSL_IS_ODD(n)){\n result->val = 0.;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else{\n double f;\n int j;\n f = (GSL_IS_ODD(n/2)?-1.:1.);\n for(j=1; j < n; j+=2) {\n\tf*=sqrt(j/(j+1.));\n }\n result->val = f/sqrt(M_SQRTPI);\n result->err = GSL_DBL_EPSILON*fabs(result->val);\n return GSL_SUCCESS;\n }\n }\n else if (n <= 100000){\n double f = exp(-0.5*x*x)/sqrt(M_SQRTPI*gsl_sf_fact(n));\n gsl_sf_result He;\n gsl_sf_hermite_prob_iter_e(n,M_SQRT2*x,&He);\n result->val = He.val*f;\n result->err = He.err*f + GSL_DBL_EPSILON*fabs(result->val);\n if (gsl_isnan(result->val) != 1 && f > GSL_DBL_MIN && gsl_finite(He.val) == 1){\n return GSL_SUCCESS;\n }\n }\n\n /* upward recurrence: Psi_{n+1} = sqrt(2/(n+1))*x Psi_n - sqrt(n/(n+1)) Psi_{n-1} */\n\n {\n double tw = exp(-x*x*0.5/n); /* \"twiddle factor\" (in the spirit of FFT) */\n double p_n0 = tw/sqrt(M_SQRTPI); /* Psi_0(x) */\n double p_n1 = p_n0*M_SQRT2*x; /* Psi_1(x) */\n double p_n = p_n1;\n double e_n0 = p_n0*GSL_DBL_EPSILON;\n double e_n1 = p_n1*GSL_DBL_EPSILON;\n double e_n = e_n1;\n \n int j;\n\n int c = 0;\n for (j=1;j 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){\n \tp_n0 *= 0.5;\n \tp_n1 *= 0.5;\n\tp_n = p_n1;\n\te_n0 *= 0.5;\n\te_n1 *= 0.5;\n\te_n = e_n1;\n\tc++;\n }\n\n\twhile(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\tp_n0 = p_n0*2;\n\tp_n1 = p_n1*2;\n\tp_n = p_n1;\n\te_n0 = e_n0*2;\n\te_n1 = e_n1*2;\n\te_n = e_n1;\n\tc--;\n }\n }\n\n result->val = p_n*pow2(c);\n result->err = n*fabs(result->val)*GSL_DBL_EPSILON;\n\n if (gsl_isnan(result->val) != 1){\n return GSL_SUCCESS;\n }\n\n {\n /* Plancherel-Rotach approximation (note: Szego defines the Airy function differently!) */\n const double aizero1 = -2.3381074104597670384891972524467; /* first zero of the Airy function Ai */\n double z = fabs(x);\n if (z < sqrt(2*n+1.)+aizero1/M_SQRT2/pow(n,1/6.)){\n double phi = acos(z/sqrt(2*n+1.));\n result->val = (GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*pow(2./n,0.25)/M_SQRTPI/sqrt(sin(phi))*sin(M_PI*0.75+(0.5*n+0.25)*(sin(2*phi)-2*phi));\n result->err = 2. * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if (z > sqrt(2*n+1.)-aizero1/M_SQRT2/pow(n,1/6.)){\n double phi = acosh(z/sqrt(2*n+1.));\n result->val = (GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*pow(n,-0.25)/\n2/M_SQRTPI/sqrt(sinh(phi)/M_SQRT2)*exp((0.5*n+0.25)*(2*phi-sinh(2*phi)));\n result->err = 2. * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else{\n gsl_sf_result Ai;\n gsl_sf_airy_Ai_e((z-sqrt(2*n+1.))*M_SQRT2*pow(n,1/6.),0,&Ai);\n result->val = (GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*sqrt(M_SQRT2)*pow(n,-1/12.)*Ai.val;\n result->err = sqrt(M_SQRT2)*pow(n,-1/12.)*Ai.err + GSL_DBL_EPSILON*fabs(result->val);\n return GSL_SUCCESS;\n }\n }\n }\n}\n\ndouble\ngsl_sf_hermite_func(const int n, const double x)\n{\n EVAL_RESULT(gsl_sf_hermite_func_e(n, x, &result));\n}\n\n/* Evaluates all probabilists' Hermite polynomials up to order nmax at position x. The results are stored in result_array.\n * Since all polynomial orders are needed, upward recurrence is employed. */\nint\ngsl_sf_hermite_prob_array(const int nmax, const double x, double * result_array)\n{\n if(nmax < 0) {\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(nmax == 0) {\n result_array[0] = 1.0;\n return GSL_SUCCESS;\n }\n else if(nmax == 1) {\n result_array[0] = 1.0;\n result_array[1] = x;\n return GSL_SUCCESS;\n }\n else {\n /* upward recurrence: He_{n+1} = x He_n - n He_{n-1} */\n\n double p_n0 = 1.0; /* He_0(x) */\n double p_n1 = x; /* He_1(x) */\n double p_n = p_n1;\n int j=0, c=0;\n\n result_array[0] = 1.0;\n result_array[1] = x;\n\n for(j=1; j <= nmax-1; j++){\n p_n = x*p_n1-j*p_n0;\n p_n0 = p_n1;\n p_n1 = p_n;\n\n while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 0.5;\n\tp_n1 *= 0.5;\n\tp_n = p_n1;\n\tc++;\n }\n\n while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 2.0;\n\tp_n1 *= 2.0;\n\tp_n = p_n1;\n\tc--;\n }\n\n result_array[j+1] = pow2(c)*p_n;\n }\n\n return GSL_SUCCESS;\n }\n}\n\n\n/* Evaluates the m-th derivative of all probabilists' Hermite polynomials up to order nmax at position x. The results are stored in result_array.\n * Since all polynomial orders are needed, upward recurrence is employed. */\n\nint\ngsl_sf_hermite_prob_array_der(const int m, const int nmax, const double x, double * result_array)\n{\n if(nmax < 0 || m < 0) {\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(m == 0) {\n gsl_sf_hermite_prob_array(nmax, x, result_array);\n return GSL_SUCCESS;\n }\n else if(nmax < m) {\n int j;\n for(j=0; j <= nmax; j++){\n result_array[j] = 0.0;\n }\n return GSL_SUCCESS;\n }\n else if(nmax == m) {\n int j;\n for(j=0; j < m; j++){\n result_array[j] = 0.0;\n }\n result_array[nmax] = gsl_sf_fact(m);\n return GSL_SUCCESS;\n }\n else if(nmax == m+1) {\n int j;\n for(j=0; j < m; j++){\n result_array[j] = 0.0;\n }\n result_array[nmax-1] = gsl_sf_fact(m);\n result_array[nmax] = result_array[nmax-1]*(m+1)*x;\n return GSL_SUCCESS;\n }\n else {\n /* upward recurrence: He^{(m)}_{n+1} = (n+1)/(n-m+1)*(x He^{(m)}_n - n He^{(m)}_{n-1}) */\n\n double p_n0 = gsl_sf_fact(m); /* He^{(m)}_{m}(x) */\n double p_n1 = p_n0*(m+1)*x; /* He^{(m)}_{m+1}(x) */\n double p_n = p_n1;\n int j=0, c=0;\n\n for(j=0; j < m; j++){\n result_array[j] = 0.0;\n }\n\n result_array[m] = p_n0;\n result_array[m+1] = p_n1;\n\n for(j=m+1; j <= nmax-1; j++){\n p_n = (x*p_n1-j*p_n0)*(j+1)/(j-m+1);\n p_n0 = p_n1;\n p_n1 = p_n;\n\n while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 0.5;\n\tp_n1 *= 0.5;\n\tp_n = p_n1;\n\tc++;\n }\n\n while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 2.0;\n\tp_n1 *= 2.0;\n\tp_n = p_n1;\n\tc--;\n }\n\n result_array[j+1] = pow2(c)*p_n;\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/* Evaluates all derivatives (starting from 0) up to the mmax-th derivative of the probabilists' Hermite polynomial of order n at position x. The results are stored in result_array.\n * Since all polynomial orders are needed, upward recurrence is employed. */\n\nint\ngsl_sf_hermite_prob_der_array(const int mmax, const int n, const double x, double * result_array)\n{\n if(n < 0 || mmax < 0) {\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(n == 0) {\n int j;\n result_array[0] = 1.0;\n for(j=1; j <= mmax; j++){\n result_array[j] = 0.0;\n }\n return GSL_SUCCESS;\n }\n else if(n == 1 && mmax > 0) {\n int j;\n result_array[0] = x;\n result_array[1] = 1.0;\n for(j=2; j <= mmax; j++){\n result_array[j] = 0.0;\n }\n return GSL_SUCCESS;\n }\n else if( mmax == 0) {\n result_array[0] = gsl_sf_hermite_prob(n,x);\n return GSL_SUCCESS;\n }\n else if( mmax == 1) {\n result_array[0] = gsl_sf_hermite_prob(n,x);\n result_array[1] = n*gsl_sf_hermite_prob(n-1,x);\n return GSL_SUCCESS;\n }\n else {\n /* upward recurrence */\n\n int k = GSL_MAX_INT(0,n-mmax);\n /* Getting a bit lazy here... */\n double p_n0 = gsl_sf_hermite_prob(k,x); /* He_k(x) */\n double p_n1 = gsl_sf_hermite_prob(k+1,x); /* He_{k+1}(x) */\n double p_n = p_n1;\n int j=0, c=0;\n\n for(j=n+1; j <= mmax; j++){\n result_array[j] = 0.0;\n }\n\n result_array[GSL_MIN_INT(n,mmax)] = p_n0;\n result_array[GSL_MIN_INT(n,mmax)-1] = p_n1;\n\n for(j=GSL_MIN_INT(mmax,n)-1; j > 0; j--){\n k++;\n p_n = x*p_n1-k*p_n0;\n p_n0 = p_n1;\n p_n1 = p_n;\n\n while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 0.5;\n\tp_n1 *= 0.5;\n\tp_n = p_n1;\n\tc++;\n }\n\n while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 2.0;\n\tp_n1 *= 2.0;\n\tp_n = p_n1;\n\tc--;\n }\n\n result_array[j-1] = pow2(c)*p_n;\n }\n\n p_n = 1.0;\n for(j=1; j <= GSL_MIN_INT(n,mmax); j++){\n p_n = p_n*(n-j+1);\n result_array[j] = p_n*result_array[j];\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/* Evaluates the series sum_{j=0}^n a_j*He_j(x) with He_j being the j-th probabilists' Hermite polynomial.\n * For improved numerical stability the Clenshaw algorithm (Clenshaw, C. W. (July 1955). \"A note on the summation of Chebyshev series\". Mathematical Tables and other Aids to Computation 9 (51): 118–110.) adapted to probabilists' Hermite polynomials is used. */\n\nint\ngsl_sf_hermite_prob_series_e(const int n, const double x, const double * a, gsl_sf_result * result)\n{\n if(n < 0) {\n DOMAIN_ERROR(result);\n }\n else if(n == 0) {\n result->val = a[0];\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else if(n == 1) {\n result->val = a[0]+a[1]*x;\n result->err = 2.*GSL_DBL_EPSILON * (fabs(a[0]) + fabs(a[1]*x)) ;\n return GSL_SUCCESS;\n }\n else {\n /* downward recurrence: b_n = a_n + x b_{n+1} - (n+1) b_{n+2} */\n\n double b0 = 0.;\n double b1 = 0.;\n double btmp = 0.;\n\n double e0 = 0.;\n double e1 = 0.;\n double etmp = e1;\n\n int j;\n\n for(j=n; j >= 0; j--){\n btmp = b0;\n b0 = a[j]+x*b0-(j+1)*b1;\n b1 = btmp;\n\n etmp = e0;\n e0 = (GSL_DBL_EPSILON*fabs(a[j])+fabs(x)*e0+(j+1)*e1);\n e1 = etmp;\n }\n\n result->val = b0;\n result->err = e0 + fabs(b0)*GSL_DBL_EPSILON;\n return GSL_SUCCESS;\n }\n}\n\ndouble\ngsl_sf_hermite_prob_series(const int n, const double x, const double * a)\n{\n EVAL_RESULT(gsl_sf_hermite_prob_series_e(n, x, a, &result));\n}\n\n/* Evaluates all physicists' Hermite polynomials up to order nmax at position x. The results are stored in result_array.\n * Since all polynomial orders are needed, upward recurrence is employed. */\nint\ngsl_sf_hermite_phys_array(const int nmax, const double x, double * result_array)\n{\n if(nmax < 0) {\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(nmax == 0) {\n result_array[0] = 1.0;\n return GSL_SUCCESS;\n }\n else if(nmax == 1) {\n result_array[0] = 1.0;\n result_array[1] = 2.0*x;\n return GSL_SUCCESS;\n }\n else {\n /* upward recurrence: H_{n+1} = 2x H_n - 2n H_{n-1} */\n\n double p_n0 = 1.0; /* H_0(x) */\n double p_n1 = 2.0*x; /* H_1(x) */\n double p_n = p_n1;\n int j=0, c=0;\n\n result_array[0] = 1.0;\n result_array[1] = 2.0*x;\n\n for(j=1; j <= nmax-1; j++){\n p_n = 2.0*x*p_n1-2.0*j*p_n0;\n p_n0 = p_n1;\n p_n1 = p_n;\n\n while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 0.5;\n\tp_n1 *= 0.5;\n\tp_n = p_n1;\n\tc++;\n }\n\n while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 2.0;\n\tp_n1 *= 2.0;\n\tp_n = p_n1;\n\tc--;\n }\n\n result_array[j+1] = pow2(c)*p_n;\n }\n\n return GSL_SUCCESS;\n }\n}\n\n\n/* Evaluates the m-th derivative of all physicists' Hermite polynomials up to order nmax at position x. The results are stored in result_array.\n * Since all polynomial orders are needed, upward recurrence is employed. */\nint\ngsl_sf_hermite_phys_array_der(const int m, const int nmax, const double x, double * result_array)\n{\n if(nmax < 0 || m < 0) {\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(m == 0) {\n gsl_sf_hermite_phys_array(nmax, x, result_array);\n return GSL_SUCCESS;\n }\n else if(nmax < m) {\n int j;\n for(j=0; j <= nmax; j++){\n result_array[j] = 0.0;\n }\n return GSL_SUCCESS;\n }\n else if(nmax == m) {\n int j;\n for(j=0; j < m; j++){\n result_array[j] = 0.0;\n }\n result_array[nmax] = pow2(m)*gsl_sf_fact(m);\n return GSL_SUCCESS;\n }\n else if(nmax == m+1) {\n int j;\n for(j=0; j < m; j++){\n result_array[j] = 0.0;\n }\n result_array[nmax-1] = pow2(m)*gsl_sf_fact(m);\n result_array[nmax] = result_array[nmax-1]*2*(m+1)*x;\n return GSL_SUCCESS;\n }\n else {\n /* upward recurrence: H^{(m)}_{n+1} = 2(n+1)/(n-m+1)*(x H^{(m)}_n - n H^{(m)}_{n-1}) */\n\n double p_n0 = pow2(m)*gsl_sf_fact(m); /* H^{(m)}_{m}(x) */\n double p_n1 = p_n0*2*(m+1)*x; /* H^{(m)}_{m+1}(x) */\n double p_n = p_n1;\n int j=0, c=0;\n\n for(j=0; j < m; j++){\n result_array[j] = 0.0;\n }\n\n result_array[m] = p_n0;\n result_array[m+1] = p_n1;\n\n for(j=m+1; j <= nmax-1; j++){\n p_n = (x*p_n1-j*p_n0)*2*(j+1)/(j-m+1);\n p_n0 = p_n1;\n p_n1 = p_n;\n\n while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 0.5;\n\tp_n1 *= 0.5;\n\tp_n = p_n1;\n\tc++;\n }\n\n while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 2.0;\n\tp_n1 *= 2.0;\n\tp_n = p_n1;\n\tc--;\n }\n\n result_array[j+1] = pow2(c)*p_n;\n }\n\n return GSL_SUCCESS;\n }\n}\n\n\n/* Evaluates all derivatives (starting from 0) up to the mmax-th derivative of the physicists' Hermite polynomial of order n at position x. The results are stored in result_array.\n * Since all polynomial orders are needed, upward recurrence is employed. */\nint\ngsl_sf_hermite_phys_der_array(const int mmax, const int n, const double x, double * result_array)\n{\n if(n < 0 || mmax < 0) {\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(n == 0) {\n int j;\n result_array[0] = 1.0;\n for(j=1; j <= mmax; j++){\n result_array[j] = 0.0;\n }\n return GSL_SUCCESS;\n }\n else if(n == 1 && mmax > 0) {\n int j;\n result_array[0] = 2*x;\n result_array[1] = 1.0;\n for(j=2; j <= mmax; j++){\n result_array[j] = 0.0;\n }\n return GSL_SUCCESS;\n }\n else if( mmax == 0) {\n result_array[0] = gsl_sf_hermite_phys(n,x);\n return GSL_SUCCESS;\n }\n else if( mmax == 1) {\n result_array[0] = gsl_sf_hermite_phys(n,x);\n result_array[1] = 2*n*gsl_sf_hermite_phys(n-1,x);\n return GSL_SUCCESS;\n }\n else {\n /* upward recurrence */\n\n int k = GSL_MAX_INT(0,n-mmax);\n /* Getting a bit lazy here... */\n double p_n0 = gsl_sf_hermite_phys(k,x); /* H_k(x) */\n double p_n1 = gsl_sf_hermite_phys(k+1,x); /* H_{k+1}(x) */\n double p_n = p_n1;\n int j=0, c=0;\n\n for(j=n+1; j <= mmax; j++){\n result_array[j] = 0.0;\n }\n\n result_array[GSL_MIN_INT(n,mmax)] = p_n0;\n result_array[GSL_MIN_INT(n,mmax)-1] = p_n1;\n\n for(j=GSL_MIN_INT(mmax,n)-1; j > 0; j--){\n k++;\n p_n = 2*x*p_n1-2*k*p_n0;\n p_n0 = p_n1;\n p_n1 = p_n;\n\n while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 0.5;\n\tp_n1 *= 0.5;\n\tp_n = p_n1;\n\tc++;\n }\n\n while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 2.0;\n\tp_n1 *= 2.0;\n\tp_n = p_n1;\n\tc--;\n }\n\n result_array[j-1] = pow2(c)*p_n;\n }\n\n p_n = 1.0;\n for(j=1; j <= GSL_MIN_INT(n,mmax); j++){\n p_n = p_n*(n-j+1)*2;\n result_array[j] = p_n*result_array[j];\n }\n\n return GSL_SUCCESS;\n }\n}\n\n\n/* Evaluates the series sum_{j=0}^n a_j*H_j(x) with H_j being the j-th physicists' Hermite polynomial.\n * For improved numerical stability the Clenshaw algorithm (Clenshaw, C. W. (July 1955). \"A note on the summation of Chebyshev series\". Mathematical Tables and other Aids to Computation 9 (51): 118–110.) adapted to physicists' Hermite polynomials is used. */\nint\ngsl_sf_hermite_phys_series_e(const int n, const double x, const double * a, gsl_sf_result * result)\n{\n if(n < 0) {\n DOMAIN_ERROR(result);\n }\n else if(n == 0) {\n result->val = a[0];\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else if(n == 1) {\n result->val = a[0]+a[1]*2.*x;\n result->err = 2.*GSL_DBL_EPSILON * (fabs(a[0]) + fabs(a[1]*2.*x)) ;\n return GSL_SUCCESS;\n }\n else {\n /* downward recurrence: b_n = a_n + 2x b_{n+1} - 2(n+1) b_{n+2} */\n\n double b0 = 0.;\n double b1 = 0.;\n double btmp = 0.;\n\n double e0 = 0.;\n double e1 = 0.;\n double etmp = e1;\n\n int j;\n\n for(j=n; j >= 0; j--){\n btmp = b0;\n b0 = a[j]+2.*x*b0-2.*(j+1)*b1;\n b1 = btmp;\n\n etmp = e0;\n e0 = (GSL_DBL_EPSILON*fabs(a[j])+fabs(2.*x)*e0+2.*(j+1)*e1);\n e1 = etmp;\n }\n\n result->val = b0;\n result->err = e0 + fabs(b0)*GSL_DBL_EPSILON;\n return GSL_SUCCESS;\n }\n}\n\ndouble\ngsl_sf_hermite_phys_series(const int n, const double x, const double * a)\n{\n EVAL_RESULT(gsl_sf_hermite_phys_series_e(n, x, a, &result));\n}\n\n\n/* Evaluates all Hermite functions up to order nmax at position x. The results are stored in result_array.\n * Since all polynomial orders are needed, upward recurrence is employed. */\nint\ngsl_sf_hermite_func_array(const int nmax, const double x, double * result_array)\n{\n if(nmax < 0) {\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(nmax == 0) {\n result_array[0] = exp(-0.5*x*x)/sqrt(M_SQRTPI);\n return GSL_SUCCESS;\n }\n else if(nmax == 1) {\n result_array[0] = exp(-0.5*x*x)/sqrt(M_SQRTPI);\n result_array[1] = result_array[0]*M_SQRT2*x;\n return GSL_SUCCESS;\n }\n else {\n /* upward recurrence: Psi_{n+1} = sqrt(2/(n+1))*x Psi_n - sqrt(n/(n+1)) Psi_{n-1} */\n\n double p_n0 = exp(-0.5*x*x)/sqrt(M_SQRTPI); /* Psi_0(x) */\n double p_n1 = p_n0*M_SQRT2*x; /* Psi_1(x) */\n double p_n = p_n1;\n int j=0, c=0;\n\n result_array[0] = p_n0;\n result_array[1] = p_n1;\n\n for (j=1;j<=nmax-1;j++)\n {\n p_n=(M_SQRT2*x*p_n1-sqrt(j)*p_n0)/sqrt(j+1.);\n p_n0=p_n1;\n p_n1=p_n;\n\n while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 0.5;\n\tp_n1 *= 0.5;\n\tp_n = p_n1;\n\tc++;\n }\n\n while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\tp_n0 *= 2.0;\n\tp_n1 *= 2.0;\n\tp_n = p_n1;\n\tc--;\n }\n\n result_array[j+1] = pow2(c)*p_n;\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/* Evaluates the series sum_{j=0}^n a_j*Psi_j(x) with Psi_j being the j-th Hermite function.\n * For improved numerical stability the Clenshaw algorithm (Clenshaw, C. W. (July 1955). \"A note on the summation of Chebyshev series\". Mathematical Tables and other Aids to Computation 9 (51): 118–110.) adapted to Hermite functions is used. */\n\nint\ngsl_sf_hermite_func_series_e(const int n, const double x, const double * a, gsl_sf_result * result)\n{\n if(n < 0) {\n DOMAIN_ERROR(result);\n }\n else if(n == 0) {\n result->val = a[0]*exp(-0.5*x*x)/sqrt(M_SQRTPI);\n result->err = GSL_DBL_EPSILON*fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(n == 1) {\n result->val = (a[0]+a[1]*M_SQRT2*x)*exp(-0.5*x*x)/sqrt(M_SQRTPI);\n result->err = 2.*GSL_DBL_EPSILON*(fabs(a[0])+fabs(a[1]*M_SQRT2*x))*exp(-0.5*x*x)/sqrt(M_SQRTPI);\n return GSL_SUCCESS;\n }\n else {\n /* downward recurrence: b_n = a_n + sqrt(2/(n+1))*x b_{n+1} - sqrt((n+1)/(n+2)) b_{n+2} */\n\n double b0 = 0.;\n double b1 = 0.;\n double btmp = 0.;\n\n double e0 = 0.;\n double e1 = 0.;\n double etmp = e1;\n\n int j;\n\n for(j=n; j >= 0; j--){\n btmp = b0;\n b0 = a[j]+sqrt(2./(j+1))*x*b0-sqrt((j+1.)/(j+2.))*b1;\n b1 = btmp;\n\n etmp = e0;\n e0 = (GSL_DBL_EPSILON*fabs(a[j])+sqrt(2./(j+1))*fabs(x)*e0+sqrt((j+1.)/(j+2.))*e1);\n e1 = etmp;\n }\n\n result->val = b0*exp(-0.5*x*x)/sqrt(M_SQRTPI);\n result->err = e0 + fabs(result->val)*GSL_DBL_EPSILON;\n return GSL_SUCCESS;\n }\n}\n\ndouble\ngsl_sf_hermite_func_series(const int n, const double x, const double * a)\n{\n EVAL_RESULT(gsl_sf_hermite_func_series_e(n, x, a, &result));\n}\n\n\n/* Evaluates the m-th derivative of the Hermite function of order n at position x.\n * A summation including upward recurrences is used. */\nint\ngsl_sf_hermite_func_der_e(const int m, const int n, const double x, gsl_sf_result * result)\n{\n /* FIXME: asymptotic formula! */\n if(m < 0 || n < 0) {\n DOMAIN_ERROR(result);\n }\n else if(m == 0){\n return gsl_sf_hermite_func_e(n,x,result);\n }\n else{\n int j=0, c=0;\n double r,er,b;\n double h0 = 1.;\n double h1 = x;\n double eh0 = GSL_DBL_EPSILON;\n double eh1 = GSL_DBL_EPSILON;\n double p0 = 1.;\n double p1 = M_SQRT2*x;\n double ep0 = GSL_DBL_EPSILON;\n double ep1 = M_SQRT2*GSL_DBL_EPSILON;\n double f = 1.;\n for (j=GSL_MAX_INT(1,n-m+1);j<=n;j++)\n {\n\tf *= sqrt(2.*j);\n }\n if (m>n)\n {\n\tf = (GSL_IS_ODD(m-n)?-f:f);\n\tfor (j=0;j 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(h0),fabs(h1)) > GSL_SQRT_DBL_MAX )){\n\t h0 *= 0.5;\n\t h1 *= 0.5;\n\t eh0 *= 0.5;\n\t eh1 *= 0.5;\n\t c++;\n\t}\n\n\twhile(( ( (fabs(h0) < GSL_SQRT_DBL_MIN) && (h0 != 0) ) || ( (fabs(h1) < GSL_SQRT_DBL_MIN) && (h1 != 0) ) ) && ( GSL_MAX(fabs(h0),fabs(h1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\t h0 *= 2.0;\n\t h1 *= 2.0;\n\t eh0 *= 2.0;\n\t eh1 *= 2.0;\n\t c--;\n\t}\n\n }\n h0 *= pow2(c);\n h1 *= pow2(c);\n eh0 *= pow2(c);\n eh1 *= pow2(c);\n\n b = 0.;\n c = 0;\n for (j=1;j<=n-m;j++)\n {\n\tb = (M_SQRT2*x*p1-sqrt(j)*p0)/sqrt(j+1.);\n\tp0 = p1;\n\tp1 = b;\n\t\n\tb = (M_SQRT2*fabs(x)*ep1+sqrt(j)*ep0)/sqrt(j+1.);\n\tep0 = ep1;\n\tep1 = b;\n\n\twhile(( GSL_MIN(fabs(p0),fabs(p1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p0),fabs(p1)) > GSL_SQRT_DBL_MAX )){\n\t p0 *= 0.5;\n\t p1 *= 0.5;\n\t ep0 *= 0.5;\n\t ep1 *= 0.5;\n\t c++;\n\t}\n\n\twhile(( ( (fabs(p0) < GSL_SQRT_DBL_MIN) && (p0 != 0) ) || ( (fabs(p1) < GSL_SQRT_DBL_MIN) && (p1 != 0) ) ) && ( GSL_MAX(fabs(p0),fabs(p1)) < 0.5*GSL_SQRT_DBL_MAX )){\n\t p0 = p0*2;\n\t p1 = p1*2;\n\t ep0 = ep0*2;\n\t ep1 = ep1*2;\n\t c--;\n\t}\n\n }\n p0 *= pow2(c);\n p1 *= pow2(c);\n ep0 *= pow2(c);\n ep1 *= pow2(c);\n\n c = 0;\n b = 0.;\n r = 0.;\n er = 0.;\n for (j=GSL_MAX_INT(0,m-n);j<=m;j++)\n {\n\tr += f*h0*p0;\n\ter += eh0*fabs(f*p0)+ep0*fabs(f*h0)+GSL_DBL_EPSILON*fabs(f*h0*p0);\n\t\n\tb = x*h1-(j+1.)*h0;\n\th0 = h1;\n\th1 = b;\n\t\n\tb = 0.5*(fabs(x)*eh1+(j+1.)*eh0);\n\teh0 = eh1;\n\teh1 = b;\n\t\n\tb = (M_SQRT2*x*p1-sqrt(n-m+j+1.)*p0)/sqrt(n-m+j+2.);\n\tp0 = p1;\n\tp1 = b;\n\t\n\tb = 0.5*(M_SQRT2*fabs(x)*ep1+sqrt(n-m+j+1.)*ep0)/sqrt(n-m+j+2.);\n\tep0 = ep1;\n\tep1 = b;\n\t\n\tf *= -(m-j)/(j+1.)/sqrt(n-m+j+1.)*M_SQRT1_2;\n\n\twhile(( (fabs(h0) > 2.0*GSL_SQRT_DBL_MIN) && (fabs(h1) > 2.0*GSL_SQRT_DBL_MIN) && (fabs(p0) > 2.0*GSL_SQRT_DBL_MIN) && (fabs(p1) > 2.0*GSL_SQRT_DBL_MIN) && (fabs(r) > 4.0*GSL_SQRT_DBL_MIN) ) && ( (fabs(h0) > GSL_SQRT_DBL_MAX) || (fabs(h1) > GSL_SQRT_DBL_MAX) || (fabs(p0) > GSL_SQRT_DBL_MAX) || (fabs(p1) > GSL_SQRT_DBL_MAX) || (fabs(r) > GSL_SQRT_DBL_MAX) )){\n\t h0 *= 0.5;\n\t h1 *= 0.5;\n\t eh0 *= 0.5;\n\t eh1 *= 0.5;\n\t p0 *= 0.5;\n\t p1 *= 0.5;\n\t ep0 *= 0.5;\n\t ep1 *= 0.5;\n\t r *= 0.25;\n\t er *= 0.25;\n\t c++;\n\t}\n\n\twhile(( ( (fabs(h0) < GSL_SQRT_DBL_MIN) && (h0 != 0) ) || ( (fabs(h1) < GSL_SQRT_DBL_MIN) && (h1 != 0) ) || ( (fabs(p0) < GSL_SQRT_DBL_MIN) && (p0 != 0) ) || ( (fabs(p1) < GSL_SQRT_DBL_MIN) && (p1 != 0) ) || ( (fabs(r) < GSL_SQRT_DBL_MIN) && (r != 0) ) ) && ( (fabs(h0) < 0.5*GSL_SQRT_DBL_MAX) && (fabs(h1) < 0.5*GSL_SQRT_DBL_MAX) && (fabs(p0) < 0.5*GSL_SQRT_DBL_MAX) && (fabs(p1) < 0.5*GSL_SQRT_DBL_MAX) && (fabs(r) < 0.25*GSL_SQRT_DBL_MAX) )){\n\t p0 *= 2.0;\n\t p1 *= 2.0;\n\t ep0 *= 2.0;\n\t ep1 *= 2.0;\n\t h0 *= 2.0;\n\t h1 *= 2.0;\n\t eh0 *= 2.0;\n\t eh1 *= 2.0;\n\t r *= 4.0;\n\t er *= 4.0;\n\t c--;\n\t}\n\n }\n\n r *= pow2(2*c);\n er *= pow2(2*c);\n result->val = r*exp(-0.5*x*x)/sqrt(M_SQRTPI);\n result->err = er*fabs(exp(-0.5*x*x)/sqrt(M_SQRTPI)) + GSL_DBL_EPSILON*fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\ndouble\ngsl_sf_hermite_func_der(const int m, const int n, const double x)\n{\n EVAL_RESULT(gsl_sf_hermite_func_der_e(m, n, x, &result));\n}\n\nstatic double\nH_zero_init(const int n, const int k)\n{\n double p = 1., x = 1., y = 1.;\n if (k == 1 && n > 50) {\n x = (GSL_IS_ODD(n)?1./sqrt((n-1)/6.):1./sqrt(0.5*n));\n }\n else {\n p = -0.7937005259840997373758528196*gsl_sf_airy_zero_Ai(n/2-k+1);\n x = sqrt(2*n+1.);\n y = pow(2*n+1.,1/6.);\n x = x - p/y - 0.1*p*p/(x*y*y) + (9/280. - p*p*p*11/350.)/(x*x*x) + (p*277/12600. - gsl_sf_pow_int(p,4)*823/63000.)/gsl_sf_pow_int(x,4)/y;\n }\n p = acos(x/sqrt(2*n+1.));\n y = M_PI*(-2*(n/2-k)-1.5)/(n+0.5);\n if(gsl_fcmp(y,sin(2.*p)-2*p,GSL_SQRT_DBL_EPSILON)==0) return x; /* initial approx sufficiently accurate */\n if (y > -GSL_DBL_EPSILON) return sqrt(2*n+1.);\n if (p < GSL_DBL_EPSILON) p = GSL_DBL_EPSILON;\n if (p > M_PI_2) p = M_PI_2;\n if (sin(2.*p)-2*p > y){\n x = GSL_MAX((sin(2.*p)-2*p-y)/4.,GSL_SQRT_DBL_EPSILON);\n do{\n x *= 2.;\n p += x;\n } while (sin(2.*p)-2*p > y);\n }\n do {\n x = p;\n p -= (sin(2.*p)-2.*p-y)/(2.*cos(2.*p)-2.);\n if (p<0.||p>M_PI_2) p = M_PI_2;\n } while (gsl_fcmp(x,p,100*GSL_DBL_EPSILON)!=0);\n return sqrt(2*n+1.)*cos(p);\n}\n\n\n/* lookup table for the positive zeros of the probabilists' Hermite polynomials of order 3 through 20 */\nstatic double He_zero_tab[99] = {\n 1.73205080756887729352744634151,\n 0.741963784302725857648513596726,\n 2.33441421833897723931751226721,\n 1.35562617997426586583052129087,\n 2.85697001387280565416230426401,\n 0.616706590192594152193686099399,\n 1.88917587775371067550566789858,\n 3.32425743355211895236183546247,\n 1.154405394739968127239597758838,\n 2.36675941073454128861885646856,\n 3.75043971772574225630392202571,\n 0.539079811351375108072461918694,\n 1.63651904243510799922544657297,\n 2.80248586128754169911301080618,\n 4.14454718612589433206019783917,\n 1.023255663789132524828148225810,\n 2.07684797867783010652215614374,\n 3.20542900285646994336567590292,\n 4.51274586339978266756667884317,\n 0.484935707515497653046233483105,\n 1.46598909439115818325066466416,\n 2.48432584163895458087625118368,\n 3.58182348355192692277623675546,\n 4.85946282833231215015516494660,\n 0.928868997381063940144111999584,\n 1.87603502015484584534137013967,\n 2.86512316064364499771968407254,\n 3.93616660712997692868589612142,\n 5.18800122437487094818666404539,\n 0.444403001944138945299732445510,\n 1.34037519715161672153112945211,\n 2.25946445100079912386492979448,\n 3.22370982877009747166319001956,\n 4.27182584793228172295999293076,\n 5.50090170446774760081221630899,\n 0.856679493519450033897376121795,\n 1.72541837958823916151095838741,\n 2.62068997343221478063807762201,\n 3.56344438028163409162493844661,\n 4.59139844893652062705231872720,\n 5.80016725238650030586450565322,\n 0.412590457954601838167454145167,\n 1.24268895548546417895063983219,\n 2.08834474570194417097139675101,\n 2.96303657983866750254927123447,\n 3.88692457505976938384755016476,\n 4.89693639734556468372449782879,\n 6.08740954690129132226890147034,\n 0.799129068324547999424888414207,\n 1.60671006902872973652322479373,\n 2.43243682700975804116311571682,\n 3.28908242439876638890856229770,\n 4.19620771126901565957404160583,\n 5.19009359130478119946445431715,\n 6.36394788882983831771116094427,\n 0.386760604500557347721047189801,\n 1.16382910055496477419336819907,\n 1.95198034571633346449212362880,\n 2.76024504763070161684598142269,\n 3.60087362417154828824902745506,\n 4.49295530252001124266582263095,\n 5.47222570594934308841242925805,\n 6.63087819839312848022981922233,\n 0.751842600703896170737870774614,\n 1.50988330779674075905491513417,\n 2.28101944025298889535537879396,\n 3.07379717532819355851658337833,\n 3.90006571719800990903311840097,\n 4.77853158962998382710540812497,\n 5.74446007865940618125547815768,\n 6.88912243989533223256205432938,\n 0.365245755507697595916901619097,\n 1.09839551809150122773848360538,\n 1.83977992150864548966395498992,\n 2.59583368891124032910545091458,\n 3.37473653577809099529779309480,\n 4.18802023162940370448450911428,\n 5.05407268544273984538327527397,\n 6.00774591135959752029303858752,\n 7.13946484914647887560975631213,\n 0.712085044042379940413609979021,\n 1.42887667607837287134157901452,\n 2.15550276131693514033871248449,\n 2.89805127651575312007902775275,\n 3.66441654745063847665304033851,\n 4.46587262683103133615452574019,\n 5.32053637733603803162823765939,\n 6.26289115651325170419416064557,\n 7.38257902403043186766326977122,\n 0.346964157081355927973322447164,\n 1.04294534880275103146136681143,\n 1.74524732081412671493067861704,\n 2.45866361117236775131735057433,\n 3.18901481655338941485371744116,\n 3.94396735065731626033176813604,\n 4.73458133404605534390170946748,\n 5.57873880589320115268040332802,\n 6.51059015701365448636289263918,\n 7.61904854167975829138128156060\n};\n\n/* Computes the s-th zero the probabilists' Hermite polynomial of order n.\nA Newton iteration using a continued fraction representation adapted from [E.T. Whittaker (1914), On the continued fractions which represent the functions of Hermite and other functions defined by differential equations, Proceedings of the Edinburgh Mathematical Society, 32, 65-74] is performed with the initial approximation from [Arpad Elbert and Martin E. Muldoon, Approximations for zeros of Hermite functions, pp. 117-126 in D. Dominici and R. S. Maier, eds, \"Special Functions and Orthogonal Polynomials\", Contemporary Mathematics, vol 471 (2008)] refined via the bisection method. */\nint\ngsl_sf_hermite_prob_zero_e(const int n, const int s, gsl_sf_result * result)\n{\n if(n <= 0 || s < 0 || s > n/2) {\n DOMAIN_ERROR(result);\n }\n else if(s == 0) {\n if (GSL_IS_ODD(n) == 1) {\n result->val = 0.;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else {\n DOMAIN_ERROR(result);\n }\n }\n else if(n == 2) {\n result->val = 1.;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else if(n < 21) {\n result->val = He_zero_tab[(GSL_IS_ODD(n)?n/2:0)+((n/2)*(n/2-1))+s-2];\n result->err = GSL_DBL_EPSILON*(result->val);\n return GSL_SUCCESS;\n }\n else {\n double d = 1., x = 1., x0 = 1.;\n int j;\n x = H_zero_init(n,s) * M_SQRT2;\n do {\n x0 = x;\n d = 0.;\n for (j=1; jval = x;\n result->err = 2*GSL_DBL_EPSILON*x + fabs(x-x0);\n return GSL_SUCCESS;\n }\n}\n\ndouble\ngsl_sf_hermite_prob_zero(const int n, const int s)\n{\n EVAL_RESULT(gsl_sf_hermite_prob_zero_e(n, s, &result));\n}\n\n/* lookup table for the positive zeros of the physicists' Hermite polynomials of order 3 through 20 */\nstatic double H_zero_tab[99] = {\n 1.22474487139158904909864203735,\n 0.524647623275290317884060253835,\n 1.65068012388578455588334111112,\n 0.958572464613818507112770593893,\n 2.02018287045608563292872408814,\n 0.436077411927616508679215948251,\n 1.335849074013696949714895282970,\n 2.35060497367449222283392198706,\n 0.816287882858964663038710959027,\n 1.67355162876747144503180139830,\n 2.65196135683523349244708200652,\n 0.381186990207322116854718885584,\n 1.157193712446780194720765779063,\n 1.98165675669584292585463063977,\n 2.93063742025724401922350270524,\n 0.723551018752837573322639864579,\n 1.46855328921666793166701573925,\n 2.26658058453184311180209693284,\n 3.19099320178152760723004779538,\n 0.342901327223704608789165025557,\n 1.03661082978951365417749191676,\n 1.75668364929988177345140122011,\n 2.53273167423278979640896079775,\n 3.43615911883773760332672549432,\n 0.656809566882099765024611575383,\n 1.32655708449493285594973473558,\n 2.02594801582575533516591283121,\n 2.78329009978165177083671870152,\n 3.66847084655958251845837146485,\n 0.314240376254359111276611634095,\n 0.947788391240163743704578131060,\n 1.59768263515260479670966277090,\n 2.27950708050105990018772856942,\n 3.02063702512088977171067937518,\n 3.88972489786978191927164274724,\n 0.605763879171060113080537108602,\n 1.22005503659074842622205526637,\n 1.85310765160151214200350644316,\n 2.51973568567823788343040913628,\n 3.24660897837240998812205115236,\n 4.10133759617863964117891508007,\n 0.291745510672562078446113075799,\n 0.878713787329399416114679311861,\n 1.47668273114114087058350654421,\n 2.09518325850771681573497272630,\n 2.74847072498540256862499852415,\n 3.46265693360227055020891736115,\n 4.30444857047363181262129810037,\n 0.565069583255575748526020337198,\n 1.13611558521092066631913490556,\n 1.71999257518648893241583152515,\n 2.32573248617385774545404479449,\n 2.96716692790560324848896036355,\n 3.66995037340445253472922383312,\n 4.49999070730939155366438053053,\n 0.273481046138152452158280401965,\n 0.822951449144655892582454496734,\n 1.38025853919888079637208966969,\n 1.95178799091625397743465541496,\n 2.54620215784748136215932870545,\n 3.17699916197995602681399455926,\n 3.86944790486012269871942409801,\n 4.68873893930581836468849864875,\n 0.531633001342654731349086553718,\n 1.06764872574345055363045773799,\n 1.61292431422123133311288254454,\n 2.17350282666662081927537907149,\n 2.75776291570388873092640349574,\n 3.37893209114149408338327069289,\n 4.06194667587547430689245559698,\n 4.87134519367440308834927655662,\n 0.258267750519096759258116098711,\n 0.776682919267411661316659462284,\n 1.30092085838961736566626555439,\n 1.83553160426162889225383944409,\n 2.38629908916668600026459301424,\n 2.96137750553160684477863254906,\n 3.57376906848626607950067599377,\n 4.24811787356812646302342016090,\n 5.04836400887446676837203757885,\n 0.503520163423888209373811765050,\n 1.01036838713431135136859873726,\n 1.52417061939353303183354859367,\n 2.04923170985061937575050838669,\n 2.59113378979454256492128084112,\n 3.15784881834760228184318034120,\n 3.76218735196402009751489394104,\n 4.42853280660377943723498532226,\n 5.22027169053748216460967142500,\n 0.245340708300901249903836530634,\n 0.737473728545394358705605144252,\n 1.23407621539532300788581834696,\n 1.73853771211658620678086566214,\n 2.25497400208927552308233334473,\n 2.78880605842813048052503375640,\n 3.34785456738321632691492452300,\n 3.94476404011562521037562880052,\n 4.60368244955074427307767524898,\n 5.38748089001123286201690041068\n};\n\n/* Computes the s-th zero the physicists' Hermite polynomial of order n, thus also the s-th zero of the Hermite function of order n.\nA Newton iteration using a continued fraction representation adapted from [E.T. Whittaker (1914), On the continued fractions which represent the functions of Hermite and other functions defined by differential equations, Proceedings of the Edinburgh Mathematical Society, 32, 65-74] is performed with the initial approximation from [Arpad Elbert and Martin E. Muldoon, Approximations for zeros of Hermite functions, pp. 117-126 in D. Dominici and R. S. Maier, eds, \"Special Functions and Orthogonal Polynomials\", Contemporary Mathematics, vol 471 (2008)] refined via the bisection method. */\nint\ngsl_sf_hermite_phys_zero_e(const int n, const int s, gsl_sf_result * result)\n{\n if(n <= 0 || s < 0 || s > n/2) {\n DOMAIN_ERROR(result);\n }\n else if(s == 0) {\n if (GSL_IS_ODD(n) == 1) {\n result->val = 0.;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else {\n DOMAIN_ERROR(result);\n }\n }\n else if(n == 2) {\n result->val = M_SQRT1_2;\n result->err = 0.;\n return GSL_SUCCESS;\n }\n else if(n < 21) {\n result->val = H_zero_tab[(GSL_IS_ODD(n)?n/2:0)+((n/2)*(n/2-1))+s-2];\n result->err = GSL_DBL_EPSILON*(result->val);\n return GSL_SUCCESS;\n }\n else {\n double d = 1., x = 1., x0 = 1.;\n int j;\n x = H_zero_init(n,s);\n do {\n x0 = x;\n d = 0.;\n for (j=1; jval = x;\n result->err = 2*GSL_DBL_EPSILON*x + fabs(x-x0);\n return GSL_SUCCESS;\n }\n}\n\ndouble\ngsl_sf_hermite_phys_zero(const int n, const int s)\n{\n EVAL_RESULT(gsl_sf_hermite_phys_zero_e(n, s, &result));\n}\n\nint\ngsl_sf_hermite_func_zero_e(const int n, const int s, gsl_sf_result * result)\n{\n return gsl_sf_hermite_phys_zero_e(n, s, result);\n}\n\ndouble\ngsl_sf_hermite_func_zero(const int n, const int s)\n{\n EVAL_RESULT(gsl_sf_hermite_func_zero_e(n, s, &result));\n}\n", "meta": {"hexsha": "cbf5503b7bf5aca6d45a7e24ffd32318cd7d2b75", "size": 52955, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/specfunc/hermite.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/hermite.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/specfunc/hermite.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5837988827, "max_line_length": 591, "alphanum_fraction": 0.6215843641, "num_tokens": 20301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.5763384780079684}} {"text": "#ifndef COSMOLOGY_H\n#define COSMOLOGY_H\n\n#include \n//nbody code\n#include \n#include \n//gsl code\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Math;\n\nnamespace Cosmology\n{\n //scale factor function\n Double_t ScaleFactorFunc(const Double_t a, const Double_t om, const Double_t xla);\n //{return 1/sqrt(1.+om*(1./a-1.)+xla*(pow(a,2.0)-1.));};\n\n //Hubble expansion factor, omegak is diff omega m omegala\n Double_t HubbleFunc(const Double_t a, const Double_t Ho, const Double_t om, const Double_t ola);\n //Generalized Hubble expansion factor with omega_r=0 and omega_k specified\n Double_t HubbleFunc(const Double_t a, const Double_t Ho, const Double_t om, const Double_t ode, const Double_t ok, Double_t alpha=0.0, Double_t wde=-1.0);\n\n\t//wrapper for integration\t\n/*\tDouble_t HubbleIntFunc(Double_t a, void* params);\n\tdouble HubbleIntFuncGSL(double a, void* params);\n\tdouble HubbleIntFuncGSLMonte(double a, size_t dim, void* params);\n\n\t//wrapper for integration of 1/aH for time calculation.\n\tDouble_t aHIntFunc(Double_t a, void* params);\n\tdouble aHIntFuncGSL(double a, void* params);\n\tdouble* aHIntFuncGSLMonte(double a, size_t dim, void* params);\n*/\n //Evaluates the time t (in units of t0) and Hubble parameter (units 1/t0)\n //given the expansion factor a (=1 at t=1)\n //for cosmological parameters omega0 and lambda0 (evaluated at t=1).\n Double_t Timet(const Double_t a, const Double_t om, const Double_t ola);\n Double_t Timeh(const Double_t a, const Double_t om, const Double_t ola);\n\n //Growth factor\n Double_t GrowthFunc(const Double_t a, const Double_t om, const Double_t ola);\n Double_t GrowthFunc(const Double_t a, const Double_t Ho, const Double_t om, const Double_t ode, const Double_t ok, Double_t alpha=0.0, Double_t wde=-1.0);\n\n\t//window function\n\tDouble_t WKR2(const Double_t k, const Double_t R);\n\n\t//Power Spectra\n\tDouble_t PK(const Double_t k, const Double_t ns, const Double_t Amp);\n\t//----Based on Bardeen et al 1986 BBKS\n\t//qBBKS\n\tDouble_t qBBSK(const Double_t k, const Double_t ns, const Double_t Omegam, const Double_t h, const Double_t Omegab);\n\tDouble_t TBBKS(const Double_t k, const Double_t ns, const Double_t Omegam, const Double_t h, const Double_t Omegab);\n\t//PBBSK here k is in Mpc^-1\n\tDouble_t PBBKS(const Double_t k, const Double_t ns, const Double_t Amp, const Double_t Omegam, const Double_t h, const Double_t Omegab=0.);\n\n\t//----Based on Eisenstien and Hu 1998\n\t//q98\n\tDouble_t qEH98(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);\n\t//L98\n\tDouble_t LEH98(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);\n\t//C98\n\tDouble_t CEH98(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);\n\t//T98\n\tDouble_t TEH98(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);\n\t//P98 here k is in Mpc^-1. \n\tDouble_t PEH98(const Double_t k, const Double_t ns, const Double_t deltaH, const Double_t clight, const Double_t Ho, const Double_t Omegam, const Double_t h, const Double_t Theta27);\n\t//P98 here k is in Mpc^-1, but just pass amplitude in \n\tDouble_t PEH98(const Double_t k, const Double_t ns, const Double_t Amp, const Double_t Omegam, const Double_t h, const Double_t Theta27);\n\t//----P98 with Warm Dark Matter dampenning like term, here k is in Mpc^-1. \n\tDouble_t PWDMEH98(const Double_t k, const Double_t ns, const Double_t AMP, const Double_t Omegam, const Double_t h, const Double_t Theta27, const Double_t Rd);\n\n\t//effective index in k units of Mpc^-1. neff =dlnP/dlnk\n\t//diff L98 by k\n\tDouble_t LEH98diff(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);\n\t//diff C98 by k\n\tDouble_t CEH98diff(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);\n\tDouble_t neffEH98(const Double_t k, const Double_t ns, const Double_t Omegam, const Double_t h, const Double_t Theta27);\n\t//----same as above but with Warm Dark Matter dampenning like term, here k is in Mpc^-1. \n\tDouble_t neffWDMEH98(const Double_t k, const Double_t ns, const Double_t Omegam, const Double_t h, const Double_t Theta27, const Double_t Rd);\n\n\n\t//----Based on preprint of Green et al 04 for zeq>>z>zb and k>kb, zb=150 and kb~1e3 Mpc^-1.\n\tDouble_t PGreen04(const Double_t k, const Double_t Amp, const Double_t wm);\n\n\t//----Based on data from a file not certain how to construct it yet (could use void * to store k and pk arrays.\n\tDouble_t PFromFile(const Double_t k, void* params);\n\n\t// For integrals, void params has form of params[0]=ns;params[1]=Amp;params[2]=Omegam;params[3]=h;\n\t// Must eventually alter so that Omega_Lambda is not assumed to be 1-Omegam\n\n\t//integrate P(k)k^2dk*4pi/(2pi)^3\n\tDouble_t IntegralkkPower(int powerspectype, void *params, int itype=0, bool logint=true);\n\n\t//integrate W^2(kR)P(k)k^2dk*4pi/(2pi)^3\n\tDouble_t IntegralSigma(int powerspectype, Double_t R, void *params, int itype=0, bool logint=true);\n\n //-------------------------------------------------------------------\n // Does open-ended romberg integration of the scale factor integral from a1 to a2\n // Based on a Numerical Recipes routine\n Double_t aintegral(const Double_t a1,const Double_t a2, const Double_t omega, const Double_t xlambda); \n \n} \n\n#endif\n", "meta": {"hexsha": "998d1c54be404773d948e8935d738e49b39e46b6", "size": 5469, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Cosmology/Cosmology.h", "max_stars_repo_name": "ICRAR/NBodylib", "max_stars_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "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/Cosmology/Cosmology.h", "max_issues_repo_name": "ICRAR/NBodylib", "max_issues_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-05-21T16:49:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T06:31:03.000Z", "max_forks_repo_path": "src/Cosmology/Cosmology.h", "max_forks_repo_name": "ICRAR/NBodylib", "max_forks_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-04-23T02:58:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T00:21:57.000Z", "avg_line_length": 49.7181818182, "max_line_length": 183, "alphanum_fraction": 0.7388919364, "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5762902602491635}} {"text": "/// \\file angles.c\n/// \\brief Optimize polar angles with respect to Coulomb repulsion, given the radii.\n//\n//\tCopyright (c) 2014, Christian B. Mendl\n//\tAll rights reserved.\n//\thttp://christian.mendl.net\n//\n//\tThis program is free software; you can redistribute it and/or\n//\tmodify it under the terms of the Simplified BSD License\n//\thttp://www.opensource.org/licenses/bsd-license.php\n//\n//\tReference:\n//\t Christian B. Mendl, Francesc Malet, Paola Gori-Giorgi\n//\t Wigner localization in quantum dots from Kohn-Sham density functional theory without symmetry breaking\n//\t Physical Review B 89, 125106 (2014)\n//\t (preprint http://arxiv.org/abs/1311.6011)\n//_______________________________________________________________________________________________________________________\n//\n\n#include \"angles.h\"\n#include \"coulomb.h\"\n#include \"util.h\"\n#define _USE_MATH_DEFINES\n#include \n#include \n#include \n#include \n#include \n#include \n// LAPACK functions\n#include \n// GSL library\n#include \n#include \n\n\nstatic const int maxiter\t\t= 64;\t\t\t//!< maximum number of iterations for local angle optimization\nstatic const double step_size\t= 0.01;\t\t\t//!< step size for angle optimization\n\n\n//_______________________________________________________________________________________________________________________\n//\n// GSL wrappers of Vee() for local minimization\n\n/// \\brief GSL parameters for angle optimization\ntypedef struct\n{\n\tdouble phi0;\n\tconst double *r;\n}\ngsl_angle_params_t;\n\n\n/// \\brief GSL wrapper for Vee()\nstatic double gslVee(const gsl_vector *phiRest, void *p)\n{\n\tint i;\n\tconst gsl_angle_params_t *params = (gsl_angle_params_t *)p;\n\tdouble v_val;\n\n\t// first angle is held fixed\n\tconst int nelec = (int)phiRest->size + 1;\n\n\tdouble *phi = (double *)malloc(nelec*sizeof(double));\n\tphi[0] = params->phi0;\n\tfor (i = 1; i < nelec; i++) {\n\t\tphi[i] = gsl_vector_get(phiRest, i-1);\n\t}\n\n\tv_val = Vee(nelec, params->r, phi);\n\n\tfree(phi);\n\n\treturn v_val;\n}\n\n/// \\brief GSL wrapper for VeeGradPhi()\nstatic void gslVeeGradPhi(const gsl_vector *phiRest, void *p, gsl_vector *df)\n{\n\tint i;\n\tconst gsl_angle_params_t *params = (gsl_angle_params_t *)p;\n\tdouble *grad;\n\n\t// first angle is held fixed\n\tconst int nelec = (int)phiRest->size + 1;\n\n\tdouble *phi = (double *)malloc(nelec*sizeof(double));\n\tphi[0] = params->phi0;\n\tfor (i = 1; i < nelec; i++) {\n\t\tphi[i] = gsl_vector_get(phiRest, i-1);\n\t}\n\n\tgrad = (double *)malloc(nelec*sizeof(double));\n\n\t// calculate gradient\n\tVeeGradPhi(nelec, params->r, phi, grad);\n\n\t// ignore derivative with respect to first angle (held fixed)\n\tfor (i = 1; i < nelec; i++) {\n\t\tgsl_vector_set(df, i-1, grad[i]);\n\t}\n\n\tfree(grad);\n\tfree(phi);\n}\n\n/// \\brief GSL wrapper for both 'Vee()' and 'VeeGradPhi()' together\nstatic void gslVeeValGradPhi(const gsl_vector *phiRest, void *p, double *f, gsl_vector *df)\n{\n\tint i;\n\tconst gsl_angle_params_t *params = (gsl_angle_params_t *)p;\n\tdouble *phi;\n\tdouble *grad;\n\n\t// first angle is held fixed\n\tconst int nelec = (int)phiRest->size + 1;\n\n\tphi = (double *)malloc(nelec*sizeof(double));\n\tphi[0] = params->phi0;\n\tfor (i = 1; i < nelec; i++) {\n\t\tphi[i] = gsl_vector_get(phiRest, i-1);\n\t}\n\n\t*f = Vee(nelec, params->r, phi);\n\n\tgrad = (double *)malloc(nelec*sizeof(double));\n\n\t// calculate gradient\n\tVeeGradPhi(nelec, params->r, phi, grad);\n\n\t// ignore derivative with respect to first angle (which is held fixed)\n\tfor (i = 1; i < nelec; i++) {\n\t\tgsl_vector_set(df, i-1, grad[i]);\n\t}\n\n\tfree(grad);\n\tfree(phi);\n}\n\n\n//_______________________________________________________________________________________________________________________\n///\n/// \\brief Optimize polar angles with respect to Coulomb repulsion, given the radii\n///\n/// \\param nelec number of electrons\n/// \\param r radii, array of length 'nelec'\n/// \\param phi serves as input (starting values) and output (optimized angles); array of length 'nelec';\n/// phi[0] is not changed due to invariance under global rotation\n///\n/// \\return detailed error description, if any\n///\nerror_desc_t OptimizeAngles(const int nelec, const double *r, double *phi)\n{\n\tint i, j, k;\n\terror_desc_t err = { 0 };\n\tint status;\n\n\t// tolerance for convergence test based on gradient\n\tconst double tol = nelec < 7 ? 1e-12 : 1e-10;\n\n\tconst gsl_multimin_fdfminimizer_type *T = gsl_multimin_fdfminimizer_vector_bfgs2;\t// alternative: gsl_multimin_fdfminimizer_conjugate_fr\n\tgsl_multimin_fdfminimizer *s = gsl_multimin_fdfminimizer_alloc(T, nelec-1);\n\n\tgsl_angle_params_t params;\n\tparams.phi0 = phi[0];\n\tparams.r = r;\n\n\tgsl_multimin_function_fdf my_func;\n\tmy_func.n = nelec-1;\n\tmy_func.f = gslVee;\n\tmy_func.df = gslVeeGradPhi;\n\tmy_func.fdf = gslVeeValGradPhi;\n\tmy_func.params = ¶ms;\n\n\t// starting point\n\t// omit first angle phi[0]\n\tgsl_vector *x = gsl_vector_alloc(nelec-1);\n\tfor (i = 1; i < nelec; i++) {\n\t\tgsl_vector_set(x, i-1, phi[i]);\n\t}\n\n\tgsl_multimin_fdfminimizer_set(s, &my_func, x, step_size, 0.1);\n\n\tfor (k = 0; k < maxiter; k++)\n\t{\n\t\tstatus = gsl_multimin_fdfminimizer_iterate(s);\n\n\t\t// interval [-pi, pi]\n\t\tfor (i = 0; i < nelec-1; i++)\n\t\t{\n\t\t\tdouble curphi = gsl_vector_get(s->x, i);\n\t\t\tassert(!isinf(curphi));\n\n\t\t\tif (curphi < -M_PI)\t\t// using \"if\" instead of \"while\" to avoid infinite loop if curphi is +-1.#INF\n\t\t\t{\n\t\t\t\tcurphi += 2*M_PI;\n\t\t\t}\n\t\t\telse if (curphi > M_PI)\n\t\t\t{\n\t\t\t\tcurphi -= 2*M_PI;\n\t\t\t}\n\n\t\t\tgsl_vector_set(s->x, i, curphi);\n\t\t}\n\n\t\t// check status\n\t\tif (status != 0) {\n\t\t\terr.codes |= E_ITERATION;\n\t\t\terr.msg = gsl_strerror(status);\n\t\t\tfprintf(stderr, \"Warning: 'gsl_multimin_fdfminimizer_iterate' failed at iteration %i, error: %s.\\n\", k, err.msg);\n\t\t\tbreak;\n\t\t}\n\n\t\t// convergence test\n\t\tstatus = gsl_multimin_test_gradient(s->gradient, tol);\n\t\tif (status == GSL_SUCCESS) {\n\t\t\tprintf(\"'gsl_multimin_test_gradient()' successful.\\n\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// norm of gradient\n\tdouble delta = 0;\n\tfor (i = 0; i < nelec-1; i++)\n\t{\n\t\tdelta += square(gsl_vector_get(s->gradient, i));\n\t}\n\t// 2-norm\n\tdelta = sqrt(delta);\n\tprintf(\"final delta: %g\\n\", delta);\n\n\tif (k == maxiter)\n\t{\n\t\tfprintf(stderr, \"Warning: 'OptimizeAngles' did not converge within %i iterations, final delta: %g.\\n\", maxiter, delta);\n\t\terr.codes |= E_CONVERGENCE;\n\t\terr.conv_delta = delta;\n\t}\n\n\t// copy values back\n\tfor (i = 1; i < nelec; i++) {\n\t\tphi[i] = gsl_vector_get(s->x, i-1);\n\t}\n\n\tgsl_multimin_fdfminimizer_free(s);\n\tgsl_vector_free(x);\n\n\n\t// consistency check: all eigenvalues of Hessian matrix should be non-negative\n\t{\n\t\tdouble *hessfull = (double *)malloc(nelec*nelec*sizeof(double));\n\t\tdouble *hesssubm = (double *)malloc((nelec-1)*(nelec-1)*sizeof(double));\n\t\tdouble *eigenval = (double *)malloc((nelec-1)*sizeof(double));\n\n\t\t// calculate Hessian matrix\n\t\tVeeHessPhi(nelec, r, phi, hessfull);\n\t\t// omit first row and column in Hessian matrix since phi[0] is fixed\n\t\tfor (j = 1; j < nelec; j++)\n\t\t{\n\t\t\tfor (i = 1; i < nelec; i++)\n\t\t\t{\n\t\t\t\thesssubm[(i-1)+(j-1)*(nelec-1)] = hessfull[i+j*nelec];\n\t\t\t}\n\t\t}\n\t\t// calculate eigenvalues\n\t\tdsyev('N', 'U', nelec-1, hesssubm, nelec-1, eigenval, &status);\n\t\t// check for errors\n\t\tif (status != 0) {\n\t\t\tfprintf(stderr, \"Warning: 'dsyev' failed, info: %i\\n\", status);\n\t\t\terr.codes |= E_LAPACK;\n\t\t}\n\t\tif (eigenval[0] < 0) {\n\t\t\tfprintf(stderr, \"Warning: Hessian has negative eigenvalue %g.\\n\", eigenval[0]);\n\t\t\terr.codes |= E_NEG_HESS;\n\t\t\terr.hess_eig = eigenval[0];\n\t\t}\n\n\t\tfree(eigenval);\n\t\tfree(hesssubm);\n\t\tfree(hessfull);\n\t}\n\n\treturn err;\n}\n\n\n//_______________________________________________________________________________________________________________________\n///\n/// \\brief Perform a global optimization of the polar angles with respect to Coulomb repulsion, given the radii\n///\n/// \\param nelec number of electrons\n/// \\param r radii, array of length 'nelec'\n/// \\param phi serves as input (starting values) and output (optimized angles); array of length 'nelec';\n/// phi[0] is not changed due to invariance under global rotation\n/// \\param optVee optimized Coulomb repulsion (output)\n/// \\return detailed error description, if any\n///\nerror_desc_t OptimizeAnglesGlobal(const int nelec, const double *r, double *phi, double *optVee)\n{\n\tint i, k, l;\n\n\terror_desc_t err = OptimizeAngles(nelec, r, phi);\n\n\t// temporary storage for angles\n\tdouble *chi\t= (double *)malloc(nelec*sizeof(double));\n\n\t// try permuting angles to find minimum value\n\t(*optVee) = Vee(nelec, r, phi);\n\tfor (i = 0; i < 32; i++)\t\t// iterate several times\n\t{\n\t\t// for all pairs of electrons...\n\t\tfor (l = 1; l < nelec; l++)\t\t// angle of first electron always zero\n\t\t{\n\t\t\tfor (k = 1; k < l; k++)\n\t\t\t{\n\t\t\t\tdouble curV;\n\n\t\t\t\tmemcpy(chi, phi, nelec*sizeof(double));\n\t\t\t\t// permute k <-> l\n\t\t\t\tchi[k] = phi[l];\n\t\t\t\tchi[l] = phi[k];\n\t\t\t\terror_desc_t cur_err = OptimizeAngles(nelec, r, chi);\n\n\t\t\t\tcurV = Vee(nelec, r, chi);\n\t\t\t\tif (curV < (*optVee))\n\t\t\t\t{\n\t\t\t\t\t// only accumulate error if we really use the optimized angles\n\t\t\t\t\tAccumulateError(&err, &cur_err);\n\n\t\t\t\t\t// save values\n\t\t\t\t\tmemcpy(phi, chi, nelec*sizeof(double));\n\t\t\t\t\t(*optVee) = curV;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// clean up\n\tfree(chi);\n\n\treturn err;\n}\n\n\n/*\n//_______________________________________________________________________________________________________________________\n//\n// GSL wrappers of Vee() for global minimization by simulated annealing\n\n\ntypedef struct\n{\n\tint nelec;\n\tconst double *r;\n\tdouble phi[10];\n}\nsaConfig_t;\n\n\nstatic double saVee(void *xp)\n{\n\tconst saConfig_t *x = (saConfig_t *)xp;\n\n\treturn Vee(x->nelec, x->r, x->phi);\n}\n\n\nstatic void saStep(const gsl_rng *randgen, void *xp, double step_size)\n{\n\tint i;\n\tsaConfig_t *x = (saConfig_t *)xp;\n\n\t// first angle always fixed\n\tfor (i = 1; i < x->nelec; i++)\n\t{\n\t\tdouble u = gsl_rng_uniform(randgen);\n\t\tx->phi[i] += step_size * (u - 0.5);\t\t// divide by nelec ?\n\n\t\t// [-pi,pi] range\n\t\tif (x->phi[i] < -M_PI)\n\t\t{\n\t\t\tx->phi[i] += 2*M_PI;\n\t\t}\n\t\telse if (x->phi[i] > M_PI)\n\t\t{\n\t\t\tx->phi[i] -= 2*M_PI;\n\t\t}\n\t}\n}\n\n\nstatic double saDistance(void *xp, void *yp)\n{\n\tint i;\n\n\tconst saConfig_t *x = (saConfig_t *)xp;\n\tconst saConfig_t *y = (saConfig_t *)yp;\n\n\t// distance between angles\n\tdouble dphi[10];\n\tfor (i = 0; i < x->nelec; i++)\n\t{\n\t\tdphi[i] = x->phi[i] - y->phi[i];\n\n\t\t// [-pi,pi] range\n\t\tif (dphi[i] < -M_PI)\n\t\t{\n\t\t\tdphi[i] += 2*M_PI;\n\t\t}\n\t\telse if (dphi[i] > M_PI)\n\t\t{\n\t\t\tdphi[i] -= 2*M_PI;\n\t\t}\n\t}\n\n\tassert(x->nelec == y->nelec);\n\n\treturn Norm(dphi + 1, x->nelec - 1);\t// skip first angle (always held fixed)\n}\n\n\nstatic void saPrint(void *xp)\n{\n\tint i;\n\tconst saConfig_t *x = (saConfig_t *)xp;\n\t\n\tprintf(\" angles phi: \");\n\tfor (i = 0; i < x->nelec; i++) {\n\t\tprintf(\"%f \", x->phi[i]);\n\t}\n}\n\n\n//_______________________________________________________________________________________________________________________\n///\n/// \\brief Globally optimize polar angles with respect to Coulomb repulsion, given the radii\n///\n/// \\param nelec number of electrons\n/// \\param r radii, array of length 'nelec'\n/// \\param phi serves as input (starting values) and output (optimized angles); array of length 'nelec';\n/// phi[0] is not changed due to invariance under global rotation\n///\n/// \\return detailed error description, if any\n///\nerror_desc_t OptimizeAnglesGlobal(const int nelec, const double *r, double *phi)\n{\n\tconst gsl_rng_type *T;\n\tgsl_rng *randgen;\n\n\tgsl_siman_params_t params;\n\n\terror_desc_t err = { 0 };\n\n\t// initial configuration\n\tsaConfig_t config;\n\tconfig.nelec = nelec;\n\tconfig.r = r;\n\tmemcpy(config.phi, phi, nelec*sizeof(double));\n\n\tgsl_rng_env_setup();\n\n\t// random number generator\n\tT = gsl_rng_default;\n\trandgen = gsl_rng_alloc(T);\n\n\t// parameters\n\tparams.n_tries\t\t\t= 200;\t\t\t\t// how many points do we try before stepping\n\tparams.iters_fixed_T\t= 1000;\t\t\t\t// how many iterations for each T?\n\tparams.step_size\t\t= 0.01 * M_PI;\t\t// max step size in random walk\n\tparams.k\t\t\t\t= 1.0;\t\t\t\t// virtual Boltzmann constant\n\tparams.t_initial\t\t= 0.001;\t\t\t// initial temperature\n\tparams.mu_t\t\t\t\t= 1.004;\t\t\t// damping factor for temperature\n\tparams.t_min\t\t\t= 2.0e-7;\t\t\t// minimum temperature\n\n\tgsl_siman_solve(randgen, &config, saVee, saStep, saDistance, saPrint, NULL, NULL, NULL, sizeof(saConfig_t), params);\n\n\t// first angle must not change\n\tassert(config.phi[0] == phi[0]);\n\n\t// store optimized angles in 'phi'\n\tmemcpy(phi, config.phi, nelec*sizeof(double));\n\n\t// clean up\n\tgsl_rng_free(randgen);\n\n\n\t// consistency check: all eigenvalues of Hessian matrix should be non-negative\n\t{\n\t\tint i, j;\n\t\tint status;\n\t\tdouble *hessfull = (double *)malloc(nelec*nelec*sizeof(double));\n\t\tdouble *hesssubm = (double *)malloc((nelec-1)*(nelec-1)*sizeof(double));\n\t\tdouble *eigenval = (double *)malloc((nelec-1)*sizeof(double));\n\n\t\t// calculate Hessian matrix\n\t\tVeeHessPhi(nelec, r, phi, hessfull);\n\t\t// omit first row and column in Hessian matrix since phi[0] is fixed\n\t\tfor (j = 1; j < nelec; j++)\n\t\t{\n\t\t\tfor (i = 1; i < nelec; i++)\n\t\t\t{\n\t\t\t\thesssubm[(i-1)+(j-1)*(nelec-1)] = hessfull[i+j*nelec];\n\t\t\t}\n\t\t}\n\t\t// calculate eigenvalues\n\t\tdsyev('N', 'U', nelec-1, hesssubm, nelec-1, eigenval, &status);\n\t\t// check for errors\n\t\tif (status != 0) {\n\t\t\tfprintf(stderr, \"Warning: 'dsyev' failed, info: %i\\n\", status);\n\t\t\terr.codes |= E_LAPACK;\n\t\t}\n\t\tif (eigenval[0] < 0) {\n\t\t\tfprintf(stderr, \"Warning: Hessian has negative eigenvalue %g.\\n\", eigenval[0]);\n\t\t\terr.codes |= E_NEG_HESS;\n\t\t\terr.hess_eig = eigenval[0];\n\t\t}\n\n\t\tfree(eigenval);\n\t\tfree(hesssubm);\n\t\tfree(hessfull);\n\t}\n\n\treturn err;\n}\n*/", "meta": {"hexsha": "d7550bc1251ce5a95a9198891d1d60c017c6f89d", "size": 13409, "ext": "c", "lang": "C", "max_stars_repo_path": "src/angles.c", "max_stars_repo_name": "Arfaouim/quantum-dot", "max_stars_repo_head_hexsha": "f149e1d6684ea321b62710638f153d3dce196ca2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T13:59:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T13:59:40.000Z", "max_issues_repo_path": "src/angles.c", "max_issues_repo_name": "Arfaouim/quantum-dot", "max_issues_repo_head_hexsha": "f149e1d6684ea321b62710638f153d3dce196ca2", "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/angles.c", "max_forks_repo_name": "Arfaouim/quantum-dot", "max_forks_repo_head_hexsha": "f149e1d6684ea321b62710638f153d3dce196ca2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-26T21:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T22:00:35.000Z", "avg_line_length": 25.5896946565, "max_line_length": 137, "alphanum_fraction": 0.6726825267, "num_tokens": 4098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.5762682570019941}} {"text": "//IN method.\n//Affine transformation (weights and biases) of Ni inputs to No outputs.\n//This version uses CBLAS.\n\n//Input X has Ni neurons and output Y has No neurons.\n//Each output neuron has a bias term, so B is a vector of length No.\n\n//The vecs of length Ni are always contiguous in memory, such that:\n\n//If col-major: Y[:,l] = W' * X[:,l] + B\n//where:\n//X has size Ni x L\n//Y has size No x L\n//W has size Ni x No\n//B has size No x 1\n\n//If row-major: Y[l,:] = X[l,:] * W' + B\n//X has size L x Ni\n//Y has size L x No\n//W has size No x Ni\n//B has size 1 x No\n\n//For a different set-up that allows affine transformation of vecs in\n//any orientation, use the affine function from math.\n\n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint affine_cblas_s (float *Y, const float *X, const float *W, const float *B, const size_t Ni, const size_t No, const size_t L);\nint affine_cblas_d (double *Y, const double *X, const double *W, const double *B, const size_t Ni, const size_t No, const size_t L);\nint affine_cblas_c (float *Y, const float *X, const float *W, const float *B, const size_t Ni, const size_t No, const size_t L);\nint affine_cblas_z (double *Y, const double *X, const double *W, const double *B, const size_t Ni, const size_t No, const size_t L);\n\n\nint affine_cblas_s (float *Y, const float *X, const float *W, const float *B, const size_t Ni, const size_t No, const size_t L)\n{\n for (size_t l=L; l>0u; --l, X+=Ni, Y+=No)\n {\n cblas_scopy((int)No,B,1,Y,1);\n cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,1.0f,W,(int)Ni,X,1,1.0f,Y,1);\n }\n\n return 0;\n}\n\n\nint affine_cblas_d (double *Y, const double *X, const double *W, const double *B, const size_t Ni, const size_t No, const size_t L)\n{\n for (size_t l=L; l>0u; --l, X+=Ni, Y+=No)\n {\n cblas_dcopy((int)No,B,1,Y,1);\n cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,1.0,W,(int)Ni,X,1,1.0,Y,1);\n }\n\n return 0;\n}\n\n\nint affine_cblas_c (float *Y, const float *X, const float *W, const float *B, const size_t Ni, const size_t No, const size_t L)\n{\n const float o[2] = {1.0f,0.0f};\n\n for (size_t l=L; l>0u; --l, X+=2u*Ni, Y+=2u*No)\n {\n cblas_ccopy((int)No,B,1,Y,1);\n cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,o,W,(int)Ni,X,1,o,Y,1);\n }\n\n return 0;\n}\n\n\nint affine_cblas_z (double *Y, const double *X, const double *W, const double *B, const size_t Ni, const size_t No, const size_t L)\n{\n const double o[2] = {1.0,0.0};\n\n for (size_t l=L; l>0u; --l, X+=2u*Ni, Y+=2u*No)\n {\n cblas_zcopy((int)No,B,1,Y,1);\n cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,o,W,(int)Ni,X,1,o,Y,1);\n }\n\n return 0;\n}\n\n\n#ifdef __cplusplus\n}\n}\n#endif\n", "meta": {"hexsha": "28fc7e916d6ff70ebb04e0ff9a8596d8f07f6b7b", "size": 2752, "ext": "c", "lang": "C", "max_stars_repo_path": "c/affine.cblas.c", "max_stars_repo_name": "erikedwards4/nn", "max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z", "max_issues_repo_path": "c/affine.cblas.c", "max_issues_repo_name": "erikedwards4/nn", "max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "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": "c/affine.cblas.c", "max_forks_repo_name": "erikedwards4/nn", "max_forks_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9684210526, "max_line_length": 132, "alphanum_fraction": 0.6457122093, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5762682351386913}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n/* parameters to model */\nstruct model_params\n{\n double a1;\n double a2;\n double a3;\n double a4;\n double a5;\n};\n\n/* Branin function */\nint\nfunc_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n struct model_params *par = (struct model_params *) params;\n double x1 = gsl_vector_get(x, 0);\n double x2 = gsl_vector_get(x, 1);\n double f1 = x2 + par->a1 * x1 * x1 + par->a2 * x1 + par->a3;\n double f2 = sqrt(par->a4) * sqrt(1.0 + (1.0 - par->a5) * cos(x1));\n\n gsl_vector_set(f, 0, f1);\n gsl_vector_set(f, 1, f2);\n\n return GSL_SUCCESS;\n}\n\nint\nfunc_df (const gsl_vector * x, void *params, gsl_matrix * J)\n{\n struct model_params *par = (struct model_params *) params;\n double x1 = gsl_vector_get(x, 0);\n double f2 = sqrt(par->a4) * sqrt(1.0 + (1.0 - par->a5) * cos(x1));\n\n gsl_matrix_set(J, 0, 0, 2.0 * par->a1 * x1 + par->a2);\n gsl_matrix_set(J, 0, 1, 1.0);\n\n gsl_matrix_set(J, 1, 0, -0.5 * par->a4 / f2 * (1.0 - par->a5) * sin(x1));\n gsl_matrix_set(J, 1, 1, 0.0);\n\n return GSL_SUCCESS;\n}\n\nint\nfunc_fvv (const gsl_vector * x, const gsl_vector * v,\n void *params, gsl_vector * fvv)\n{\n struct model_params *par = (struct model_params *) params;\n double x1 = gsl_vector_get(x, 0);\n double v1 = gsl_vector_get(v, 0);\n double c = cos(x1);\n double s = sin(x1);\n double f2 = sqrt(par->a4) * sqrt(1.0 + (1.0 - par->a5) * c);\n double t = 0.5 * par->a4 * (1.0 - par->a5) / f2;\n\n gsl_vector_set(fvv, 0, 2.0 * par->a1 * v1 * v1);\n gsl_vector_set(fvv, 1, -t * (c + s*s/f2) * v1 * v1);\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 * x = gsl_multifit_nlinear_position(w);\n double x1 = gsl_vector_get(x, 0);\n double x2 = gsl_vector_get(x, 1);\n\n /* print out current location */\n printf(\"%f %f\\n\", x1, x2);\n}\n\nvoid\nsolve_system(gsl_vector *x0, gsl_multifit_nlinear_fdf *fdf,\n gsl_multifit_nlinear_parameters *params)\n{\n const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust;\n const size_t max_iter = 200;\n const double xtol = 1.0e-8;\n const double gtol = 1.0e-8;\n const double ftol = 1.0e-8;\n const size_t n = fdf->n;\n const size_t p = fdf->p;\n gsl_multifit_nlinear_workspace *work =\n gsl_multifit_nlinear_alloc(T, params, n, p);\n gsl_vector * f = gsl_multifit_nlinear_residual(work);\n gsl_vector * x = gsl_multifit_nlinear_position(work);\n int info;\n double chisq0, chisq, rcond;\n\n printf(\"# %s/%s\\n\",\n gsl_multifit_nlinear_name(work),\n gsl_multifit_nlinear_trs_name(work));\n\n /* initialize solver */\n gsl_multifit_nlinear_init(x0, fdf, work);\n\n /* store initial cost */\n gsl_blas_ddot(f, f, &chisq0);\n\n /* iterate until convergence */\n gsl_multifit_nlinear_driver(max_iter, xtol, gtol, ftol,\n callback, NULL, &info, work);\n\n /* store final cost */\n gsl_blas_ddot(f, f, &chisq);\n\n /* store cond(J(x)) */\n gsl_multifit_nlinear_rcond(&rcond, work);\n\n /* print summary */\n fprintf(stderr, \"%-25s %-6zu %-5zu %-5zu %-13.4e %-12.4e %-13.4e (%.2e, %.2e)\\n\",\n gsl_multifit_nlinear_trs_name(work),\n gsl_multifit_nlinear_niter(work),\n fdf->nevalf,\n fdf->nevaldf,\n chisq0,\n chisq,\n 1.0 / rcond,\n gsl_vector_get(x, 0),\n gsl_vector_get(x, 1));\n\n printf(\"\\n\\n\");\n\n gsl_multifit_nlinear_free(work);\n}\n\nint\nmain (void)\n{\n const size_t n = 2;\n const size_t p = 2;\n gsl_vector *f = gsl_vector_alloc(n);\n gsl_vector *x = gsl_vector_alloc(p);\n gsl_multifit_nlinear_fdf fdf;\n gsl_multifit_nlinear_parameters fdf_params =\n gsl_multifit_nlinear_default_parameters();\n struct model_params params;\n\n params.a1 = -5.1 / (4.0 * M_PI * M_PI);\n params.a2 = 5.0 / M_PI;\n params.a3 = -6.0;\n params.a4 = 10.0;\n params.a5 = 1.0 / (8.0 * M_PI);\n\n /* print map of Phi(x1, x2) */\n {\n double x1, x2, chisq;\n\n for (x1 = -5.0; x1 < 15.0; x1 += 0.1)\n {\n for (x2 = -5.0; x2 < 15.0; x2 += 0.1)\n {\n gsl_vector_set(x, 0, x1);\n gsl_vector_set(x, 1, x2);\n func_f(x, ¶ms, f);\n\n gsl_blas_ddot(f, f, &chisq);\n\n printf(\"%f %f %f\\n\", x1, x2, chisq);\n }\n printf(\"\\n\");\n }\n printf(\"\\n\\n\");\n }\n\n /* define function to be minimized */\n fdf.f = func_f;\n fdf.df = func_df;\n fdf.fvv = func_fvv;\n fdf.n = n;\n fdf.p = p;\n fdf.params = ¶ms;\n\n /* starting point */\n gsl_vector_set(x, 0, 6.0);\n gsl_vector_set(x, 1, 14.5);\n\n fprintf(stderr, \"%-25s %-6s %-5s %-5s %-13s %-12s %-13s %-15s\\n\",\n \"Method\", \"NITER\", \"NFEV\", \"NJEV\", \"Initial Cost\",\n \"Final cost\", \"Final cond(J)\", \"Final x\");\n \n fdf_params.trs = gsl_multifit_nlinear_trs_lm;\n solve_system(x, &fdf, &fdf_params);\n\n fdf_params.trs = gsl_multifit_nlinear_trs_lmaccel;\n solve_system(x, &fdf, &fdf_params);\n\n fdf_params.trs = gsl_multifit_nlinear_trs_dogleg;\n solve_system(x, &fdf, &fdf_params);\n\n fdf_params.trs = gsl_multifit_nlinear_trs_ddogleg;\n solve_system(x, &fdf, &fdf_params);\n\n fdf_params.trs = gsl_multifit_nlinear_trs_subspace2D;\n solve_system(x, &fdf, &fdf_params);\n\n gsl_vector_free(f);\n gsl_vector_free(x);\n\n return 0;\n}\n", "meta": {"hexsha": "9dbf278372d284108daf4e2b3dbd6ec068f5fdcc", "size": 5363, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/nlfit3.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/nlfit3.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/nlfit3.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 25.5380952381, "max_line_length": 83, "alphanum_fraction": 0.6207346634, "num_tokens": 1891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5755314831046934}} {"text": "/**\n *\n * @generated c Tue Jan 7 11:45:26 2014\n *\n **/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"auxiliary.h\"\n\n/*-------------------------------------------------------------------\n * Check the orthogonality of Q\n */\n\nint c_check_orthogonality(int M, int N, int LDQ, PLASMA_Complex32_t *Q)\n{\n float alpha, beta;\n float normQ;\n int info_ortho;\n int i;\n int minMN = min(M, N);\n float eps;\n float *work = (float *)malloc(minMN*sizeof(float));\n\n eps = LAPACKE_slamch_work('e');\n alpha = 1.0;\n beta = -1.0;\n\n /* Build the idendity matrix USE DLASET?*/\n PLASMA_Complex32_t *Id = (PLASMA_Complex32_t *) malloc(minMN*minMN*sizeof(PLASMA_Complex32_t));\n memset((void*)Id, 0, minMN*minMN*sizeof(PLASMA_Complex32_t));\n for (i = 0; i < minMN; i++)\n Id[i*minMN+i] = (PLASMA_Complex32_t)1.0;\n\n /* Perform Id - Q'Q */\n if (M >= N)\n cblas_cherk(CblasColMajor, CblasUpper, CblasConjTrans, N, M, alpha, Q, LDQ, beta, Id, N);\n else\n cblas_cherk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, alpha, Q, LDQ, beta, Id, M);\n\n normQ = LAPACKE_clansy_work(LAPACK_COL_MAJOR, 'i', 'u', minMN, Id, minMN, work);\n\n printf(\"============\\n\");\n printf(\"Checking the orthogonality of Q \\n\");\n printf(\"||Id-Q'*Q||_oo / (N*eps) = %e \\n\",normQ/(minMN*eps));\n\n if ( isnan(normQ / (minMN * eps)) || (normQ / (minMN * eps) > 10.0) ) {\n printf(\"-- Orthogonality is suspicious ! \\n\");\n info_ortho=1;\n }\n else {\n printf(\"-- Orthogonality is CORRECT ! \\n\");\n info_ortho=0;\n }\n\n free(work); free(Id);\n\n return info_ortho;\n}\n\n/*------------------------------------------------------------\n * Check the factorization QR\n */\n\nint c_check_QRfactorization(int M, int N, PLASMA_Complex32_t *A1, PLASMA_Complex32_t *A2, int LDA, PLASMA_Complex32_t *Q)\n{\n float Anorm, Rnorm;\n PLASMA_Complex32_t alpha, beta;\n int info_factorization;\n int i,j;\n float eps;\n\n eps = LAPACKE_slamch_work('e');\n\n PLASMA_Complex32_t *Ql = (PLASMA_Complex32_t *)malloc(M*N*sizeof(PLASMA_Complex32_t));\n PLASMA_Complex32_t *Residual = (PLASMA_Complex32_t *)malloc(M*N*sizeof(PLASMA_Complex32_t));\n float *work = (float *)malloc(max(M,N)*sizeof(float));\n\n alpha=1.0;\n beta=0.0;\n\n if (M >= N) {\n /* Extract the R */\n PLASMA_Complex32_t *R = (PLASMA_Complex32_t *)malloc(N*N*sizeof(PLASMA_Complex32_t));\n memset((void*)R, 0, N*N*sizeof(PLASMA_Complex32_t));\n LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'u', M, N, A2, LDA, R, N);\n\n /* Perform Ql=Q*R */\n memset((void*)Ql, 0, M*N*sizeof(PLASMA_Complex32_t));\n cblas_cgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, N, CBLAS_SADDR(alpha), Q, LDA, R, N, CBLAS_SADDR(beta), Ql, M);\n free(R);\n }\n else {\n /* Extract the L */\n PLASMA_Complex32_t *L = (PLASMA_Complex32_t *)malloc(M*M*sizeof(PLASMA_Complex32_t));\n memset((void*)L, 0, M*M*sizeof(PLASMA_Complex32_t));\n LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'l', M, N, A2, LDA, L, M);\n\n /* Perform Ql=LQ */\n memset((void*)Ql, 0, M*N*sizeof(PLASMA_Complex32_t));\n cblas_cgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, M, CBLAS_SADDR(alpha), L, M, Q, LDA, CBLAS_SADDR(beta), Ql, M);\n free(L);\n }\n\n /* Compute the Residual */\n for (i = 0; i < M; i++)\n for (j = 0 ; j < N; j++)\n Residual[j*M+i] = A1[j*LDA+i]-Ql[j*M+i];\n\n Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, Residual, M, work);\n Anorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, A2, LDA, work);\n\n if (M >= N) {\n printf(\"============\\n\");\n printf(\"Checking the QR Factorization \\n\");\n printf(\"-- ||A-QR||_oo/(||A||_oo.N.eps) = %e \\n\",Rnorm/(Anorm*N*eps));\n }\n else {\n printf(\"============\\n\");\n printf(\"Checking the LQ Factorization \\n\");\n printf(\"-- ||A-LQ||_oo/(||A||_oo.N.eps) = %e \\n\",Rnorm/(Anorm*N*eps));\n }\n\n if (isnan(Rnorm / (Anorm * N *eps)) || (Rnorm / (Anorm * N * eps) > 10.0) ) {\n printf(\"-- Factorization is suspicious ! \\n\");\n info_factorization = 1;\n }\n else {\n printf(\"-- Factorization is CORRECT ! \\n\");\n info_factorization = 0;\n }\n\n free(work); free(Ql); free(Residual);\n\n return info_factorization;\n}\n\n/*------------------------------------------------------------------------\n * Check the factorization of the matrix A2\n */\n\nint c_check_LLTfactorization(int N, PLASMA_Complex32_t *A1, PLASMA_Complex32_t *A2, int LDA, int uplo)\n{\n float Anorm, Rnorm;\n PLASMA_Complex32_t alpha;\n int info_factorization;\n int i,j;\n float eps;\n\n eps = LAPACKE_slamch_work('e');\n\n PLASMA_Complex32_t *Residual = (PLASMA_Complex32_t *)malloc(N*N*sizeof(PLASMA_Complex32_t));\n PLASMA_Complex32_t *L1 = (PLASMA_Complex32_t *)malloc(N*N*sizeof(PLASMA_Complex32_t));\n PLASMA_Complex32_t *L2 = (PLASMA_Complex32_t *)malloc(N*N*sizeof(PLASMA_Complex32_t));\n float *work = (float *)malloc(N*sizeof(float));\n\n memset((void*)L1, 0, N*N*sizeof(PLASMA_Complex32_t));\n memset((void*)L2, 0, N*N*sizeof(PLASMA_Complex32_t));\n\n alpha= 1.0;\n\n LAPACKE_clacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N);\n\n /* Dealing with L'L or U'U */\n if (uplo == PlasmaUpper){\n LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N);\n LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N);\n cblas_ctrmm(CblasColMajor, CblasLeft, CblasUpper, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N);\n }\n else{\n LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N);\n LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N);\n cblas_ctrmm(CblasColMajor, CblasRight, CblasLower, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N);\n }\n\n /* Compute the Residual || A -L'L|| */\n for (i = 0; i < N; i++)\n for (j = 0; j < N; j++)\n Residual[j*N+i] = L2[j*N+i] - Residual[j*N+i];\n\n Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', N, N, Residual, N, work);\n Anorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', N, N, A1, LDA, work);\n\n printf(\"============\\n\");\n printf(\"Checking the Cholesky Factorization \\n\");\n printf(\"-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \\n\",Rnorm/(Anorm*N*eps));\n\n if ( isnan(Rnorm/(Anorm*N*eps)) || (Rnorm/(Anorm*N*eps) > 10.0) ){\n printf(\"-- Factorization is suspicious ! \\n\");\n info_factorization = 1;\n }\n else{\n printf(\"-- Factorization is CORRECT ! \\n\");\n info_factorization = 0;\n }\n\n free(Residual); free(L1); free(L2); free(work);\n\n return info_factorization;\n}\n\n/*--------------------------------------------------------------\n * Check the gemm\n */\nfloat c_check_gemm(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K,\n PLASMA_Complex32_t alpha, PLASMA_Complex32_t *A, int LDA,\n PLASMA_Complex32_t *B, int LDB,\n PLASMA_Complex32_t beta, PLASMA_Complex32_t *Cplasma,\n PLASMA_Complex32_t *Cref, int LDC,\n float *Cinitnorm, float *Cplasmanorm, float *Clapacknorm )\n{\n PLASMA_Complex32_t beta_const = -1.0;\n float Rnorm;\n float *work = (float *)malloc(max(K,max(M, N))* sizeof(float));\n\n *Cinitnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);\n *Cplasmanorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, Cplasma, LDC, work);\n\n cblas_cgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K,\n CBLAS_SADDR(alpha), A, LDA, B, LDB, CBLAS_SADDR(beta), Cref, LDC);\n\n *Clapacknorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);\n\n cblas_caxpy(LDC * N, CBLAS_SADDR(beta_const), Cplasma, 1, Cref, 1);\n\n Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);\n\n free(work);\n\n return Rnorm;\n}\n\n/*--------------------------------------------------------------\n * Check the trsm\n */\nfloat c_check_trsm(PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum trans, PLASMA_enum diag,\n int M, int NRHS, PLASMA_Complex32_t alpha,\n PLASMA_Complex32_t *A, int LDA,\n PLASMA_Complex32_t *Bplasma, PLASMA_Complex32_t *Bref, int LDB,\n float *Binitnorm, float *Bplasmanorm, float *Blapacknorm )\n{\n PLASMA_Complex32_t beta_const = -1.0;\n float Rnorm;\n float *work = (float *)malloc(max(M, NRHS)* sizeof(float));\n /*float eps = LAPACKE_slamch_work('e');*/\n\n *Binitnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, Bref, LDB, work);\n *Bplasmanorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bplasma, LDB, work);\n\n cblas_ctrsm(CblasColMajor, (CBLAS_SIDE)side, (CBLAS_UPLO)uplo,\n (CBLAS_TRANSPOSE)trans, (CBLAS_DIAG)diag, M, NRHS,\n CBLAS_SADDR(alpha), A, LDA, Bref, LDB);\n\n *Blapacknorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work);\n\n cblas_caxpy(LDB * NRHS, CBLAS_SADDR(beta_const), Bplasma, 1, Bref, 1);\n\n Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work);\n Rnorm = Rnorm / *Blapacknorm; \n /* max(M,NRHS) * eps);*/\n\n free(work);\n\n return Rnorm;\n}\n\n/*--------------------------------------------------------------\n * Check the solution\n */\n\nfloat c_check_solution(int M, int N, int NRHS, PLASMA_Complex32_t *A, int LDA,\n PLASMA_Complex32_t *B, PLASMA_Complex32_t *X, int LDB,\n float *anorm, float *bnorm, float *xnorm )\n{\n/* int info_solution; */\n float Rnorm = -1.00;\n PLASMA_Complex32_t zone = 1.0;\n PLASMA_Complex32_t mzone = -1.0;\n float *work = (float *)malloc(max(M, N)* sizeof(float));\n\n *anorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, A, LDA, work);\n *xnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, X, LDB, work);\n *bnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work);\n\n cblas_cgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, NRHS, N, CBLAS_SADDR(zone), A, LDA, X, LDB, CBLAS_SADDR(mzone), B, LDB);\n\n Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work);\n\n free(work);\n\n return Rnorm;\n}\n", "meta": {"hexsha": "d122839d6ba644faa10141ba3bf8da980b36af80", "size": 10509, "ext": "c", "lang": "C", "max_stars_repo_path": "timing/cauxiliary.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "timing/cauxiliary.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "timing/cauxiliary.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2651006711, "max_line_length": 134, "alphanum_fraction": 0.5899705015, "num_tokens": 3563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5755077500142392}} {"text": "#include \n#include \n#include \n#include \n#include \n\n// y' = 2y + x\n// https://www.wolframalpha.com/input/?i=y%27+%3D+2y+%2B+x%2C+y%280%29+%3D+1%2C+y%281%29\n// https://www.wolframalpha.com/input/?i=1%2F4+*+%285+*+e%5E2+-+3%29\n\n// 저항값: 1Kohm\n// 인덕턴스: 300uH\n// DC 전원: 5V\n\n// ---DC---R---L---GND---\n// 직렬 회로의 특성상 전류값이 일정함 i(t)\n// V = i(t) * R + L * [di(t) / dt]\n// 5 = y * R + L * y'\n// 미분 방정식의 표준형은 무조건 y'의 계수가 1이어야 합니다!!!\n// 5 / L = (R / L) * y + y'\n// 5 / 0.0003 = (1000 / 0.0003) * y + y'\n\n// y' = 5 / 0.0003 - (1000 / 0.0003) * y <<<=== 표준형\nint odefunc (double x, const double y[], double f[], void *params)\n{\n // f[0] = x+2*y[0]; \n\t//f[0] = pow(M_E, x);\n\t//f[0] = -(1000 / 0.0003) * x - (5 / 0.0003);\n\tf[0] = -(1000 / 0.0003) * y[0] + (5 / 0.0003);\n\n return GSL_SUCCESS;\n}\n\nint * jac;\n\nint main(void)\n{\n int dim = 1;\n\t// 미방을 풀기 위한 데이터 타입\n gsl_odeiv2_system sys = {odefunc, NULL, dim, NULL};\n\n\t// 드라이버는 미방을 쉽게 풀 수 있도록 시간에 따른 변화, 제어, 스텝에 대한 래퍼\n\t// gsl_odeiv2_step_rkf45는 룬게쿠타 4-5차를 의미함\n\t// 다음 인자는 미분방정식의 시작지점\n\t// 절대적인 에러 바운드와 상대적인 에러 바운드\n gsl_odeiv2_driver * d = gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rkf45, 1e-6, 1e-6, 0.0);\n int i;\n double x0 = 0.0, xf = 10.0; /* start and end of integration interval */\n double x = x0;\n double y[1] = { 0.5 }; /* initial value */\n\tdouble tmp = 0.0;\n\tint cnt = 0;\n\n for (i = 0; tmp <= xf; tmp += 0.0000001)\n {\n double xi = x0 + tmp * (xf-x0) / xf;\n int status = gsl_odeiv2_driver_apply (d, &x, xi, y);\n\n if (status != GSL_SUCCESS)\n {\n printf (\"error, return value=%d\\n\", status);\n break;\n }\n\n\t\tif (cnt++ < 101)\n\t\t{\n \tprintf (\"%.8e %.8e\\n\", x, y[0]);\n\t\t}\n }\n\n gsl_odeiv2_driver_free (d);\n return 0;\n}\n", "meta": {"hexsha": "521529a6fa59bbef3551f915f04769f2f7739c78", "size": 1840, "ext": "c", "lang": "C", "max_stars_repo_path": "ch4/src/main/rl_test.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": "ch4/src/main/rl_test.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": "ch4/src/main/rl_test.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": 24.8648648649, "max_line_length": 105, "alphanum_fraction": 0.5315217391, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5753569436013529}} {"text": "#include \"odeint.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#if HAVE_MKL_CBLAS\n#include \n#elif HAVE_OPENBLAS\n#include \n#else\n#include \n#endif\n\n/* TODO:\n * - implicit methods\n * - off-GPU\n */\n\n/**\n * The maximum number of steps.\n */\n#define MAX_STEP 8\n\n/**\n * @name: Name of the method\n * @steps: Number of steps\n * @last_step_is_update: Indicate if the last step correspond to the update, in\n * which case no final update is computed and the last transient 'y' is used.\n * @c: Whole step weight\n * @a: Previous steps weights\n * @b: Final step weights\n * @order: Order of the final update used to adjust the step size\n * @e: Error estimate\n * @error_estimate_order: Order of the error estimate (unused)\n */\ntypedef struct _OdeIntMeta\n{\n const char *name;\n int steps;\n int last_step_is_update;\n int error_estimate;\n double c[MAX_STEP];\n double a[(MAX_STEP*(MAX_STEP-1))/2];\n double b[MAX_STEP];\n int order;\n double e[MAX_STEP];\n int error_estimate_order;\n} OdeIntMeta;\n\n/*\n * Butcher table\n *\n * For method that provide no error estimate, we reuse the last step, which\n * will yield no error.\n */\nconst OdeIntMeta INTEGRATOR_META[] =\n{\n {\"euler\", 1, 0, 0,\n {0.0},\n {0},\n {1.0}, 1,\n {0}, 0},\n {\"heuns\", 2, 0, 0,\n {0.0, 1.0},\n {1.0},\n {1.0/2.0, 1.0/2.0}, 2,\n {0}, 0},\n {\"heuns-euler\", 2, 0, 1,\n {0.0, 1.0},\n {1.0},\n {1.0/2.0, 1.0/2.0}, 2,\n {1.0, 0.0}, 1},\n {\"bogacki-shampine\", 4, 1, 1,\n {0.0, 1.0/2.0, 3.0/4.0, 1.0},\n {1.0/2.0,\n 0.0, 3.0/4.0,\n 2.0/9.0, 1.0/3.0, 4.0/9.0},\n {2.0/9.0, 1.0/3.0, 4.0/9.0, 0.0}, 3,\n {7.0/24.0, 1.0/4.0, 1.0/3.0, 1.0/8.0}, 2},\n {\"runge-kutta\", 4, 0, 0,\n {0.0, 1.0/2.0, 1.0/2.0, 1.0},\n {1.0/2.0,\n 0.0, 1.0/2.0,\n 0.0, 0.0, 1.0},\n {1.0/6.0, 1.0/3.0, 1.0/3.0, 1.0/6.0}, 4,\n {0}, 0},\n {\"runge-kutta-fehlberg\", 6, 0, 1,\n {0.0, 1.0/4.0, 3.0/8.0, 12.0/13.0, 1.0, 1.0/2.0},\n {1.0/4.0,\n 3.0/32.0, 9.0/32.0,\n 1932.0/2197.0, -7200.0/2197.0, 7296.0/2197.0,\n 439.0/216.0, -8.0, 3680.0/513.0, -845/4104.0,\n -8.0/27.0, 2.0, -3544.0/2565.0, 1859.0/4104.0, -11.0/40.0},\n {16.0/135.0, 0.0, 6656.0/12825.0, 28561.0/56430.0, -9.0/50.0, 2.0/55.0}, 5,\n {25.0/216.0, 0.0, 1408.0/2565.0, 2197.0/4104.0, -1.0/5.0, 0.0}, 4},\n {\"cash-karp\", 6, 0, 1,\n {0.0, 1.0/5.0, 3.0/10.0, 3.0/5.0, 1.0, 7.0/8.0},\n {1.0/5.0,\n 3.0/40.0, 9.0/40.0,\n 3.0/10.0, -9.0/10.0, 6.0/5.0,\n -11.0/54.0, 5.0/2.0, -70.0/27.0, 35.0/27.0,\n 1631.0/55296.0, 175.0/512.0, 575.0/13824.0, 44275.0/110592.0, 253.0/4096.0},\n {37.0/378.0, 0.0, 250.0/621.0, 125.0/594.0, 0.0, 512.0/1771.0}, 5,\n {2825.0/27648.0, 0.0, 18575.0/48384.0, 13525.0/55296.0, 277.0/14336.0, 1.0/4.0}, 4},\n {\"dormand-prince\", 7, 1, 1,\n {0.0, 1.0/5.0, 3.0/10.0, 4.0/5.0, 8.0/9.0, 1.0, 1.0},\n {1.0/5.0,\n 3.0/40.0, 9.0/40.0,\n 44.0/45.0, -56.0/15.0, 32.0/9.0,\n 19372.0/6561.0, -25360.0/2187.0, 64448.0/6561.0, -212.0/729.0,\n 9017.0/3168.0, -355.0/33.0, 46732.0/5247.0, 49.0/176.0, -5103.0/18656.0,\n 35.0/384.0, 0.0, 500.0/1113.0, 125.0/192.0, -2187.0/6784.0, 11.0/84.0},\n {35.0/384.0, 0.0, 500.0/1113.0, 125.0/192.0, -2187.0/6784.0, 11.0/84.0, 0.0}, 5,\n {5179.0/57600.0, 0.0, 7571.0/16695.0, 393.0/640.0, -92097.0/339200.0, 187.0/2100.0, 1.0/40.0}, 4}\n};\n\nstruct _OdeIntIntegrator\n{\n const OdeIntMeta *integrator_meta;\n double *t;\n double *y;\n size_t n;\n double rtol;\n double atol;\n double *transient_y;\n double *transient_ye;\n double *F; // dy/dt\n double h;\n};\n\n/**\n * odeint_integrator_new:\n * @t0: Initial timestep\n * @y0: Initial value for the system which will be updated throughout the\n * integration\n * @n: Number of equations and variables (each variable has a differential equation w.r.t. time 't')\n * @rtol: Relative tolerance (i.e. number of significant digits)\n * @atol: Absolute tolerance\n */\nOdeIntIntegrator *\nodeint_integrator_new (OdeIntMethod method,\n double *t0,\n double *y0,\n size_t n,\n double rtol,\n double atol)\n{\n OdeIntIntegrator *ret = malloc (sizeof (OdeIntIntegrator));\n\n ret->integrator_meta = &INTEGRATOR_META[method];\n\n ret->t = t0;\n ret->y = y0;\n ret->n = n;\n /* we need at least 2 steps for the initial step size estimate */\n ret->F = calloc ((ret->integrator_meta->steps + 1) * n, sizeof (double));\n\n /* transient states for multi-step methods */\n ret->transient_y = malloc ( n * sizeof (double) );\n ret->transient_ye = malloc ( n * sizeof (double) );\n\n ret->rtol = rtol;\n ret->atol = atol;\n\n ret->h = 0;\n\n assert (ret->F != NULL);\n\n return ret;\n}\n\n/**\n * odeint_integrator_integrate:\n * @func: The function to integrate\n * @user_data:\n * @tw: The upper integration bound, which may also be smaller than the current\n * time.\n *\n * Integrate dy/dt = @func(t, y) over [t, @tw] or [@tw, t] if @tw < t.\n */\nvoid\nodeint_integrator_integrate (OdeIntIntegrator *self,\n OdeIntFunc func,\n void *user_data,\n double tw)\n{\n double t0 = *self->t;\n double t;\n\n /* transient state for the multi-step method */\n double *y = self->transient_y;\n double *ye = self->transient_ye;\n\n // Estimate initial step size using order, local curvature and tolerance\n // information\n //\n // reference:\n // H. A. Watts, “Starting Step Size for an ODE Solver,” Journal of\n // Computational and Applied Mathematics 9, no. 2 (June 1, 1983): 177–91,\n // https://doi.org/10.1016/0377-0427(83)90040-7.\n if (self->h == 0)\n {\n double epsilon = sqrt (DBL_EPSILON);\n\n func (t0, self->y, self->F, user_data);\n\n /* simple Euler step */\n cblas_dcopy (self->n, self->y, 1, y, 1);\n cblas_daxpy (self->n,\n epsilon,\n self->F,\n 1,\n y,\n 1);\n\n func (t0 + epsilon, y, self->F + self->n, user_data);\n\n cblas_daxpy (self->n,\n -1,\n self->F,\n 1,\n self->F + self->n,\n 1);\n\n double y_norm = cblas_dnrm2 (self->n, self->F + self->n, 1) / epsilon;\n\n assert (isfinite (y_norm));\n\n // if the has no curvature whatsoever, the step size will be infinite,\n self->h = sqrt (2.0) * pow (self->atol, 1.0 / (self->integrator_meta->order + 1)) / sqrt (y_norm);\n }\n\n size_t iteration = 0;\n\n while (fabs (tw - *self->t) >= self->rtol * fabs (tw) + self->atol)\n {\n iteration++;\n\n t = *self->t;\n\n // ensure we always land exactly on the upper integration bound\n // if we went too far, the step size will be negative and still point\n // toward the integration bound\n #define fsign(x)((x) < 0. ? -1. : 1.)\n self->h = fsign (tw - t) * fmin (fabs (self->h), fabs (tw - t));\n\n int step;\n for (step = 0; step < self->integrator_meta->steps; step++)\n {\n /* restore state at the beginning of the step */\n cblas_dcopy (self->n, self->y, 1, y, 1);\n\n int prev_step;\n for (prev_step = 0; prev_step < step; prev_step++)\n {\n cblas_daxpy (self->n,\n self->h * self->integrator_meta->a[(step * step - step)/2 + prev_step],\n self->F + prev_step * self->n,\n 1,\n y,\n 1);\n }\n\n /* update from previous steps */\n func (t + self->h * self->integrator_meta->c[step], y, self->F + (step * self->n), user_data);\n }\n\n // final update\n if (!self->integrator_meta->last_step_is_update)\n {\n /* restore state at the beginning of the step */\n cblas_dcopy (self->n, self->y, 1, y, 1);\n\n int step;\n for (step = 0; step < self->integrator_meta->steps; step++)\n {\n cblas_daxpy (self->n,\n self->h * self->integrator_meta->b[step],\n self->F + step * self->n,\n 1,\n y,\n 1);\n }\n }\n\n // error estimate\n if (self->integrator_meta->error_estimate)\n {\n /* restore state at the beginning of the step */\n cblas_dcopy (self->n, self->y, 1, ye, 1);\n\n int step;\n for (step = 0; step < self->integrator_meta->steps; step++)\n {\n cblas_daxpy (self->n,\n self->h * self->integrator_meta->e[step],\n self->F + step * self->n,\n 1,\n ye,\n 1);\n }\n\n // component-wise error\n double error_ratio = 0;\n size_t i;\n for (i = 0; i < self->n; i++)\n {\n double tol = self->rtol * fmax (fabs (ye[i]), fabs(y[i])) + self->atol;\n double error = fabs (ye[i] - y[i]);\n error_ratio = fmax (error_ratio, error / tol);\n }\n\n assert (isfinite (error_ratio));\n\n // check if the step is accepted\n if (error_ratio <= 1)\n {\n *self->t = t + self->h;\n cblas_dcopy (self->n, y, 1, self->y, 1);\n }\n\n // compute optimal step size\n self->h = self->h * pow (1.0 / error_ratio, 1.0 / self->integrator_meta->order);\n }\n else\n {\n *self->t = t + self->h;\n cblas_dcopy (self->n, y, 1, self->y, 1);\n }\n }\n}\n\nvoid odeint_integrator_free (OdeIntIntegrator *self)\n{\n free (self->transient_y);\n free (self->transient_ye);\n free (self->F);\n free (self);\n}\n", "meta": {"hexsha": "e70264623df433ced75f5f06a9117001ccdef7e6", "size": 10945, "ext": "c", "lang": "C", "max_stars_repo_path": "contrib/odeint/odeint.c", "max_stars_repo_name": "major-lab/mirbooking", "max_stars_repo_head_hexsha": "64569acae18401007e25b045c19c7ca0fe2b2a1c", "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": "contrib/odeint/odeint.c", "max_issues_repo_name": "major-lab/mirbooking", "max_issues_repo_head_hexsha": "64569acae18401007e25b045c19c7ca0fe2b2a1c", "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": "contrib/odeint/odeint.c", "max_forks_repo_name": "major-lab/mirbooking", "max_forks_repo_head_hexsha": "64569acae18401007e25b045c19c7ca0fe2b2a1c", "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.9096209913, "max_line_length": 117, "alphanum_fraction": 0.4661489265, "num_tokens": 3742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.5750963067543113}} {"text": "/*\n * $Source: /Users/mariko/lib/source/sde_wa/sde_wa_manual/sde_wa_manual_progra\n * $Revision: 1.7 $\n * $Author: mariko $\n * $Date: 2011/11/29 10:48:07 $\n */\n#include /* for malloc */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"european_option_blacksholes.h\"\n#include \"mlmc.h\"\n\n#define L_MAX 20\n\nint main(void){\n\tenum ALG alg = E_M;\n\tint m_moment = 7; /* Romberg */\n\tint M = 4;\n\tint n;\n\tdouble x0=1.0;\n\tdouble K = 1.00;\n\tstruct EBS_params ebs_params;\n\tdouble mu=0.05;\n\tdouble sigma=0.2;\n\tdouble T=1.0;\n\tebs_params.mu=mu;\n\tebs_params.sigma=sigma;\n\tebs_params.T=T;\n\tebs_params.K=K;\n\tMLMC_L **mlmc_est;\n\t{\n\t\tSDE_WA_SYSTEM *sde;\n\t\tSDE_WA_SLTN *sl;\n\t\tSDE_WA_PRICER *pricer;\n\t\tdouble sum;\n\t\tint dNl;\n\t\tdouble hl;\n\t\tdouble eps=0.0001;\n\t\tdouble epss[] = {0.001, 0.0005, 0.0002, 0.0001, 0.00005};\n\t\tint l;\n\t\tint L;\n\t\tint i;\n\t\tdouble con;\n\t\tint converged_flag=0;\n\t\tint extraporation_flag=0;\n\t\tsde=alloc_SDE_WA_SYSTEM(1, 1, &ebs_params);\n\t\tsde->sde_type=STR;\n\n\t\tsde->V[0]=ebs_str_V_0;\n\t\tsde->V[1]=ebs_V_1;\n\n\t\tsde->drift_corrector[0]=NULL;\n\t\tsde->drift_corrector[1]=diff_ebs_V_1; /* for EM */\n\n\t\tsde->exp_sV[0]=exp_ebs_sVy_0; /* for NV */\n\t\tsde->exp_sV[1]=exp_ebs_sVy_1; /* for NV */\n\n\t\tsl=alloc_SDE_WA_SLTN(alg, m_moment, sde);\n\n\t\tpricer=alloc_SDE_WA_PRICER(sl);\n\t\tpricer->payoff_function=european_option_blacksholes_call_payoff;\n\t\tpricer->init_y[0] = x0;\n\t\tpricer->T = 1.0;\n\n\t\t//gsl_qrng *q;\n\t\tgsl_rng_type *rng_type = (gsl_rng_type *)gsl_rng_default;\n\t\tgsl_rng *rng = gsl_rng_alloc(rng_type);\n\n\t\tif (pricer->gen_unif_rand == NULL) {\n\t\t\t/* sobol seq. => seq.dim.<=40*/\n\t\t//\tq=gsl_qrng_alloc(gsl_qrng_sobol, n*sde->dim_BM);\n\t\t//\tpricer->gen_unif_rand = q;\n\t\t//\tpricer->next_rand = gen_unif_rand_number_gsl_quasi;\n\n\t\t\tpricer->gen_unif_rand = rng;\n\t\t\tpricer->next_rand = gen_unif_rand_number_gsl_pseudo;\n\t\t}\n\n\t\tmlmc_est = (MLMC_L **)malloc(sizeof(MLMC_L *)*L_MAX);\n\t\tfor (l=0; lN = 4000000;\n\t\t\tmlmc_level_l_estimation(pricer, mlmc_est[L], L, M, mlmc_est[L]->N);\n\t\t\tmlmc_est[L]->V = mlmc_est[L]->sumV/mlmc_est[L]->N - (mlmc_est[L]->sumY/mlmc_est[L]->N)*(mlmc_est[L]->sumY/mlmc_est[L]->N);\n\t\t\tprintf(\"L:%d M:%d\\n\", L, M);\n\t\t\tprintf(\"N:%d, Y:%12e, V:%12.12lf, sumV:%lf\\n\", mlmc_est[L]->N, mlmc_est[L]->sumY/mlmc_est[L]->N, mlmc_est[L]->V, mlmc_est[L]->sumV);\n\t\t}\n\t\t//exit(-1);\n\t\tfor (i=0; i<5; i++) {\n\t\t\tL=-1;\n\t\t\teps = epss[i];\n\t\t\tfor (l=0; lN);\n\t\t\t\tprintf(\"N:%d, Y:%lf, sumV:%lf\\n\", mlmc_est[L]->N, mlmc_est[L]->sumY/mlmc_est[L]->N, mlmc_est[L]->sumV);\n\t\t\t\t//estimate Vl\n\t\t\t\tsum = 0.0;\n\t\t\t\tfor (l=0; l<=L; l++) {\n\t\t\t\t\tmlmc_est[l]->V = mlmc_est[l]->sumV/mlmc_est[l]->N - \n\t\t\t\t\t\t(mlmc_est[l]->sumY/mlmc_est[l]->N)*(mlmc_est[l]->sumY/mlmc_est[l]->N);\n\t\t\t\t\thl = 1.0/pow(M,l);\n\t\t\t\t\tsum += sqrt(mlmc_est[l]->V/hl);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//define optimal Nl\n\t\t\t\tfor (l=0; l<=L; l++) {\n\t\t\t\t\tmlmc_est[l]->newN = ceil(2.0 * sqrt(mlmc_est[l]->V * hl) * sum / (eps * eps));\n\t\t\t\t\tprintf(\"newN[%d]:%d\\n\", l, mlmc_est[l]->newN);\n\t\t\t\t}\n\n\t\t\t\t//update sample sum\n\t\t\t\tfor (l=0; l<=L; l++) {\n\t\t\t\t\tdNl = mlmc_est[l]->newN - mlmc_est[l]->N;\n\t\t\t\t\tprintf(\"dN[%d]:%d\\n\", l, dNl);\n\t\t\t\t\tif (dNl > 0) {\n\t\t\t\t\t\tmlmc_est[l]->N += dNl;\n\t\t\t\t\t\tmlmc_level_l_estimation(pricer, mlmc_est[l], l, M, dNl);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//test for convergence\n\t\t\t\tif (extraporation_flag) {\n\t\t\t\t\tif (L > 1) {\n\t\t\t\t\t\tcon = mlmc_est[L]->sumY/mlmc_est[L]->N - (1.0/(double)n) * mlmc_est[L-1]->sumY/mlmc_est[L-1]->N;\n\t\t\t\t\t\tif (fabs(con) < 1.0*(M*M - 1.0)*eps/sqrt(2.0)) {\n\t\t\t\t\t\t\tconverged_flag = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (L > 1) {\n\t\t\t\t\t\tcon = fmax(fabs(mlmc_est[L]->sumY/mlmc_est[L]->N), fabs(mlmc_est[L-1]->sumY/mlmc_est[L-1]->N/M));\n\t\t\t\t\t\tif (con < (M-1)*eps/sqrt(2.0)) {\n\t\t\t\t\t\t\tconverged_flag = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprintf(\"N:%d, Y:%lf, V:%12.12lf, sumV:%lf\\n\", mlmc_est[L]->N, mlmc_est[L]->sumY/mlmc_est[L]->N, mlmc_est[L]->V, mlmc_est[L]->sumV);\n\t\t\t\tprintf(\"L:%d, con:%lf, test:%lf \\n\\n\", L, con, (M-1)*eps/sqrt(2.0));\n\t\t\t}\n\t\t\tsum=0.0;\n\t\t\tfor (l=0; l<=L; l++) {\n\t\t\t\tsum += mlmc_est[l]->sumY / mlmc_est[l]->N;\n\t\t\t}\n\t\t\tif (extraporation_flag) {\n\t\t\t\tsum += mlmc_est[L]->sumY/mlmc_est[L]->N/(M-1);\n\t\t\t}\n\t\t\tprintf(\"P:%.12e\\n\\n\", sum);\n\t\t}\n\n\t\tfor (l=0; lsumY = 0.0;\n\tmlmc_l->sumV = 0.0;\n\tmlmc_l->V = 0.0;\n\tmlmc_l->N = 10000;\n\tmlmc_l->newN = 0;\n\n\treturn mlmc_l;\n}\n\nvoid init_level_l_estimator(MLMC_L *mlmc_l) {\n\tmlmc_l->sumY = 0.0;\n\tmlmc_l->sumV = 0.0;\n\tmlmc_l->V = 0.0;\n\tmlmc_l->N = 10000;\n\tmlmc_l->newN = 0;\n}\n\nvoid gen_unif_rand_number_gsl_pseudo(void *gen, double *rand, int n) {\n\tgsl_rng *rng = gen;\n\tint j=0;\n\n\tfor (j=0; jsltn;\n\tSDE_WA_SYSTEM *sde = sl->sde;\n\tint i,j,k,m;\n\tdouble sum=0.0;\n\tint n = pow(M, l);\n\tdouble dt1, dt2;\n\tdouble *u_seq;\n\tdouble *n_seq;\n\tdouble *sp, *sp2;\n\tdouble *tmp_pt;\n\tdouble tmp;\n\tdouble **xf;\n\tdouble **xc;\n\n\tu_seq=(double *)malloc(sizeof(double)*n*sde->dim_BM);\n\tn_seq=(double *)malloc(sizeof(double)*n*sde->dim_BM);\n\n\txf=(double **)malloc(sizeof(double *)*2);\n\tfor (i=0; i<2; i++) xf[i]=(double *)malloc(sizeof(double)*sde->dim_y);\n\n\txc=(double **)malloc(sizeof(double *)*2);\n\tfor (i=0; i<2; i++) xc[i]=(double *)malloc(sizeof(double)*sde->dim_y);\n\n\tif (l == 0) {\n\t\tsp=(double *)malloc(sizeof(double)*sde->dim_BM*2);\n\t\tsp2=(double *)malloc(sizeof(double)*sde->dim_BM*2);\n\t\tfor (sum=0.0, i=0; i < N; i++){\n\t\t\tfor (j=0; jdim_y; j++) {\n\t\t\t\txf[0][j] = pricer->init_y[j];\n\t\t\t}\n\t\t\tpricer->next_rand(pricer->gen_unif_rand, sp2, sde->dim_BM*2);\n\t\t\ttrans_rand_unif_to_normal(sp2, sp, sde->dim_BM*2);\n\n\t\t\tnext_SDE_WA(sl, pricer->T, xf[0], xf[1], sp);\n\t\t\ttmp_pt=xf[0];\n\t\t\txf[0]=xf[1];\n\t\t\txf[1]=tmp_pt;\n\n\t\t\testimator->sumY += pricer->payoff_function(xf[0], sde->params);\n\t\t\testimator->sumV += pricer->payoff_function(xf[0], sde->params) * pricer->payoff_function(xf[0], sde->params);\n\t\t} /* for i */\n\t} else {\n\t\tsp=(double *)malloc(sizeof(double)*sde->dim_BM);\n\t\tsp2=(double *)malloc(sizeof(double)*sde->dim_BM);\n\t\tdt1=pricer->T/(double)n;\n\t\tdt2=M/(double)n;\n\t\tfor (sum=0.0, i=0; i < N; i++){\n\t\t\tpricer->next_rand(pricer->gen_unif_rand, u_seq, n*sde->dim_BM);\n\t\t\ttrans_rand_unif_to_normal(u_seq, n_seq, n*sde->dim_BM);\n\n\t\t\tfor (j=0; jdim_y; j++) {\n\t\t\t\txf[0][j] = pricer->init_y[j];\n\t\t\t\txc[0][j] = pricer->init_y[j];\n\t\t\t}\n\t\t\tfor (k=0; kdim_BM; m++) {\n\t\t\t\t\tsp2[m] = 0.0;\n\t\t\t\t}\n\t\t\t\tfor (j=0; jdim_BM; m++) {\n\t\t\t\t\t\tsp[m] = n_seq[k*M + m + sde->dim_BM*j];\n\t\t\t\t\t\tsp2[m] += sp[m];\n\t\t\t\t\t}\n\t\t\t\t\tnext_SDE_WA(sl, dt1, xf[0], xf[1], sp);\n\t\t\t\t\ttmp_pt=xf[0];\n\t\t\t\t\txf[0]=xf[1];\n\t\t\t\t\txf[1]=tmp_pt;\n\t\t\t\t}\n\t\t\t\tfor (m=0; mdim_BM; m++) {\n\t\t\t\t\tsp2[m] = sp2[m]/sqrt(M);\n\t\t\t\t}\n\t\t\t\tnext_SDE_WA(sl, dt2, xc[0], xc[1], sp2);\n\t\t\t\ttmp_pt=xc[0];\n\t\t\t\txc[0]=xc[1];\n\t\t\t\txc[1]=tmp_pt;\n\t\t\t}\n\t\t\ttmp = pricer->payoff_function(xf[0], sde->params) - pricer->payoff_function(xc[0], sde->params);\n\t\t\testimator->sumY += tmp; \n\t\t\testimator->sumV += tmp*tmp;\n\t\t} /* for i */\n\t}\n\treturn sum;\n}\n\n", "meta": {"hexsha": "6fc2f9e764417eaf07f5e4c884fab39889f94f33", "size": 8916, "ext": "c", "lang": "C", "max_stars_repo_path": "european_option_blackscholes_mlmc/src/european_option_blacksholes_main_em_mlmc.c", "max_stars_repo_name": "i05nagai/SDEWeakApproximationMLMCSamples", "max_stars_repo_head_hexsha": "9b3d348812229b616df451dd46de0c8b928bb791", "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": "european_option_blackscholes_mlmc/src/european_option_blacksholes_main_em_mlmc.c", "max_issues_repo_name": "i05nagai/SDEWeakApproximationMLMCSamples", "max_issues_repo_head_hexsha": "9b3d348812229b616df451dd46de0c8b928bb791", "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": "european_option_blackscholes_mlmc/src/european_option_blacksholes_main_em_mlmc.c", "max_forks_repo_name": "i05nagai/SDEWeakApproximationMLMCSamples", "max_forks_repo_head_hexsha": "9b3d348812229b616df451dd46de0c8b928bb791", "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.3008849558, "max_line_length": 135, "alphanum_fraction": 0.6032974428, "num_tokens": 3556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5746098085661373}} {"text": "//\n// mcmc_lotkavolterra.c\n// \n//\n// Created by Juan Pablo Molano on 15/11/15.\n//\n//\n\n#include \n#include \n#include \n#include \n#include \n#include \n#define USAGE \"./mcmc_lotkavolterra.x n_burn n_steps\"\n\n//------------------------------------------------------------------------------------------------------------\n\nvoid load_matrix(char *filename, float *time, float *pre, float *dep , int n);\nvoid print_data(float *array, float *array2 , float *array3 , float *array4 , float *array5 , float *array6, float *array7, float *array8 , float *array9 , float *array10, int n_puntos);\nfloat *reserva(int n);\nfloat likelihood(float *y_obs, float *y_model, int n_row);\nvoid ec_dep(float *array, float x, float y, float gamma, float delta);\nvoid ec_pre(float *array, float x, float y, float alpha, float beta);\nint min_likelihood( float *array , int n_row);\n\n\n//------------------------------------------------------------------------------------------------------------\n\nint main(int argc, char **argv){\n \n float *tim, *pre, *dep;\n float m_x , m_y , k1_x , k1_y , k2_x , k2_y , k3_x , k3_y , k4_x , k4_y;\n float x1 , x2 , x3, x4, y1, y2, y3, y4 , h;\n float alpha_prime, beta_prime, gamma_prime, delta_prime, l_prime, l_init, gam, alph, bet , best_alpha , best_beta, best_gamma, best_delta;\n float *fit_pre, *fit_dep , *dep_init, *dep_prime , *pre_init , *pre_prime;\n int i, j , n_row = 96;\n float *alpha_a, *beta_a , *gamma_a , *delta_a , *walk_a, *best_dep, *best_pre;\n srand48(time(NULL));\n\n alpha_a = reserva( atof(argv[1]) + atof(argv[2]));\n beta_a = reserva( atof(argv[1]) + atof(argv[2]));\n gamma_a= reserva( atof(argv[1]) + atof(argv[2]));\n delta_a = reserva( atof(argv[1]) + atof(argv[2]));\n walk_a = reserva( atof(argv[1]) + atof(argv[2]));\n \n alpha_a[0] = drand48();\n beta_a[0] = drand48();\n gamma_a[0] = drand48();\n delta_a[0] = drand48();\n\n tim = reserva(96);\n pre = reserva(96);\n dep = reserva(96);\n fit_dep = reserva(96);\n fit_pre = reserva(96);\n dep_init = reserva(96);\n dep_prime = reserva(96);\n pre_init = reserva(96);\n pre_prime = reserva(96);\n best_dep = reserva(96);\n best_pre = reserva(96);\n \n load_matrix( \"new_data.txt\" , tim , pre , dep, 96);\n\n h = tim[1] - tim[0];\n \n fit_pre[0] = pre[0];\n fit_dep[0] = dep[0];\n \n const gsl_rng_type * T;\n gsl_rng * r;\n gsl_rng_env_setup();\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n \n for(i=1;i<96;i++){\n \n ec_pre( &k1_x , fit_pre[i-1] , fit_dep[i-1] , alpha_a[0] , beta_a[0]);\n ec_dep( &k1_y , fit_pre[i-1] , fit_dep[i-1] , gamma_a[0] , delta_a[0]);\n \n x1 = fit_pre[i-1] + (h/2.0) * k1_x;\n y1 = fit_dep[i-1] + (h/2.0) * k1_y;\n \n\n ec_pre( &k2_x , fit_pre[i-1] , fit_dep[i-1] , alpha_a[0] , beta_a[0]);\n ec_dep( &k2_y , fit_pre[i-1] , fit_dep[i-1] , gamma_a[0] , delta_a[0]);\n \n\n x2 = fit_pre[i-1] + (h/2.0) * k2_x;\n y2 = fit_dep[i-1] + (h/2.0) * k2_y;\n \n\n ec_pre( &k3_x , fit_pre[i-1] , fit_dep[i-1] , alpha_a[0] , beta_a[0]);\n ec_dep( &k3_y , fit_pre[i-1] , fit_dep[i-1] , gamma_a[0] , delta_a[0]);\n \n\n x3 = fit_pre[i-1] + h * k3_x;\n y3 = fit_dep[i-1] + h * k3_y;\n \n ec_pre( &k4_x , fit_pre[i-1] , fit_dep[i-1] , alpha_a[0] , beta_a[0]);\n ec_dep( &k4_y , fit_pre[i-1] , fit_dep[i-1] , gamma_a[0] , delta_a[0]);\n \n \n m_x = (1.0/6.0)*(k1_x + 2.0*k2_x + 2.0*k3_x + k4_x);\n m_y = (1.0/6.0)*(k1_y + 2.0*k2_y + 2.0*k3_y + k4_y);\n \n fit_pre[i] = fit_pre[i-1] + h * m_x;\n fit_dep[i] = fit_dep[i-1] + h * m_y;\n }\n\n for (i=0; i < atof(argv[1]) + atof(argv[2]); i++) {\n \n alpha_prime = gsl_ran_gaussian(r, 0.1) + alpha_a[i];\n beta_prime = gsl_ran_gaussian(r, 0.1) + beta_a[i];\n gamma_prime = gsl_ran_gaussian(r, 0.1) + gamma_a[i];\n delta_prime = gsl_ran_gaussian(r, 0.1) + delta_a[i];\n \n \n for(j=1;j<96;j++){\n \n dep_init[0] = dep[0];\n pre_init[0] = pre[0];\n \n \n ec_pre( &k1_x , pre_init[j-1] , dep_init[j-1] , alpha_a[i] , beta_a[i]);\n ec_dep( &k1_y , pre_init[j-1] , dep_init[j-1] , gamma_a[i] , delta_a[i]);\n \n x1 = pre_init[j-1] + (h/2.0) * k1_x;\n y1 = dep_init[j-1] + (h/2.0) * k1_y;\n \n \n ec_pre( &k2_x , pre_init[j-1] , dep_init[j-1] , alpha_a[i] , beta_a[i]);\n ec_dep( &k2_y , pre_init[j-1] , dep_init[j-1] , gamma_a[i] , delta_a[i]);\n \n \n x2 = pre_init[j-1] + (h/2.0) * k2_x;\n y2 = dep_init[j-1] + (h/2.0) * k2_y;\n \n \n ec_pre( &k3_x , pre_init[j-1] , dep_init[j-1] , alpha_a[i] , beta_a[i]);\n ec_dep( &k3_y , pre_init[j-1] , dep_init[j-1] , gamma_a[i] , delta_a[i]);\n \n \n x3 = pre_init[j-1] + h * k3_x;\n y3 = dep_init[j-1] + h * k3_y;\n \n ec_pre( &k4_x , pre_init[j-1] , dep_init[j-1] , alpha_a[i] , beta_a[i]);\n ec_dep( &k4_y , pre_init[j-1] , dep_init[j-1] , gamma_a[i] , delta_a[i]);\n \n \n m_x = (1.0/6.0)*(k1_x + 2.0*k2_x + 2.0*k3_x + k4_x);\n m_y = (1.0/6.0)*(k1_y + 2.0*k2_y + 2.0*k3_y + k4_y);\n \n pre_init[j] = pre_init[i-1] + h * m_x;\n dep_init[j] = dep_init[i-1] + h * m_y;\n }\n \n for(j=1;j<96;j++){\n \n dep_prime[0] = dep[0];\n pre_prime[0] = pre[0];\n \n \n ec_pre( &k1_x , pre_prime[j-1] , dep_prime[j-1] , alpha_prime , beta_prime);\n ec_dep( &k1_y , pre_prime[j-1] , dep_prime[j-1] , gamma_prime , delta_prime);\n \n x1 = pre_prime[j-1] + (h/2.0) * k1_x;\n y1 = dep_prime[j-1] + (h/2.0) * k1_y;\n \n \n ec_pre( &k2_x , pre_prime[j-1] , dep_prime[j-1] , alpha_prime , beta_prime);\n ec_dep( &k2_y , pre_prime[j-1] , dep_prime[j-1] , gamma_prime , delta_prime);\n \n \n x2 = pre_prime[j-1] + (h/2.0) * k2_x;\n y2 = dep_prime[j-1] + (h/2.0) * k2_y;\n \n \n ec_pre( &k3_x , pre_prime[j-1] , dep_prime[j-1] , alpha_prime , beta_prime);\n ec_dep( &k3_y , pre_prime[j-1] , dep_prime[j-1] , gamma_prime , delta_prime);\n \n \n x3 = pre_prime[j-1] + h * k3_x;\n y3 = dep_prime[j-1] + h * k3_y;\n \n ec_pre( &k4_x , pre_prime[j-1] , dep_prime[j-1] , alpha_prime , beta_prime);\n ec_dep( &k4_y , pre_prime[j-1] , dep_prime[j-1] , gamma_prime , delta_prime);\n \n \n m_x = (1.0/6.0)*(k1_x + 2.0*k2_x + 2.0*k3_x + k4_x);\n m_y = (1.0/6.0)*(k1_y + 2.0*k2_y + 2.0*k3_y + k4_y);\n \n pre_prime[j] = pre_prime[j-1] + h * m_x;\n dep_prime[j] = dep_prime[j-1] + h * m_y;\n }\n\n \n l_prime = likelihood( dep, dep_prime , n_row) + likelihood( pre , pre_prime , n_row);\n l_init = likelihood( dep , dep_init , n_row) + likelihood( pre , pre_init , n_row);\n \n gam = l_init - l_prime;\n \n if (gam>=0.0) {\n alpha_a[i+1] = alpha_prime;\n beta_a[i+1] = beta_prime;\n gamma_a[i+1] = gamma_prime;\n delta_a[i+1] = delta_prime;\n walk_a[i+1] = l_prime;\n }\n else{\n \n bet = drand48();\n alph = exp(gam);\n \n if (bet <= alph) {\n \n alpha_a[i+1] = alpha_prime;\n beta_a[i+1] = beta_prime;\n gamma_a[i+1] = gamma_prime;\n delta_a[i+1] = delta_prime;\n walk_a[i+1] = l_prime;\n\n }\n else{\n \n alpha_a[i+1] = alpha_a[i];\n beta_a[i+1] = beta_a[i];\n gamma_a[i+1] = gamma_a[i];\n delta_a[i+1] = delta_a[i];\n walk_a[i+1] = l_prime;\n \n }\n \n }\n }\n \n j = min_likelihood( walk_a , n_row);\n best_alpha = alpha_a[j];\n best_beta = beta_a[j];\n best_gamma = gamma_a[j];\n best_delta = delta_a[j];\n \n for(i=1;i<96;i++){\n \n best_dep[0] = dep[0];\n best_pre[0] = pre[0];\n \n ec_pre( &k1_x , best_pre[i-1] , best_dep[i-1] , best_alpha , best_beta);\n ec_dep( &k1_y , best_pre[i-1] , best_dep[i-1], best_gamma , best_delta);\n \n x1 = fit_pre[i-1] + (h/2.0) * k1_x;\n y1 = fit_dep[i-1] + (h/2.0) * k1_y;\n \n \n ec_pre( &k2_x , best_pre[i-1] , best_dep[i-1] , best_alpha , best_beta);\n ec_dep( &k2_y , best_pre[i-1] , best_dep[i-1] , best_gamma , best_delta);\n \n \n x2 = fit_pre[i-1] + (h/2.0) * k2_x;\n y2 = fit_dep[i-1] + (h/2.0) * k2_y;\n \n \n ec_pre( &k3_x , best_pre[i-1] , best_dep[i-1], best_alpha , best_beta);\n ec_dep( &k3_y , best_pre[i-1] , best_dep[i-1], best_gamma , best_delta);\n \n \n x3 = fit_pre[i-1] + h * k3_x;\n y3 = fit_dep[i-1] + h * k3_y;\n \n ec_pre( &k4_x , best_pre[i-1] , best_dep[i-1], best_alpha , best_beta);\n ec_dep( &k4_y , best_pre[i-1] , best_dep[i-1] , best_gamma , best_delta);\n \n \n m_x = (1.0/6.0)*(k1_x + 2.0*k2_x + 2.0*k3_x + k4_x);\n m_y = (1.0/6.0)*(k1_y + 2.0*k2_y + 2.0*k3_y + k4_y);\n \n best_pre[i] = best_pre[i-1] + h * m_x;\n best_dep[i-1] = best_dep[i-1] + h * m_y;\n }\n \n \n print_data( tim , pre, dep, best_pre , best_pre, walk_a , alpha_a , beta_a , gamma_a , delta_a , n_row);\n \n gsl_rng_free (r);\n\n \n return 0;\n\n}\n\n\n\n\n\n//------------------------------------------------------------------------------------------------------------\n\nvoid load_matrix(char *filename, float *time, float *pre, float *dep , int n){\n \n FILE *in;\n int i;\n in=fopen(filename,\"r\");\n if(!in){\n printf(\"problems opening the file %s\\n\", filename);\n exit(1);\n }\n for(i=0;i<(n);i++){\n \n fscanf(in, \"%f %f %f\\n\", &time[i], &pre[i], &dep[i]);\n \n }\n fclose(in);\n}\n\n//------------------------------------------------------------------------------------------------------------\n\nvoid print_data(float *array, float *array2 , float *array3 , float *array4 , float *array5 , float *array6, float *array7, float *array8 , float *array9 , float *array10 , int n_puntos){\n int i;\n for(i=0;i\n#include \n#include \n#include \n#include \n#include \n\ndouble\ngsl_ran_gaussian_tail (const gsl_rng * r, const double a, const double sigma)\n{\n /* Returns a gaussian random variable larger than a\n * This implementation does one-sided upper-tailed deviates.\n */\n\n double s = a / sigma;\n\n if (s < 1)\n {\n /* For small s, use a direct rejection method. The limit s < 1\n can be adjusted to optimise the overall efficiency */\n\n double x;\n\n do\n {\n x = gsl_ran_gaussian (r, 1.0);\n }\n while (x < s);\n return x * sigma;\n }\n else\n {\n /* Use the \"supertail\" deviates from the last two steps\n * of Marsaglia's rectangle-wedge-tail method, as described\n * in Knuth, v2, 3rd ed, pp 123-128. (See also exercise 11, p139,\n * and the solution, p586.)\n */\n\n double u, v, x;\n\n do\n {\n u = gsl_rng_uniform (r);\n do\n {\n v = gsl_rng_uniform (r);\n }\n while (v == 0.0);\n x = sqrt (s * s - 2 * log (v));\n }\n while (x * u > s);\n return x * sigma;\n }\n}\n\ndouble\ngsl_ran_gaussian_tail_pdf (const double x, const double a, const double sigma)\n{\n if (x < a)\n {\n return 0;\n }\n else\n {\n double N, p;\n double u = x / sigma ;\n\n double f = gsl_sf_erfc (a / (sqrt (2.0) * sigma));\n\n N = 0.5 * f;\n\n p = (1 / (N * sqrt (2 * M_PI) * sigma)) * exp (-u * u / 2);\n\n return p;\n }\n}\n\ndouble\ngsl_ran_ugaussian_tail (const gsl_rng * r, const double a)\n{\n return gsl_ran_gaussian_tail (r, a, 1.0) ;\n}\n\ndouble\ngsl_ran_ugaussian_tail_pdf (const double x, const double a)\n{\n return gsl_ran_gaussian_tail_pdf (x, a, 1.0) ;\n}\n", "meta": {"hexsha": "e7c9ced79eabe7ba2af2c490961dfc4ee5e2155c", "size": 2659, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/gausstail.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/gausstail.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/gausstail.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": 24.6203703704, "max_line_length": 81, "alphanum_fraction": 0.6088755171, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5742265898630452}} {"text": "#include \n#include \n#include \n\ndouble\nf (double x, void *p)\n{\n if (x < 0.5)\n return 0.25;\n else\n return 0.75;\n}\n\nint\nmain (void)\n{\n int i, n = 10000; \n\n gsl_cheb_series *cs = gsl_cheb_alloc (40);\n\n gsl_function F;\n\n F.function = f;\n F.params = 0;\n\n gsl_cheb_init (cs, &F, 0.0, 1.0);\n\n for (i = 0; i < n; i++)\n {\n double x = i / (double)n;\n double r10 = gsl_cheb_eval_n (cs, 10, x);\n double r40 = gsl_cheb_eval (cs, x);\n printf (\"%g %g %g %g\\n\", \n x, GSL_FN_EVAL (&F, x), r10, r40);\n }\n\n gsl_cheb_free (cs);\n\n return 0;\n}\n", "meta": {"hexsha": "58a0c5469914fefb7a50561b6885748a79960df5", "size": 623, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/cheb.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/cheb.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/cheb.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": 15.1951219512, "max_line_length": 48, "alphanum_fraction": 0.5409309791, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478254, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5737971670037544}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"sph_data_types.h\"\n#include \"sph_linked_list.h\"\n#include \"sph_compute.h\"\n\nextern const double fk_bspline_32[32];\nextern const double fk_bspline_128[128];\nextern const double fk_bspline_1024[1024];\n\n#pragma omp declare simd\ndouble w_bspline_3d(double r,double h){\n const double A_d = 3./(2.*M_PI*h*h*h);\n double q=0.;\n \n if(r<0||h<=0.)\n exit(10);\n \n q = r/h;\n if(q<=1)\n return A_d*(2./3.-q*q + q*q*q/2.0);\n else if((1.<=q)&&(q<2.))\n return A_d*(1./6.)*(2.-q)*(2.-q)*(2.-q);\n else \n return 0.;\n}\n\ndouble w_bspline_3d_constant(double h){\n return 3./(2.*M_PI*h*h*h);\n}\n\n#pragma omp declare simd\ndouble w_bspline_3d_simd(double q){\n double wq = 0.0;\n double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q);\n double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); \n \n if(q<2.)\n wq = wq2;\n\n if(q<1.)\n wq = wq1;\n \n return wq;\n}\n\n#pragma omp declare simd\ndouble dwdq_bspline_3d_simd(double q){\n double wq = 0.0;\n double wq1 = (1.5*q*q - 2.*q);\n double wq2 = -0.5*(2.-q)*(2.-q); \n \n if(q<2.)\n wq = wq2;\n\n if(q<1.)\n wq = wq1;\n \n return wq;\n}\n\n// https://stackoverflow.com/questions/56417115/efficient-integer-floor-function-in-c\n// 341.333333333 = 1024./3.\n#pragma omp declare simd\ndouble w_bspline_3d_LUT_1024(double q){\n int kq = (int)(341.333333333*q);\n double phi = q-kq*0.002929688;\n double wq = phi*fk_bspline_1024[kq] + (1.-phi)*fk_bspline_1024[kq+1];\n \n return wq;\n}\n\n#pragma omp declare simd\ndouble w_bspline_3d_LUT_128(double q){\n int kq = (int)(42.666666667*q);\n double phi = q-kq*0.0234375;\n double wq = phi*fk_bspline_128[kq] + (1.-phi)*fk_bspline_128[kq+1];\n \n return wq;\n}\n\n#pragma omp declare simd\ndouble w_bspline_3d_LUT_32(double q){\n int kq = (int)(10.666666667*q);\n double phi = q-kq*0.09375;\n double wq = (1.-phi)*fk_bspline_32[kq] + phi*fk_bspline_32[kq+1];\n \n return wq;\n}\n\ndouble dwdq_bspline_3d(double r,double h){\n const double A_d = 3./(2.*M_PI*h*h*h*h);\n double q=0.;\n \n if(r<0||h<=0.)\n exit(10);\n \n q = r/h;\n if(q<=1)\n return A_d*q*(-2.+1.5*q);\n else if((1.<=q)&&(q<2.))\n return -A_d*0.5*(2.-q)*(2.-q);\n else \n return 0.;\n}\n\ndouble distance_2d(double xi,double yi,\n double xj,double yj){\n double dist = 0.0;\n\n dist += (xi-xj)*(xi-xj);\n dist += (yi-yj)*(yi-yj);\n\n return sqrt(dist);\n}\n\n#pragma omp declare simd\ndouble distance_3d(double xi,double yi,double zi,\n double xj,double yj,double zj){\n double dist = 0.0;\n\n dist += (xi-xj)*(xi-xj);\n dist += (yi-yj)*(yi-yj);\n dist += (zi-zj)*(zi-zj);\n\n return sqrt(dist);\n}\n\n/**********************************************************************/\n\nint compute_density_3d_chunk(int64_t node_begin, int64_t node_end,\n int64_t nb_begin, int64_t nb_end,double h,\n double* restrict x, double* restrict y,\n double* restrict z, double* restrict nu,\n double* restrict rho){\n const double inv_h = 1./h;\n const double kernel_constant = w_bspline_3d_constant(h);\n\n #pragma omp parallel for \n for(int64_t ii=node_begin;iiwidth+1)*(2*box->width+1)*(2*box->width+1)];\n\n for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){\n \n if (kh_exist(box->hbegin, kbegin)){\n kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));\n node_hash = kh_key(box->hbegin, kbegin);\n node_begin = kh_value(box->hbegin, kbegin);\n node_end = kh_value(box->hend, kend);\n\n for(int64_t ii=node_begin;iirho[ii] = 0.0; \n\n res = neighbour_hash_3d(node_hash,nblist,box->width,box);\n for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){\n if(nblist[j]>=0){\n //nb_hash = nblist[j];\n nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );\n nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );\n\n compute_density_3d_chunk(node_begin,node_end,nb_begin,nb_end,h,\n lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho);\n }\n }\n }\n }\n\n return 0;\n}\n\n/**********************************************************************/\n\nint compute_density_3d_chunk_noomp(int64_t node_begin, int64_t node_end,\n int64_t nb_begin, int64_t nb_end,double h,\n double* restrict x, double* restrict y,\n double* restrict z, double* restrict nu,\n double* restrict rho){\n const double inv_h = 1./h;\n const double kernel_constant = w_bspline_3d_constant(h);\n\n for(int64_t ii=node_begin;iihbegin);\n const khiter_t hbegin_start = kh_begin(box->hbegin), hbegin_finish = kh_end(box->hbegin);\n\n \n //for (khint32_t kbegin = hbegin_start; kbegin != hbegin_finish; kbegin++)\n #pragma omp parallel for num_threads(24)\n for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){\n int res;\n int64_t node_hash=-1,node_begin=0, node_end=0;\n int64_t nb_begin= 0, nb_end = 0;\n int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n\n if (kh_exist(box->hbegin, kbegin)){ // I have to call this!\n khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));\n\n node_hash = kh_key(box->hbegin, kbegin);\n node_begin = kh_value(box->hbegin, kbegin);\n node_end = kh_value(box->hend, kend);\n\n for(int64_t ii=node_begin;iirho[ii] = 0.0; \n\n res = neighbour_hash_3d(node_hash,nblist,box->width,box);\n for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){\n if(nblist[j]>=0){\n //nb_hash = nblist[j];\n\n nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );\n nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );\n\n pair_count += (node_end-node_begin)*(nb_end-nb_begin);\n\n compute_density_3d_chunk_noomp(node_begin,node_end,nb_begin,nb_end,h,\n lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho);\n }\n }\n }\n\n //printf(\"thread %d - %lf %lf\\n\",i,lsph->rho[node_begin],lsph->rho[node_end-1]);\n }\n\n printf(\"pair_count = %ld\\n\",pair_count);\n\n //for(int64_t i=0;irho[i]);\n\n return 0;\n}\n\n/**********************************************************************/\n\nint compute_density_3d_chunk_loopswapped(int64_t node_begin, int64_t node_end,\n int64_t node_hash,linkedListBox *box, double h,\n double* restrict x, double* restrict y,\n double* restrict z, double* restrict nu,\n double* restrict rho)\n{\n int64_t pair_count;\n int res=0,nb_count=0,fused_count=0;\n //int64_t nb_begin= 0, nb_end = 0;\n const double inv_h = 1./h;\n const double kernel_constant = w_bspline_3d_constant(h);\n int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n int64_t nb_begin[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n int64_t nb_end[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n\n res = neighbour_hash_3d(node_hash,nblist,box->width,box);\n for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){\n if(nblist[j]>=0){\n nb_begin[nb_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );\n nb_end[nb_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );\n nb_count+=1;\n }\n else{\n nb_begin[nb_count] = -1;\n nb_end[nb_count] = -1;\n }\n }\n\n qsort(nb_begin,nb_count,sizeof(int64_t),compare_int64_t);\n qsort(nb_end ,nb_count,sizeof(int64_t),compare_int64_t);\n\n fused_count = nb_count;\n {\n int64_t tmp;\n unsigned int j=0;\n while(jhbegin);\n const khiter_t hbegin_start = kh_begin(box->hbegin), hbegin_finish = kh_end(box->hbegin);\n\n \n //for (khint32_t kbegin = hbegin_start; kbegin != hbegin_finish; kbegin++)\n #pragma omp parallel for num_threads(24)\n for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){\n int res;\n int64_t node_hash=-1,node_begin=0, node_end=0;\n\n if (kh_exist(box->hbegin, kbegin)){ // I have to call this!\n khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));\n\n node_hash = kh_key(box->hbegin, kbegin);\n node_begin = kh_value(box->hbegin, kbegin);\n node_end = kh_value(box->hend, kend);\n\n for(int64_t ii=node_begin;iirho[ii] = 0.0;\n\n ppc = compute_density_3d_chunk_loopswapped(node_begin,node_end,node_hash,box,h,\n lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho);\n pair_count += ppc;\n }\n }\n\n printf(\"pair_count = %ld\\n\",pair_count);\n\n return 0;\n}\n\n/*******************************************************************/\n\nint count_box_pairs(linkedListBox *box){\n int64_t pair_count = 0, particle_pair_count = 0;\n\n for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){\n int res;\n int64_t node_hash=-1,node_begin=0, node_end=0;\n int64_t nb_begin= 0, nb_end = 0;\n int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n\n if (kh_exist(box->hbegin, kbegin)){ // I have to call this!\n khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));\n\n node_hash = kh_key(box->hbegin, kbegin);\n node_begin = kh_value(box->hbegin, kbegin);\n node_end = kh_value(box->hend, kend);\n\n res = neighbour_hash_3d(node_hash,nblist,box->width,box);\n for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){\n if(nblist[j]>=0){\n //nb_hash = nblist[j];\n\n nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );\n nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );\n\n pair_count += 1;\n particle_pair_count += (node_end-node_begin)*(nb_end-nb_begin);\n }\n }\n }\n }\n\n printf(\"unique ordered particle_pair_count = %ld\\n\",particle_pair_count);\n\n return pair_count;\n}\n\nint setup_box_pairs(linkedListBox *box,\n int64_t *node_begin,int64_t *node_end,\n int64_t *nb_begin,int64_t *nb_end)\n{\n int64_t pair_count = 0;\n\n for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){\n int res;\n int64_t node_hash=-1;\n int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n\n if (kh_exist(box->hbegin, kbegin)){ // I have to call this!\n khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));\n\n node_hash = kh_key(box->hbegin, kbegin);\n\n res = neighbour_hash_3d(node_hash,nblist,box->width,box);\n for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){\n if(nblist[j]>=0){\n //nb_hash = nblist[j];\n\n node_begin[pair_count] = kh_value(box->hbegin, kbegin);\n node_end[pair_count] = kh_value(box->hend, kend);\n nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );\n nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );\n\n pair_count += 1;//(node_end-node_begin)*(nb_end-nb_begin);\n }\n }\n }\n //printf(\"thread %d - %lf %lf\\n\",i,lsph->rho[node_begin],lsph->rho[node_end-1]);\n }\n\n return pair_count;\n}\n\nint compute_density_3d_chunk_noomp_shift(int64_t node_begin, int64_t node_end,\n int64_t nb_begin, int64_t nb_end,double h,\n double* restrict x, double* restrict y,\n double* restrict z, double* restrict nu,\n double* restrict rho){\n const double inv_h = 1./h;\n const double kernel_constant = w_bspline_3d_constant(h);\n\n for(int64_t ii=node_begin;iirho[ii] = 0.0; \n\n #pragma omp parallel for num_threads(24) \n for(size_t i=0;ix,lsph->y,lsph->z,lsph->nu,local_rho);\n\n #pragma omp critical\n {\n for(size_t ii=node_begin[i];iirho[ii] += local_rho[ii - node_begin[i]];\n }\n }\n \n free(node_begin); \n free(node_end);\n free(nb_begin);\n free(nb_end);\n\n //for(int64_t i=0;irho[i]);\n\n return 0;\n}\n\n/*******************************************************************/\n/*******************************************************************/\n\n/*\n Pit from hell\n */\nint compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end,\n int64_t nb_begin, int64_t nb_end,double h,\n double* restrict x, double* restrict y,\n double* restrict z, double* restrict nu,\n double* restrict rhoi, double* restrict rhoj){\n const double inv_h = 1./h;\n\n for(int64_t ii=node_begin;ii=0){\n for(int64_t j=i+1;jhbegin); kbegin != kh_end(box->hbegin); kbegin++){\n int res;\n int64_t node_hash=-1;\n int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n\n if (kh_exist(box->hbegin, kbegin)){ // I have to call this!\n khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));\n\n node_hash = kh_key(box->hbegin, kbegin);\n\n res = neighbour_hash_3d(node_hash,nblist,box->width,box);\n for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){\n if(nblist[j]>=0){\n //nb_hash = nblist[j];\n\n if(kh_value(box->hbegin, kbegin) <= kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ))\n {\n node_begin[pair_count] = kh_value(box->hbegin, kbegin);\n node_end[pair_count] = kh_value(box->hend, kend);\n nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );\n nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );\n\n pair_count += 1;//(node_end-node_begin)*(nb_end-nb_begin);\n }\n }\n }\n }\n //printf(\"thread %d - %lf %lf\\n\",i,lsph->rho[node_begin],lsph->rho[node_end-1]);\n }\n\n return pair_count;\n}\n\nint compute_density_3d_symmetrical_load_ballance(int N, double h, SPHparticle *lsph, linkedListBox *box){\n int64_t *node_begin,*node_end,*nb_begin,*nb_end;\n int64_t max_box_pair_count = 0, particle_pair_count = 0;\n int64_t box_skip = 0;\n const double kernel_constant = w_bspline_3d_constant(h);\n\n max_box_pair_count = count_box_pairs(box);\n printf(\"max_box_pair_count = %ld\\n\",max_box_pair_count);\n \n node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));\n node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));\n nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));\n nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));\n\n max_box_pair_count = setup_unique_box_pairs(box,node_begin,node_end,nb_begin,nb_end);//setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end);\n printf(\"unique max_box_pair_count = %ld\\n\",max_box_pair_count);\n\n double avg_nb_len = 0.0;\n for(int64_t i=0;irho[ii] = 0.0; \n\n #pragma omp parallel for schedule(dynamic,5) proc_bind(master)\n for(size_t i=0;ix,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj);\n\n //compute_density_3d_chunk_symm_nlo(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h,\n // lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj);\n\n //compute_density_3d_chunk_symm_colapse(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h,\n // lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj);\n\n #pragma omp critical\n {\n\n for(size_t ii=node_begin[i];iirho[ii] += kernel_constant*local_rhoi[ii - node_begin[i]];\n }\n \n if(node_begin[i] != nb_begin[i])\n for(size_t ii=nb_begin[i];iirho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]];\n }\n }\n }\n\n free(node_begin); \n free(node_end);\n free(nb_begin);\n free(nb_end);\n \n return 0;\n}\n\nint compute_density_3d_symmetrical_lb_branching(int N, double h, SPHparticle *lsph, linkedListBox *box){\n int64_t *node_begin,*node_end,*nb_begin,*nb_end;\n int64_t max_box_pair_count = 0, particle_pair_count = 0;\n int64_t box_skip = 0;\n const double kernel_constant = w_bspline_3d_constant(h);\n\n max_box_pair_count = count_box_pairs(box);\n printf(\"max_box_pair_count = %ld\\n\",max_box_pair_count);\n \n node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));\n node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));\n nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));\n nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));\n\n max_box_pair_count = setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end);\n\n box_skip = unique_box_bounds(max_box_pair_count,node_begin,node_end,nb_begin,nb_end);\n\n for(int64_t i=0;i= 0)\n particle_pair_count += (node_end[i]-node_begin[i])*(nb_end[i]-nb_begin[i]);\n printf(\"unique unordered particle_pair_count = %ld\\n\",particle_pair_count);\n\n for(int64_t ii=0;iirho[ii] = 0.0; \n\n #pragma omp parallel for \n for(size_t i=0;ix,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj);\n\n #pragma omp critical\n {\n for(size_t ii=node_begin[i];iirho[ii] += kernel_constant*local_rhoi[ii - node_begin[i]];\n\n \n if(node_begin[i] != nb_begin[i])\n for(size_t ii=nb_begin[i];iirho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]];\n\n /*\n if(node_begin[i]!=nb_begin[i])\n for(size_t ii=nb_begin[i];iirho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]];*/\n }\n }\n \n free(node_begin); \n free(node_end);\n free(nb_begin);\n free(nb_end);\n\n return 0;\n}\n\n/*******************************************************************/\n/*******************************************************************/\n\n/*\nint compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end,\n int64_t nb_begin, int64_t nb_end,double h,\n double* restrict x, double* restrict y,\n double* restrict z, double* restrict nu,\n double* restrict rho)\n{\n const double inv_h = 1./h;\n const double kernel_constant = w_bspline_3d_constant(h);\n\n double rhoi[node_end-node_begin];\n double rhoj[nb_end-nb_begin];\n\n for(int64_t ii=0;iirho[ii] = 0.0;\n\n #pragma omp parallel for num_threads(24) \n for(size_t i=0;i nb_begin[i])\n continue; \n\n compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i],nb_begin[i],nb_end[i],\n h,lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho);\n }\n\n free(node_begin); \n free(node_end);\n free(nb_begin);\n free(nb_end);\n\n //for(int64_t i=0;irho[i]);\n\n return 0;\n}*/\n\n/*******************************************************************/\n/*******************************************************************/\n/*******************************************************************/\n\n#pragma omp declare simd\ndouble pressure_from_density(double rho){\n double p = cbrt(rho);\n p = 0.5*p*rho;\n return p;\n}\n\n#pragma omp declare simd\ndouble gamma_from_u(double ux,double uy,double uz){\n double gamma = 1.0;\n gamma += ux*ux;\n gamma += uy*uy;\n gamma += uz*uz;\n\n gamma = sqrt(gamma);\n\n return gamma;\n}\n\n\n/*\nint compute_force_3d(int N, double h, SPHparticle *lsph, linkedListBox *box){\n int err, res;\n double dist = 0.0;\n khiter_t kbegin,kend;\n int64_t node_hash=-1,node_begin=0, node_end=0;\n int64_t nb_hash=-1 , nb_begin= 0, nb_end = 0;\n int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n\n for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){\n \n if (kh_exist(box->hbegin, kbegin)){\n kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));\n node_hash = kh_key(box->hbegin, kbegin);\n node_begin = kh_value(box->hbegin, kbegin);\n node_end = kh_value(box->hend, kend);\n\n for(int64_t ii=node_begin;iirho[ii] = 0.0; \n\n res = neighbour_hash_3d(node_hash,nblist,box->width,box);\n for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){\n if(nblist[j]>=0){\n nb_hash = nblist[j];\n nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );\n nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );\n\n for(int64_t ii=node_begin;iix[i],lsph->y[i],lsph->z[i],\n lsph->x[j],lsph->y[j],lsph->z[j]);\n lsph->rho[ii] += (lsph->nu[jj])*(box->w(dist,h));\n }\n }\n }\n }\n }\n }\n\n return 0;\n} */\n\n/*\nint compute_force_3d(int N, double h, SPHparticle *lsph, linkedListBox *box){\n int err, res;\n double dist = 0.0;\n khiter_t kbegin,kend;\n int64_t node_hash=-1,node_begin=0, node_end=0;\n int64_t nb_hash=-1 , nb_begin= 0, nb_end = 0;\n int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n\n for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){\n \n if (kh_exist(box->hbegin, kbegin)){\n kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));\n node_hash = kh_key(box->hbegin, kbegin);\n node_begin = kh_value(box->hbegin, kbegin);\n node_end = kh_value(box->hend, kend);\n\n for(int64_t ii=node_begin;iiwidth,box);\n for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){\n if(nblist[j]>=0){\n nb_hash = nblist[j];\n nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );\n nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );\n\n for(int64_t ii=node_begin;ii\n#include \n#include \n#include \n\n#define NIED2_BIT_COUNT 30\n#define NIED2_NBITS (NIED2_BIT_COUNT+1)\n\n/* Z_2 field operations */\n#define NIED2_ADD(x,y) (((x)+(y))%2)\n#define NIED2_MUL(x,y) (((x)*(y))%2)\n#define NIED2_SUB(x,y) NIED2_ADD((x),(y))\n\nvoid get_primitive_polynomials(int dimension, int *degree_table, int *primitive_polynomials);\n\nstatic size_t nied2_state_size(unsigned int dimension);\nstatic int nied2_init(void * state, unsigned int dimension);\nstatic int nied2_get(void * state, unsigned int dimension, double * v);\n\n\nstatic const gsl_qrng_type nied2_type = \n{\n \"niederreiter-base-2\",\n 0,\n nied2_state_size,\n nied2_init,\n nied2_get\n};\n\nconst gsl_qrng_type * gsl_qrng_niederreiter_2 = &nied2_type;\n\n\ntypedef struct\n{\n unsigned int sequence_count;\n int *cj[NIED2_NBITS];\n int *nextq;\n} nied2_state_t;\n\n\nstatic size_t nied2_state_size(unsigned int dimension)\n{\n return sizeof(nied2_state_t) + /* the struct */ \n sizeof(int) * dimension * NIED2_NBITS + /* cj */ \n sizeof(int) * dimension; /* nextq */ \n}\n\n\n/* Multiply polynomials over Z_2.\n * Notice use of a temporary vector,\n * side-stepping aliasing issues when\n * one of inputs is the same as the output\n * [especially important in the original fortran version, I guess].\n */\nstatic void poly_multiply(\n const int pa[], int pa_degree,\n const int pb[], int pb_degree,\n int pc[], int * pc_degree, int max_degree\n )\n{\n int j, k;\n int *pt; \n int pt_degree; \n\n pt = (int *) malloc(sizeof(int) * (max_degree+1)); \n pt_degree = pa_degree + pb_degree;\n\n assert(pt_degree <= max_degree); \n\n for(k=0; k<=pt_degree; k++) {\n int term = 0;\n for(j=0; j<=k; j++) {\n const int conv_term = NIED2_MUL(pa[k-j], pb[j]);\n term = NIED2_ADD(term, conv_term);\n }\n pt[k] = term;\n }\n\n for(k=0; k<=pt_degree; k++) {\n pc[k] = pt[k];\n }\n for(k=pt_degree+1; k<=max_degree; k++) {\n pc[k] = 0;\n }\n\n *pc_degree = pt_degree;\n free(pt); \n}\n\n/* Calculate the values of the constants V(J,R) as\n * described in BFN section 3.3.\n *\n * px = appropriate irreducible polynomial for current dimension\n * pb = polynomial defined in section 2.3 of BFN.\n * pb is modified\n */\nstatic void calculate_v(\n const int px[], int px_degree,\n int pb[], int * pb_degree,\n int v[], int maxv, int max_degree, gsl_rng *rng\n )\n{\n const int nonzero_element = 1; /* nonzero element of Z_2 */\n\n /* The polynomial ph is px**(J-1), which is the value of B on arrival.\n * In section 3.3, the values of Hi are defined with a minus sign:\n * don't forget this if you use them later !\n */\n int *ph;\n /* int ph_degree = *pb_degree; */\n int bigm = *pb_degree; /* m from section 3.3 */\n int m; /* m from section 2.3 */\n int r, k, kj;\n\n ph = (int *) malloc(sizeof(int) * (max_degree+1)); \n\n for(k=0; k<=max_degree; k++) {\n ph[k] = pb[k];\n }\n\n /* Now multiply B by PX so B becomes PX**J.\n * In section 2.3, the values of Bi are defined with a minus sign :\n * don't forget this if you use them later !\n */\n poly_multiply(px, px_degree, pb, *pb_degree, pb, pb_degree, max_degree);\n m = *pb_degree;\n\n /* Now choose a value of Kj as defined in section 3.3.\n * We must have 0 <= Kj < E*J = M.\n * The limit condition on Kj does not seem very relevant\n * in this program.\n */\n /* Quoting from BFN: \"Our program currently sets each K_q\n * equal to eq. This has the effect of setting all unrestricted\n * values of v to 1.\"\n * Actually, it sets them to the arbitrary chosen value.\n * Whatever.\n */\n kj = gsl_rng_uniform_int(rng, bigm+1); \n\n /* Now choose values of V in accordance with\n * the conditions in section 3.3.\n */\n for(r=0; r= bigm) {\n for(r=kj+1; r> k) & 1;\n pb[k] = 0;\n }\n\n for (;kcj[r][i_dim] = term;\n }\n }\n free(primitive_polynomials);\n free(poly_degree); \n free(v); \n free(pb); \n free(px); \n gsl_rng_free(rng); \n return GSL_SUCCESS; \n}\n\n\nstatic int nied2_init(void * state, unsigned int dimension)\n{\n nied2_state_t * n_state = (nied2_state_t *) state;\n unsigned int i_dim, i_bits;\n int ret; \n\n if(dimension < 1) return GSL_EINVAL;\n\n for (i_bits=0; i_bitscj[i_bits] = \n (int *) ((char *) n_state + \n\t sizeof(nied2_state_t) + \n\t sizeof(int) * dimension * i_bits); \n\n n_state->nextq = \n (int *) ((char *) n_state + \n\t sizeof(nied2_state_t) + \n\t sizeof(int) * dimension * NIED2_NBITS); \n\n if ((ret = calculate_cj(n_state, dimension)) != GSL_SUCCESS)\n return ret; \n\n /* skip the '0th' state, which is 0 */ \n for(i_dim=0; i_dimnextq[i_dim] = n_state->cj[0][i_dim]; \n\n n_state->sequence_count = 1;\n\n return GSL_SUCCESS;\n}\n\n\nstatic int nied2_get(void * state, unsigned int dimension, double * v)\n{\n static const double recip = 1.0/(double)(1U << NIED2_NBITS); /* 2^(-nbits) */\n nied2_state_t * n_state = (nied2_state_t *) state;\n int r;\n int c;\n unsigned int i_dim;\n\n /* Load the result from the saved state. */\n for(i_dim=0; i_dimnextq[i_dim] * recip;\n }\n\n /* Find the position of the least-significant zero in sequence_count.\n * This is the bit that changes in the Gray-code representation as\n * the count is advanced.\n */\n r = 0;\n c = n_state->sequence_count;\n while(1) {\n if((c % 2) == 1) {\n ++r;\n c /= 2;\n }\n else break;\n }\n\n if(r >= NIED2_NBITS) return GSL_EFAILED; /* FIXME: better error code here */\n\n /* Calculate the next state. */\n for(i_dim=0; i_dimnextq[i_dim] ^= n_state->cj[r][i_dim];\n }\n\n n_state->sequence_count++;\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "4062f13ca7eee80719ec02f623dedc830264c2ad", "size": 10051, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/contrib/jsqrng_niederreiter-2.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/contrib/jsqrng_niederreiter-2.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/contrib/jsqrng_niederreiter-2.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": 25.9715762274, "max_line_length": 93, "alphanum_fraction": 0.6107849965, "num_tokens": 3154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893340314393, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5733140327343403}} {"text": "/*----------------------------------------------------------------------------\n/\n/ Filename: fits_wavelet.c\n/ Author: Jay Billings\n/ Author's email: jayjaybillings@gmail.com\n/ Description: This program will perform a Debauchies wavelet transform on \n/ an input image and turn off the wavelet coefficients up to \n/ a certain percentage of the total size.\n/\n/ Usage:\n/ ./fits_wavelet \n/\n/ should be an image in FITS format and \n/ should be a number between 0.0 and 1.0.\n/\n/ Output: \n/ filtered_\n/\n/ The output image is also in the FITS format and is readily\n/ viewable in FV, available from the NASA website, or the \n/ Sky Image Processor, useable as a java applet from Dr.\n/ John Simonetti, Virginia Tech,\n/ \n/ http://www.phys.vt.edu/~jhs/SIP.\n/\n/ This code requires the CFITSIO library and the GNU Scientific\n/ Library. Both are freely available on the internet. This code\n/ compiles fine with gcc-4.1.2 using\n/\n/ gcc -o fits_wavelet fits_wavelet.c -lm -lgsl -lgslcblas \n/ -lcfitiso\n/\n/ Copyright (c) 2008 Jay Jay Billings\n/\n/ This program is free software; you can redistribute it and/or modify\n/ it under the terms of the GNU General Public License as published by\n/ the Free Software Foundation; either version 2 of the License, or\n/ (at your option) any later version.\n/\n/ This program is distributed in the hope that it will be useful,\n/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n/ GNU General Public License for more details.\n/\n/ You should have received a copy of the GNU General Public License\n/ along with this program; if not, write to the Free Software\n/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n/\n/ The license is also available at:\n/\n/\t\thttp://www.gnu.org/copyleft/gpl.html .\n/\n/ Date: 2008/03/24\n/\n*///--------------------------------------------------------------------------\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid read_image(double *,char *,int []);\nvoid write_image(double *, char *, int []); \n\nint main(int argc, char *argv[]) {\n \n int i, j, size[3], a; \n double f, limit, *pixels, *pixels_copy;\n gsl_wavelet *w;\n gsl_wavelet_workspace *work; \n size_t *p;\n\n // Check to make sure that the inputs are OK.\n if (argc < 3) {\n printf(\"You need to specify a file! \\n\\nUsage: \");\n printf(\"\\t fits_wavelet \\n\\n\");\n exit(0);\n }\n f = atof(argv[2]);\n if (f >= 1.0) {\n printf(\"The limit must be between 0.0 and 1.0!\\n\\n\");\n printf(\"Try something else! (Like 0.85...)\\n\");\n exit(0);\n }\n\n // Allocate some storage arrays. The maximum size is currently\n // set at 1024*1024, or 2^20, initilized to zero.\n if (!(pixels = calloc(1024*1024,sizeof(double)))) {\n printf(\"Memory allocation error\\n\");\n exit(0);\n }\n if (!(pixels_copy = calloc(1024*1024,sizeof(double)))) {\n printf(\"Memory allocation error\\n\");\n exit(0);\n }\n if (!(p = malloc(1024*1024*sizeof(size_t)))) {\n printf(\"Memory allocation error\\n\");\n exit(0);\n }\n\n // Read the image into the pixels array.\n read_image(pixels,argv[1],size);\n \n // Allocate the wavelet workspace.\n w = gsl_wavelet_alloc(gsl_wavelet_daubechies,20);\n work = gsl_wavelet_workspace_alloc(1024*1024); \n\n // Perform the wavelet transfer.\n gsl_wavelet_transform_forward(w,pixels,1,1024,work);\n\n // Make a copy of the pixels array and sort it.\n for (i = 0; i < size[2]; ++i) {\n pixels_copy[i] = fabs(pixels[i]);\n \n } \n gsl_sort_index(p,pixels_copy,1,size[0]*size[1]);\n \n // Loop over the wavelet coefficients and turn them off\n // up to a certain limit.\n limit = (double) size[2] * f;\n for (i = 0; i < (int) limit; ++i) {\n pixels[p[i]] = 0.0;\n }\n\n // Perform the inverse transform.\n gsl_wavelet_transform_inverse(w,pixels,1,1024,work);\n\n // Write the image. \n write_image(pixels,argv[1],size);\n\n // Free all the memory and exit.\n gsl_wavelet_free(w);\n gsl_wavelet_workspace_free(work);\n free(pixels);free(pixels_copy);free(p);\n return 0;\n}\n\n// This subroutine was adapted from documentation provided on the FITSIO website.\nvoid read_image(double *pixels_vector, char *filename, int size[3])\n{\n fitsfile *fptr; /* FITS file pointer, defined in fitsio.h */\n int status = 0; /* CFITSIO status value MUST be initialized to zero! */\n int bitpix, naxis, ii, anynul,a;\n long naxes[2] = {1,1}, fpixel[2] = {1,1};\n double *pixels;\n char format[20], hdformat[20];\n\n /*if (argc != 2) {\n printf(\"Usage: imlist filename[ext][section filter] \\n\");\n printf(\"\\n\");\n printf(\"List the the pixel values in a FITS image \\n\");\n printf(\"\\n\");\n printf(\"Example: \\n\");\n printf(\" imlist image.fits - list the whole image\\n\");\n printf(\" imlist image.fits[100:110,400:410] - list a section\\n\");\n printf(\" imlist table.fits[2][bin (x,y) = 32] - list the pixels in\\n\");\n printf(\" an image constructed from a 2D histogram of X and Y\\n\");\n printf(\" columns in a table with a binning factor = 32\\n\");\n return(0);\n }*/\n\n if (!fits_open_file(&fptr, filename, READONLY, &status))\n {\n if (!fits_get_img_param(fptr, 2, &bitpix, &naxis, naxes, &status) )\n {\n if (naxis > 2 || naxis == 0)\n printf(\"Error: only 1D or 2D images are supported\\n\");\n else\n {\n /* get memory for 1 row */\n if (!(pixels = malloc(naxes[0] * sizeof(double)))) {\n printf(\"Memory allocation error\\n\");\n exit(0);\n }\n\n if (bitpix > 0) { /* set the default output format string */\n strcpy(hdformat, \" %7d\");\n strcpy(format, \" %7.0f\");\n } else {\n strcpy(hdformat, \" %15d\");\n strcpy(format, \" %15.5f\");\n }\n\n //printf(\"\\n \"); /* print column header */\n //for (ii = 1; ii <= naxes[0]; ii++)\n // printf(hdformat, ii);\n //printf(\"\\n\"); /* terminate header line */\n\n /* loop over all the rows in the image, top to bottom */\n a = 0;\n for (fpixel[1] = naxes[1]; fpixel[1] >= 1; fpixel[1]--)\n {\n if (fits_read_pix(fptr, TDOUBLE, fpixel, naxes[0], NULL,\n pixels, NULL, &status) ) /* read row of pixels */\n break; /* jump out of loop on error */\n\n // printf(\" %4d \\n\",fpixel[1]); /* print row number */\n for (ii = 0; ii < naxes[0]; ii++) {\n pixels_vector[a] = pixels[ii];\n// printf(format, pixels_vector[a]); /* print each value */\n // printf(\" %d\\n\",a); /* terminate line */\n ++a;\n }\n }\n size[0] = naxes[0];\n size[1] = naxes[1];\n size[2] = naxes[0]*naxes[1];\n free(pixels);\n }\n }\n fits_close_file(fptr, &status);\n }\n\n if (status) {\n fits_report_error(stderr, status); /* print any error message */\n exit(0);\n }\n //return(status);\n return;\n}\n\nvoid write_image(double *pixels_vector, char *f1, int size[3]) {\n\n fitsfile *infptr, *outfptr; /* FITS file pointer, defined in fitsio.h */\n int status = 0; /* CFITSIO status value MUST be initialized to zero! */\n int ii = 1;\n char f2[200];\n long size_l[2], fpixel[2] = {1,1};\n void *pix_ptr = &pixels_vector;\n\n size_l[0] = (long) size[0];\n size_l[1] = (long) size[1];\n\n sprintf(f2,\"filtered_%s\",f1);\n\n /* Create the output file */\n if (!fits_create_file(&outfptr, f2, &status) ) {\n if (!fits_create_img(outfptr,32,2,size_l,&status)) {\n if (!fits_write_pix(outfptr,TDOUBLE,fpixel,(long) size[2],pixels_vector \\\n ,&status)) {\n if (status == END_OF_FILE) status = 0;\n }\n //printf(\"Write status: %d \\n\",status); \n }\n fits_close_file(outfptr, &status);\n }\n\n return;\n}\n", "meta": {"hexsha": "30713b59b3364bdf697ad342ad205e9891aef586", "size": 8595, "ext": "c", "lang": "C", "max_stars_repo_path": "tools/fits_wavelet/fits_wavelet.c", "max_stars_repo_name": "jayjaybillings/jayjaybillings.github.io", "max_stars_repo_head_hexsha": "b4b74ea5f7e0a015897522e40d6366b7702a32cd", "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": "tools/fits_wavelet/fits_wavelet.c", "max_issues_repo_name": "jayjaybillings/jayjaybillings.github.io", "max_issues_repo_head_hexsha": "b4b74ea5f7e0a015897522e40d6366b7702a32cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/fits_wavelet/fits_wavelet.c", "max_forks_repo_name": "jayjaybillings/jayjaybillings.github.io", "max_forks_repo_head_hexsha": "b4b74ea5f7e0a015897522e40d6366b7702a32cd", "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": 34.1071428571, "max_line_length": 83, "alphanum_fraction": 0.5511343805, "num_tokens": 2302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5731803448046092}} {"text": "#include \n#define _USE_MATH_DEFINES\n#include \n#include \n\n#define HBARC 197.3269804 // MeV•fm\n#define MASS_TRITON 2808.92113298 // MeV\n#define MASS_DEUTERON 1875.61294257 // MeV\n#define MASS_NEUTRON 939.565420 // MeV\n#define MASS_ALPHA 3727.37940 // MeV\nconst double MU_D = MASS_TRITON*MASS_DEUTERON/(MASS_TRITON + MASS_DEUTERON);\nconst double MU_N = MASS_ALPHA*MASS_NEUTRON/(MASS_ALPHA + MASS_NEUTRON);\nconst double ALPHA = 1.0/137.035999084;\nconst double Q = 17.6;\nconst double J = 1.5;\nconst double J1 = 0.5;\nconst double J2 = 1.0;\n\ndouble relative_momentum(double e, double mu)\n{\n return sqrt(2*mu*e)/HBARC;\n}\n\ndouble sommerfeld(double e, double mu)\n{\n return ALPHA * sqrt(mu/(2*e));\n}\n\nvoid coulomb_functions(double* F, double* Fp, double* G, double* Gp, int l, double eta,\n double x)\n{\n int info;\n double exp_f, exp_g;\n gsl_sf_result f, fp, g, gp;\n info = gsl_sf_coulomb_wave_FG_e(eta, x, l, 0, &f, &fp, &g, &gp, &exp_f, &exp_g);\n // printf(\"%.4f %.4f\\n\", exp_f, exp_g);\n if (info == GSL_EOVRFLW) printf(\"overflow or underflow encountered\\n\");\n *F = f.val*exp(exp_f);\n *Fp = fp.val*exp(exp_f);\n *G = g.val*exp(exp_g);\n *Gp = gp.val*exp(exp_g);\n}\n\ndouble penetration_factor(int l, double eta, double x)\n{\n double F, Fp, G, Gp;\n coulomb_functions(&F, &Fp, &G, &Gp, l, eta, x);\n return x / (F*F + G*G);\n}\n\ndouble shift_factor(int l, double eta, double x)\n{\n double F, Fp, G, Gp;\n coulomb_functions(&F, &Fp, &G, &Gp, l, eta, x);\n return x * (F*Fp + G*Gp) / (F*F + G*G);\n}\n\ndouble Gamma_c(double gamma_c_sq, int l, double eta, double x)\n{\n return 2 * gamma_c_sq * penetration_factor(l, eta, x);\n}\n\ndouble Delta_c(double gamma_c_2, double k, double r, double Bc, int l, double eta)\n{\n\treturn -gamma_c_2 * (shift_factor(l, eta, k*r)-Bc);\n}\n\ndouble Sdn2(double energy, double e0, double Bd, double Bn, double gamma_d_2,\n double gamma_n_2, double kd, double ad, double kn, double an, double eta,\n double A)\n{\n\tdouble Gamma_d = Gamma_c(gamma_d_2, 0, eta, kd*ad);\n\tdouble Gamma_n = Gamma_c(gamma_n_2, 2, 0, kn*an);\n\tdouble Gamma = Gamma_d + Gamma_n;\n\tdouble Delta_d = Delta_c(gamma_d_2, kd, ad, Bd, 0, eta);\n\tdouble Delta_n = Delta_c(gamma_n_2, kn, an, Bn, 2, 0);\n\tdouble Delta = Delta_d + Delta_n;\n // printf(\"Sdn2: %.2e %.2e %.2e\\n\", Gamma_d, Gamma_n, Delta);\n\treturn Gamma_d*Gamma_n / ((e0+Delta-energy)*(e0+Delta-energy) + Gamma*Gamma/4) + \n\t 2.0/M_PI*A * penetration_factor(0, eta, kd*ad) * penetration_factor(0, 0.0, kn*an);\n}\n\n/*\nEvaluates the cross section (barn = 100fm^2) at energy en (MeV) with R-matrix parameters:\n\t\teB (MeV) where Bc = shift_factor(eB),\n\t\tgamma_d_2 (MeV) is the reduced deuteron width,\n\t\tgamma_n_2 (MeV) is the reduced neutron width,\n\t\tad (fm) is the deuteron channel radius,\n\t\tan (fm) is the neutron channel radius,\nand ue (MeV) is the electron screening potential.\n*/\ndouble cross_section(double en, double e0, double eB, double gamma_d_2,\n\t\tdouble gamma_n_2, double ad, double an, double ue, double A)\n{\n\tif (en < 0.0 || e0 < 0.0 || eB < 0.0 || gamma_d_2 < 0.0 ||\n\t\t\tgamma_n_2 < 0.0 || ad < 0.0 || an < 0.0 || ue < 0.0) {\n\t\treturn INFINITY;\n\t}\n\tdouble kd = relative_momentum(en, MU_D); // 1/fm\n\tdouble kn = relative_momentum(en+Q, MU_N); // 1/fm\n\tdouble kdB = relative_momentum(eB, MU_D); // 1/fm\n\tdouble knB = relative_momentum(eB+Q, MU_N); // 1/fm\n\tdouble eta = sommerfeld(en, MU_D); // dimensionless\n\tdouble etaB = sommerfeld(eB, MU_D); // dimensionless\n // printf(\"kdB = %.2e\\n\", kdB);\n\tdouble Bd = shift_factor(0, etaB, kdB*ad); // dimensionless\n\tdouble Bn = shift_factor(2, 0, knB*an); // dimensionless\n // printf(\"Bd = %.2e kdB = %.2e ad = %.2e\\n\", Bd, kdB, ad);\n\treturn exp(M_PI*eta*ue/en) * \n\t\t\tM_PI/(kd*kd) * (2.0*J+1.0)/((2.0*J1+1.0)*(2.0*J2+1.0)) *\n\t\t\tSdn2(en, e0, Bd, Bn, gamma_d_2, gamma_n_2, kd, ad, kn, an, eta, A) / 100;\n}\n\n/*\nEvaluates the S-factor (MeV•barn = MeV•100fm^2) at energy en (MeV) with R-matrix parameters:\n\t\teB (MeV) where Bc = shift_factor(eB),\n\t\tgamma_d_2 (MeV) is the reduced deuteron width,\n\t\tgamma_n_2 (MeV) is the reduced neutron width,\n\t\tad (fm) is the deuteron channel radius,\n\t\tan (fm) is the neutron channel radius,\nand ue (MeV) is the electron screening potential.\n*/\ndouble S_factor(double en, double e0, double eB, double gamma_d_2,\n\t\tdouble gamma_n_2, double ad, double an, double ue, double A)\n{\n\tif (en < 0.0 || e0 < 0.0 || eB < 0.0 || gamma_d_2 < 0.0 ||\n\t\t\tgamma_n_2 < 0.0 || ad < 0.0 || an < 0.0 || ue < 0.0) {\n\t\treturn INFINITY;\n\t}\n\tdouble kd = relative_momentum(en, MU_D); // 1/fm\n\tdouble kn = relative_momentum(en+Q, MU_N); // 1/fm\n\tdouble kdB = relative_momentum(eB, MU_D); // 1/fm\n\tdouble knB = relative_momentum(eB+Q, MU_N); // 1/fm\n\tdouble eta = sommerfeld(en, MU_D); // dimensionless\n\tdouble etaB = sommerfeld(eB, MU_D); // dimensionless\n // printf(\"kdB = %.2e\\n\", kdB);\n\tdouble Bd = shift_factor(0, etaB, kdB*ad); // dimensionless\n\tdouble Bn = shift_factor(2, 0, knB*an); // dimensionless\n // printf(\"Bd = %.2e kdB = %.2e ad = %.2e\\n\", Bd, kdB, ad);\n\treturn exp(M_PI*eta*ue/en) * en * exp(2*M_PI*eta) *\\\n\t\t\tM_PI/(kd*kd) * (2.0*J+1.0)/((2.0*J1+1.0)*(2.0*J2+1.0)) *\\\n\t\t\tSdn2(en, e0, Bd, Bn, gamma_d_2, gamma_n_2, kd, ad, kn, an, eta, A) / 100;\n}\n\ndouble S_factor_unitary_limit(double en, double ue)\n{\n\tif (en < 0.0 || ue < 0.0) {\n\t\treturn INFINITY;\n\t}\n\tdouble kd = relative_momentum(en, MU_D); // 1/fm\n\tdouble eta = sommerfeld(en, MU_D); // dimensionless\n\treturn exp(M_PI*eta*ue/en) * en * exp(2*M_PI*eta) *\\\n\t\t\tM_PI/(kd*kd) * (2.0*J+1.0)/((2.0*J1+1.0)*(2.0*J2+1.0)) * 1.0 / 100;\n}\n\n", "meta": {"hexsha": "c0bde800afc1ca1942108e0e50ab0d445a87ad85", "size": 5543, "ext": "c", "lang": "C", "max_stars_repo_path": "r-matrix-simple.c", "max_stars_repo_name": "odell/r-matrix-emulation", "max_stars_repo_head_hexsha": "fa02a3631d8798d7f85b68064ae98ab2e1ede88d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-25T19:25:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T19:25:06.000Z", "max_issues_repo_path": "r-matrix-simple.c", "max_issues_repo_name": "odell/r-matrix-emulation", "max_issues_repo_head_hexsha": "fa02a3631d8798d7f85b68064ae98ab2e1ede88d", "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": "r-matrix-simple.c", "max_forks_repo_name": "odell/r-matrix-emulation", "max_forks_repo_head_hexsha": "fa02a3631d8798d7f85b68064ae98ab2e1ede88d", "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.5320512821, "max_line_length": 92, "alphanum_fraction": 0.652173913, "num_tokens": 2126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.573036335531643}} {"text": "/* -*- Mode:C++; c-file-style:\"gnu\"; indent-tabs-mode:nil; -*- */\n/*\n * Copyright (c) 2010 The Boeing Company\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 version 2 as\n * published by the Free Software Foundation;\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Author: Gary Pei \n */\n\n/*\n * This program is used to generate plots found in the paper\n * G. Pei and Tom Henderson, \"Validation of ns-3 802.11b PHY model\",\n * available online at http://www.nsnam.org/~pei/80211b.pdf\n *\n * It can be compiled as a C program and relies on a library installation of\n * the GNU Scientific Library (gsl). To compile:\n * gcc 80211b.c -o 80211b -lm -lgsl -lgslcblas\n *\n * The executable output should be redirected into a text file 80211b.txt\n * ./80211b > 80211b.txt\n *\n * Then gnuplot can load the associated plot file which references 80211b.txt:\n * gnuplot 80211b.plt\n */\n\n#include \"math.h\"\n#include \"stdlib.h\"\n#include \"stdio.h\"\n#include \n#include \n#include \n#include \n#define min(a,b) ((a) < (b) ? (a) : (b))\n#define max(a,b) ((a) > (b) ? (a) : (b))\n#define WLAN_SIR_perfect 10.0 // if SIR > 10dB, perfect reception\n#define WLAN_SIR_impossible 0.1 // if SIR < -10dB, impossible to receive\n\n/**\n * \\ingroup wifi\n * \\defgroup wifi-test wifi module tests\n */\n\n\n/**\n * \\ingroup wifi-test\n * \\ingroup tests\n *\n * \\brief fn_parameter_t structure\n */\ntypedef struct fn_parameter_t\n{\n double beta; ///< beta\n double n; ///< n\n} fn_parameters;\n\ndouble QFunction (double x)\n{\n return 0.5 * erfc (x / sqrt (2.0));\n}\n\ndouble f (double x, void * params)\n{\n double beta = ((fn_parameters *) params)->beta;\n double n = ((fn_parameters *) params)->n;\n double f = pow ( 2 * gsl_cdf_ugaussian_P (x + beta) - 1, n - 1) * exp (-x * x / 2.0) / sqrt (2.0 * M_PI);\n return f;\n}\n\ndouble p_e2 (double e2)\n{\n double sep;\n double error;\n fn_parameters params;\n params.beta = sqrt (2.0 * e2);\n params.n = 8.0;\n gsl_integration_workspace* w = gsl_integration_workspace_alloc (1000);\n gsl_function F;\n F.function = &f;\n F.params = ¶ms;\n gsl_integration_qagiu (&F, -params.beta, 0, 1e-7, 1000, w, &sep, &error);\n gsl_integration_workspace_free (w);\n if (error == 0.0)\n {\n sep = 1.0;\n }\n return 1.0 - sep;\n}\n\ndouble p_e1 (double e1)\n{\n return 1.0 - pow ( 1.0 - p_e2 (e1 / 2.0), 2.0);\n}\n\ndouble DbToNoneDb (double x)\n{\n return pow (10.0, x / 10.0);\n}\n\ndouble NoneDbToDb (double x)\n{\n return 10.0 * log10 (x);\n}\n\ndouble DQPSKFunction (double x)\n{\n double pi = acos (-1.0);\n return ( (sqrt (2.0) + 1.0) / sqrt (8.0 * pi * sqrt (2.0))) * (1.0 / sqrt (x)) * exp ( -(2.0 - sqrt (2.0)) * x);\n}\n\ndouble Get80211bDsssDbpskBerIeee (double EcNc)\n{\n double ber;\n if (EcNc > WLAN_SIR_perfect)\n {\n ber = 0;\n }\n else if (EcNc < WLAN_SIR_impossible)\n {\n ber = 0.5;\n }\n else\n {\n ber = min (QFunction (sqrt (11.0 * EcNc)),0.5);\n }\n return ber;\n}\n\ndouble Get80211bDsssDbpskBer (double sinr)\n{\n double EbN0 = sinr * 22000000.0 / 1000000.0;\n double ber = 0.5 * exp (-EbN0);\n return ber;\n}\n\ndouble Get80211bDsssDqpskBerIeee (double EcNc)\n{\n double ber;\n if (EcNc > WLAN_SIR_perfect)\n {\n ber = 0;\n }\n else if (EcNc < WLAN_SIR_impossible)\n {\n ber = 0.5;\n }\n else\n {\n ber = min (QFunction (sqrt (5.5 * EcNc)),0.5);\n }\n return ber;\n}\n\ndouble Get80211bDsssDqpskBer (double sinr)\n{\n// 2 bits per symbol, 1 MSPS\n double EbN0 = sinr * 22000000.0 / 1000000.0 / 2.0;\n double ber = DQPSKFunction (EbN0);\n return ber;\n}\n\ndouble Get80211bDsssDqpskCCK5_5BerIeee (double EcNc)\n{\n double ber;\n if (EcNc > WLAN_SIR_perfect)\n {\n ber = 0.0;\n }\n else if (EcNc < WLAN_SIR_impossible)\n {\n ber = 0.5;\n }\n else\n {\n double pew = 14.0 * QFunction (sqrt (EcNc * 8.0)) + QFunction (sqrt (EcNc * 16.0));\n pew = min (pew, 0.99999);\n ber = 8.0 / 15.0 * pew;\n }\n return ber;\n}\n\ndouble Get80211bDsssDqpskCCK11BerIeee (double EcNc)\n{\n double ber;\n if (EcNc > WLAN_SIR_perfect)\n {\n ber = 0.0;\n }\n else if (EcNc < WLAN_SIR_impossible)\n {\n ber = 0.5;\n }\n else\n {\n double pew = 24.0 * QFunction (sqrt (EcNc * 4.0)) + 16.0 * QFunction (sqrt (EcNc * 6.0)) + 174.0 * QFunction (sqrt (EcNc * 8.0)) + 16.0 * QFunction (sqrt (EcNc * 10.0)) + 24.0 * QFunction (sqrt (EcNc * 12.0)) + QFunction (sqrt (EcNc * 16.0));\n pew = min (pew, 0.99999);\n ber = 128.0 / 255.0 * pew;\n }\n return ber;\n}\n\nint main (int argc, char * argv[])\n{\n double rss, sinr;\n double totalPkt = 200.0;\n//double noise = 1.552058; // (dB) this noise figure value corresponds to\n // -99 dBm noise floor reported in CMU paper\n double noise = 7; // (dB) this noise figure value corresponds to the\n // default in YansWifiPhy, and matches CMU testbed results\n double EcNc, EbN01, EbN02, EbN05, EbN011;\n double ieee1,ieee2,ieee5,ieee11;\n double numBits = (1024. + 40. + 14.) * 8.;\n double dbpsk,dqpsk,cck16,cck256,sepcck16,sepcck256;\n noise = DbToNoneDb (noise) * 1.3803e-23 * 290.0 * 22000000;\n for (rss = -102.0; rss <= -80.0; rss += 0.1)\n {\n sinr = DbToNoneDb (rss) / 1000.0 / noise;\n EcNc = sinr * 22000000.0 / 11000000.0; // IEEE sir\n EbN01 = sinr * 22000000.0 / 1000000.0;\n // 2 bits per symbol, 1 MSPS\n EbN02 = sinr * 22000000.0 / 1000000.0 / 2.0;\n EbN05 = sinr * 22000000.0 / 1375000.0 / 4.0;\n EbN011 = sinr * 22000000.0 / 1375000.0 / 8.0;\n // 1=rss, 2=EcNc, 3=EbN01, 4=EbN02, 5=EBN05, 6=EbN011\n printf (\"%g %g %g %g %g %g \", rss, NoneDbToDb (EcNc),\n NoneDbToDb (EbN01),NoneDbToDb (EbN02),\n NoneDbToDb (EbN05),NoneDbToDb (EbN011));\n ieee1 = Get80211bDsssDbpskBerIeee (EcNc);\n ieee2 = Get80211bDsssDqpskBerIeee (EcNc);\n ieee5 = Get80211bDsssDqpskCCK5_5BerIeee (EcNc);\n ieee11 = Get80211bDsssDqpskCCK11BerIeee (EcNc);\n // 7=ber_ieee1, 8=ber_ieee2, 9=ber_ieee5, 10=ber_ieee11\n printf (\" %g %g %g %g \", ieee1, ieee2,ieee5,ieee11);\n ieee1 = totalPkt * pow (1 - ieee1, numBits);\n ieee2 = totalPkt * pow (1 - ieee2, numBits);\n ieee5 = totalPkt * pow (1 - ieee5, numBits);\n ieee11 = totalPkt * pow (1 - ieee11, numBits);\n // 11=pkt_ieee1, 12=pkt_ieee2, 13=pkt_ieee5, 14=pkt_ieee11\n printf (\" %g %g %g %g \", ieee1, ieee2,ieee5,ieee11);\n dbpsk = Get80211bDsssDbpskBer (sinr);\n dqpsk = Get80211bDsssDqpskBer (sinr);\n cck16 = max (0, 8.0 / 15.0 * p_e2 (4.0 * EbN05 / 2.0));\n cck256 = max (0, 128.0 / 255.0 * p_e1 (8.0 * EbN011 / 2.0));\n // 15=ber_dbpsk, 16=ber_dqpsk, 17=ber_cck16, 18=ber_cck256\n printf (\" %g %g %g %g \", dbpsk, dqpsk,cck16,cck256);\n dbpsk = totalPkt * pow (1 - dbpsk,numBits);\n dqpsk = totalPkt * pow (1 - dqpsk,numBits);\n sepcck16 = p_e2 (4.0 * EbN05 / 2.0);\n sepcck256 = p_e1 (8.0 * EbN011 / 2.0);\n cck16 = totalPkt * pow (1.0 - sepcck16,numBits / 4.0);\n cck256 = totalPkt * pow (1.0 - sepcck256,numBits / 8.0);\n // 19=pkt_dbpsk, 20=pkt_dqpsk, 21=pkt_cck16, 22=pkt_cck256\n printf (\" %g %g %g %g \", dbpsk, dqpsk,cck16,cck256);\n // 23=sinr\n printf (\" %g \\n\",NoneDbToDb (sinr));\n }\n return 0;\n}\n", "meta": {"hexsha": "115fa8b5c1ffa5b48ee498f5582da57cb58f2f94", "size": 7781, "ext": "c", "lang": "C", "max_stars_repo_path": "ns-allinone-3.27/ns-3.27/src/wifi/test/80211b.c", "max_stars_repo_name": "zack-braun/4607_NS", "max_stars_repo_head_hexsha": "43c8fb772e5552fb44bd7cd34173e73e3fb66537", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2019-04-21T08:22:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:26:29.000Z", "max_issues_repo_path": "ns-allinone-3.27/ns-3.27/src/wifi/test/80211b.c", "max_issues_repo_name": "zack-braun/4607_NS", "max_issues_repo_head_hexsha": "43c8fb772e5552fb44bd7cd34173e73e3fb66537", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-04-19T16:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-22T13:18:32.000Z", "max_forks_repo_path": "ns-allinone-3.27/ns-3.27/src/wifi/test/80211b.c", "max_forks_repo_name": "zack-braun/4607_NS", "max_forks_repo_head_hexsha": "43c8fb772e5552fb44bd7cd34173e73e3fb66537", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T19:36:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T02:37:41.000Z", "avg_line_length": 28.9256505576, "max_line_length": 250, "alphanum_fraction": 0.6118750803, "num_tokens": 2989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5730319304202404}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"global.h\"\n#include \"eos_pres.h\"\n#include \"eos_rho.h\"\n#include \"param.h\"\n\n// the system of ODEs to be integrated\nint\nfunc (double r, const double y[], double f[], void *params)\n{\n struct param *myparams = (struct param *) params;\n double (*pres) (double, void *);\t// EOS pressure pointer\n double (*rho) (double, void *);\t// EOS density pointer\n pres = &eos_pres;\n rho = &eos_rho;\n\n// set a minimum pressure cutoff. if we don't, the ODE solver will wobble all\n// over the surface and crash, or if you make the error tolerance really strict\n// it'll integrate forever\n if (y[1] < 1.0e-9 * myparams->pinit)\n {\n if (myparams->single_star == 0)\n\t{\n\t printf (\"surface reached!\\n\");\n\t printf (\"%12s %12s %12s\\n\", \"R (km)\", \"M (M_sun)\",\n\t\t \"rho(0) (g/cm^3)\");\n\t}\n printf (\"%12le %12le %12le\\n\", r / 1.0e+5,\n\t y[0] / GSL_CONST_CGSM_SOLAR_MASS, myparams->rho_init);\n return GSL_EBADFUNC;\t// this flag tells GSL integrator to quit\n }\n // for a single star we can print M, P and rho as functions of r\n\n if (myparams->single_star == 0)\n {\n printf (\"%12le %12le %12le %12le\\n\", r / 1.0e+5,\n\t y[0] / GSL_CONST_CGSM_SOLAR_MASS, y[1], rho (y[1], myparams));\n }\n\n // mass conservation equation\n f[0] = 4.0 * M_PI * pow (r, 2.0) * rho (y[1], myparams);\n\n // TOV equation\n f[1] = -(GSL_CONST_CGSM_GRAVITATIONAL_CONSTANT / pow (r, 2.0))\n * (rho (y[1], myparams)\n + (y[1] / pow (GSL_CONST_CGSM_SPEED_OF_LIGHT, 2.0)))\n * (y[0] + 4 * M_PI * pow (r, 3.0)\n * y[1] / pow (GSL_CONST_CGSM_SPEED_OF_LIGHT, 2.0))\n / (1.0 - (2.0 * GSL_CONST_CGSM_GRAVITATIONAL_CONSTANT * y[0]\n\t / (pow (GSL_CONST_CGSM_SPEED_OF_LIGHT, 2.0) * r)));\n\n // ODEs tend to return NaNs at the same radius where P < 0\n if ((gsl_isnan (f[0]) || gsl_isnan (f[1])))\n {\n /* print values at the radius where ODEs diverge. this is almost\n always at the surface */\n printf (\"%12f %12f %12f\\n\", r / 1.0e+5,\n\t y[0] / GSL_CONST_CGSM_SOLAR_MASS, myparams->rho_init);\n return GSL_EBADFUNC;\n }\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "8f3338df32a5165b85010c3c42a6fd779a4bb22d", "size": 2207, "ext": "c", "lang": "C", "max_stars_repo_path": "src/func.c", "max_stars_repo_name": "bcfriesen/TOV_solver", "max_stars_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-11-14T02:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-14T02:27:58.000Z", "max_issues_repo_path": "src/func.c", "max_issues_repo_name": "bcfriesen/TOV_solver", "max_issues_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/func.c", "max_forks_repo_name": "bcfriesen/TOV_solver", "max_forks_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4558823529, "max_line_length": 79, "alphanum_fraction": 0.6198459447, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5730265857837358}} {"text": "//\n// gemmtest.c\n//\n// J. Makino\n// Time-stamp: <10/10/17 13:43:33 makino>\n#include \n#include \n#include \n#include \n#ifndef NOBLAS\n#include \n#endif\n#ifdef USEGDR\n#include \"gdrdgemm.h\"\n#endif\n\n#define FTYPE double\n#include \ntypedef double v2df __attribute__((vector_size(16)));\ntypedef union {v2df v; double s[2];}v2u;\n\n\n\n#ifndef USEGDR\nvoid gdrsetboardid(int boardid)\n{}\n#endif\n\n\nvoid matmul2_host(int n,\n\t\t FTYPE a[n][n],\n\t\t FTYPE b[n][n],\n\t\t FTYPE c[n][n])\n\n{\n int i, j, k;\n for(i=0;i m) iend = m;\n\t//\tfprintf(stderr, \"m, i, ifirst, iend = %d %d %d %d\\n\", m, ii, ifirst, iend);\n\tif (ifirst < m){\n\t matmul_for_nk16_0a(n1, a[ifirst], n2, b, n3, c[ifirst], iend-ifirst, n);\n\t}\n }\n\t\n}\n\nvoid matmul_for_nk32(int n1, double a[][n1],\n\t\t\t int n2, double b[][n2],\n\t\t\t int n3, double c[][n3],\n\t\t\t int m,\n\t\t\t int n)\n{\n int ii;\n int dm = (m+127)/128;\n dm*= 32;\n#pragma omp parallel for private(ii)\t schedule(static)\n for(ii=0;ii<4;ii++){\n\tint ifirst, iend;\n\tifirst = ii*dm;\n\tiend = ifirst+dm;\n\tif (iend > m) iend = m;\n\t//\tfprintf(stderr, \"m, i, ifirst, iend = %d %d %d %d\\n\", m, ii, ifirst, iend);\n\tif (ifirst < m){\n\t matmul_for_nk32_0(n1, a[ifirst], n2, b, n3, c[ifirst], iend-ifirst, n);\n\t}\n }\n\t\n}\n\n\n\n#ifndef USEGDR\nvoid gdrsetforceswapab(){}\nvoid gdrresetforceswapab(){}\nvoid gdrsetskipsendjmat(){};\nvoid gdrresetskipsendjmat(){}\nvoid gdrsetnboards(){}\nvoid set_matmul_msg_level(int level){}\n#endif\n\n\n\n#define N 1024\n#define K 16\nint main()\n{\n double a[N][K];\n double c[N][K];\n double b[K][K];\n int i,j;\n for(i=0;i\n#include \n#include \n\n#define\tMU\t0.5\t\t\t/* the MU for which we're computing coeffs */\n\n#define\tTs\t(1.0)\t\t\t/* sampling period \t\t*/\n#define\tB\t(1.0/(4*Ts))\t\t/* one-sided signal bandwidth \t*/\n//#define\tB\t(1.0/(8./3*Ts))\t\t/* one-sided signal bandwidth \t*/\n\nstatic unsigned global_n;\nstatic double *global_h;\ndouble\t\tglobal_mu = MU;\ndouble\t\tglobal_B = B;\n\ngsl_integration_workspace *global_gsl_int_workspace = NULL;\n\n/*\n * This function computes the difference squared between the ideal\n * interpolating differentiator frequency response at frequency OMEGA and the\n * approximation defined by the FIR coefficients in global_h[]\n *\n * See eqn (9-7), \"Digital Communication Receivers\", Meyr, Moeneclaey\n * and Fechtel, Wiley, 1998. for the jist of what going on here.\n *\n * See eqns (7.99) and (7.100), \"Discrete Time Signal Processing\",\n * Oppenheim, Alan V., Schafer, Ronald W., Prentice Hall 1989. for the\n * (non-bandlimited) ideal differentiator.\n *\n * Andy Walls derived the expression for the h[n] for the bandlimited\n * differentiator by performing an Inverse DTFT on the bandlimited ideal\n * response. (Integration by parts.)\n */\n\nstatic double\nintegrand (double omega, void *params)\n{\n double real_ideal;\n double real_approx;\n double real_diff;\n double imag_ideal;\n double imag_approx;\n double imag_diff;\n\n int\t i, n;\n int\t I1;\n double *h;\n\n /*\n * Ideal differentiator frequency response,\n * with freq modulation to effect a time shift left (advance),\n * and band limited to (-fc, fc).\n * N.B. fc is global_B, mu is global_mu, Fs is 1/Ts, 2*pi*f is omega.\n * fc and Fs are in Hz, and omega is in radians/second.\n *\n * H(f) = j*2*pi*f*Ts * exp(j*2*pi*f*Ts*mu) for |f| <= fc <= Fs/2\n */\n real_ideal = -omega * Ts * sin (omega * Ts * global_mu);\n imag_ideal = omega * Ts * cos (omega * Ts * global_mu);\n\n n = global_n;\n h = global_h;\n I1 = -(n / 2);\n\n real_approx = 0;\n imag_approx = 0;\n\n for (i = 0; i < n; i++){\n real_approx += h[i] * cos (-omega * Ts * (i + I1));\n imag_approx += h[i] * sin (-omega * Ts * (i + I1));\n }\n\n real_diff = real_ideal - real_approx;\n imag_diff = imag_ideal - imag_approx;\n\n return real_diff * real_diff + imag_diff * imag_diff;\n}\n\n/*\n * Integrate the difference squared over all frequencies of interest.\n */\ndouble\nc_fcn (double *x, int n)\n{\n gsl_function F;\n double result, error;\n\n F.function = integrand;\n F.params = NULL;\n\n assert ((n & 1) == 0);\t/* assert n is even */\n global_n = n;\n global_h = x;\n // global_B is fc, the cutoff frequency in Hz. It defaults to Fs/4.0.\n gsl_integration_qag(&F, -2 * M_PI * global_B, 2 * M_PI * global_B,\n 0.0, 1e-12, 1000, GSL_INTEG_GAUSS61,\n global_gsl_int_workspace, &result, &error);\n return result;\n}\n\n/* this is the interface expected by the calling fortran code */\n\ndouble\nobjective (double x[], int *ndim)\n{\n return c_fcn (x, *ndim);\n}\n\n/*\n * starting guess for optimization\n */\nvoid initpt (double x[], int ndim)\n{\n int i;\n double w_c;\n double start;\n double t;\n double arg;\n double denom;\n\n /* Bandlimited, time shifted, differentiator filter (infinitely long)\n *\n * Andy Walls derived the expression for the h[n] for the bandlimited\n * differentiator by performing an Inverse DTFT on the bandlimited ideal\n * response. (Integration by parts.)\n *\n * Ideal differentiator frequency response,\n * with freq modulation to effect a time shift left (advance),\n * and band limited to (-fc, fc).\n * N.B. fc is global_B, mu is global_mu, Fs is 1/Ts.\n * fc and Fs are in Hz, and omega is in radians/second.\n *\n * H(f) = j*2*pi*f*Ts * exp(j*2*pi*f*Ts*mu) for |f| <= fc <= Fs/2\n * H(f) = 0 for |f| > fc <= Fs/2\n *\n * Substituting normalized radian frequency, w, for 2*pi*f*Ts, we get:\n *\n * H(w) = j*w * exp(j*w*mu) for |w| <= w_c = 2*pi*fc*Ts <= pi\n * H(w) = 0 for |w| > w_c = 2*pi*fc*Ts <= pi\n *\n * and the Inverse Discrete Time Fourier Transform is:\n *\n * h[n] = (1/(2*pi)) * integral(-pi,pi)[ H(w)*exp(j*w*n)*dw ]\n *\n * Performing integration by parts of the above expression, using these hints:\n * integral [u*dv] = u*v - integral [v*du]\n * u = j*w\n * dv = exp(j*w*(n+mu))*dw\n *\n * We eventually get an infinitely long, but decaying impulse response:\n *\n * h[n] = (w_c/pi)/(n+mu) * [cos(pi*(w_c/pi)*(n+mu)) - sinc((w_c/pi)*(n+mu))]\n *\n * = [ w_c*(n+mu)*cos(w_c*(n+mu)) - sin(w_c*(n+mu)) ] / (pi*(n+mu)^2)\n *\n * w_c is the normalized radian cutoff frequency:\n * 2*pi*fc*Ts, with fc <= Fs/2 and Fs = 1/Ts, so w_c <= pi\n *\n * For the case of w_c = pi and mu = 0, the cos() term alternates\n * between +/- 1 and the sinc() term goes to 0 except at n == 0, so\n * we get the following:\n *\n * h[n] = (-1)^n / n for n != 0\n * = 0 for n == 0\n * or\n *\n * h[n] = ..., 1/5, -1/4, 1/3, -1/2, 1, 0, -1, 1/2, -1/3, 1/4, -1/5, ...\n *\n * Compare with:\n * Eqns (7.99) and (7.100), \"Discrete Time Signal Processing\",\n * Oppenheim, Alan V., Schafer, Ronald W., Prentice Hall 1989. for the\n * non-bandlimited (w_c = pi) ideal differentiator.\n */\n\n /* Truncated, bandlimited, time shifted, differentiator filter */\n w_c = 2.0 * M_PI * global_B * Ts;\n start = (double)(-ndim/2) + global_mu;\n\n for (i = 0; i < ndim; i++){\n t = (double)(i) + start;\n arg = w_c * t;\n denom = M_PI*t*t; /* always >= 0.0 */\n if (denom < 1e-9)\n x[i] = 0.0;\n else\n x[i] = (arg * cos(arg) - sin(arg))/denom;\n }\n}\n", "meta": {"hexsha": "367aeeb3566a547f9b4d574f3142b5dce48fddc5", "size": 6521, "ext": "c", "lang": "C", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/diff_objective_fct.c", "max_stars_repo_name": "v1259397/cosmic-gnuradio", "max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z", "max_issues_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/diff_objective_fct.c", "max_issues_repo_name": "v1259397/cosmic-gnuradio", "max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "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": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/diff_objective_fct.c", "max_forks_repo_name": "v1259397/cosmic-gnuradio", "max_forks_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "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.3302325581, "max_line_length": 80, "alphanum_fraction": 0.6192301794, "num_tokens": 2052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5727948648588792}} {"text": "static char help[] = \"ODE system solver example using TS. Models two\\n\"\n\"equal-mass balls (particles) moving in the plane with either no\\n\"\n\"connection (free) or connected by a spring. Solved via a Newtonian\\n\"\n\"formulation in cartesian coordinates (x,y) and velocities\\n\"\n\"(v=dx/dt,w=dy/dt). The system has dimension 8.\\n\\n\";\n\n// DEBUG check BDF2 convergence in free problem using Lagrangian formulation:\n//for T in 2 3 4 5 7 8 9 10 11 12; do ./loose -ts_type bdf -ts_rtol 1.0e-$T -ts_atol 1.0e-$T; done\n\n#include \n\ntypedef struct {\n PetscBool spring;\n PetscReal g, // m s-2; acceleration of gravity\n m, // kg; ball mass\n l, // m; spring or rod length\n k; // N m-1; spring constant\n} LooseCtx;\n\nextern PetscErrorCode SetInitial(Vec, LooseCtx*);\nextern PetscErrorCode FreeExact(Vec, PetscReal, Vec, LooseCtx*);\nextern PetscErrorCode NewtonRHSFcn(TS, PetscReal, Vec, Vec, void*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n PetscInt steps;\n PetscReal t0 = 0.0, tf = 2.0, dt = 0.1, errnorm;\n Vec u, u0, uexact;\n TS ts;\n LooseCtx user;\n char fstr[20] = \"free\";\n\n ierr = PetscInitialize(&argc, &argv, NULL, help); if (ierr) return ierr;\n\n user.spring = PETSC_FALSE;\n user.g = 9.81;\n user.m = 58.0e-3; // 58 g for a tennis ball\n user.l = 0.5; // spring length\n user.k = 20.0; // spring constant (ignored by free)\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD, \"lse_\", \"options for loose\",\n \"\"); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-g\", \"acceleration of gravity (m s-2)\",\n \"loose.c\", user.g, &user.g, NULL); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-k\", \"spring constant (N m-1)\", \"loose.c\",\n user.k, &user.k, NULL); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-l\", \"spring length (m)\", \"loose.c\",\n user.l, &user.l, NULL); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-m\", \"mass of each ball (kg)\", \"loose.c\",\n user.m, &user.m, NULL); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-spring\",\"spring case (not free)\",\n \"loose.c\", user.spring, &user.spring,\n NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n ierr = VecCreate(PETSC_COMM_WORLD,&u); CHKERRQ(ierr);\n ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);\n ierr = TSSetApplicationContext(ts,&user); CHKERRQ(ierr);\n ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);\n\n // set time axis\n ierr = TSSetTime(ts,t0); CHKERRQ(ierr);\n ierr = TSSetMaxTime(ts,tf); CHKERRQ(ierr);\n ierr = TSSetTimeStep(ts,dt); CHKERRQ(ierr);\n ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);\n\n // set up vecs and solver type\n ierr = VecSetSizes(u,PETSC_DECIDE,8); CHKERRQ(ierr);\n ierr = TSSetEquationType(ts, TS_EQ_ODE_EXPLICIT); CHKERRQ(ierr);\n ierr = TSSetRHSFunction(ts,NULL,NewtonRHSFcn,&user); CHKERRQ(ierr);\n ierr = TSSetType(ts,TSRK); CHKERRQ(ierr);\n\n // set-up of u, ts is complete\n ierr = VecSetFromOptions(u); CHKERRQ(ierr);\n ierr = TSSetFromOptions(ts); CHKERRQ(ierr);\n\n // set initial values and solve\n ierr = SetInitial(u, &user); CHKERRQ(ierr);\n ierr = TSSolve(ts, u); CHKERRQ(ierr);\n ierr = TSGetTime(ts, &tf); CHKERRQ(ierr);\n\n // numerical error in free case\n if (!user.spring) {\n ierr = VecDuplicate(u, &uexact); CHKERRQ(ierr);\n // get initial condition for evaluating exact solution\n ierr = VecDuplicate(u, &u0); CHKERRQ(ierr);\n ierr = SetInitial(u0, &user); CHKERRQ(ierr);\n ierr = FreeExact(u0, tf, uexact, &user); CHKERRQ(ierr);\n ierr = VecAXPY(u, -1.0, uexact); CHKERRQ(ierr); // u <- u - uexact\n ierr = VecNorm(u, NORM_INFINITY, &errnorm); CHKERRQ(ierr);\n VecDestroy(&u0); VecDestroy(&uexact);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"numerical error at tf in free problem: |u-uexact|_inf = %.5e\\n\",\n errnorm); CHKERRQ(ierr);\n }\n\n // report\n ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr);\n if (user.spring)\n strcpy(fstr, \"spring\");\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"%s problem solved to tf = %.3f (%d steps)\\n\",\n fstr, tf, steps); CHKERRQ(ierr);\n\n VecDestroy(&u); TSDestroy(&ts);\n return PetscFinalize();\n}\n\n/* Variable order used in the following functions:\nu[0] = q_1 (= x_1)\nu[1] = q_2 (= y_1)\nu[2] = q_3 (= x_2)\nu[3] = q_4 (= y_2)\nu[4] = v_1 (= dx_1/dt)\nu[5] = v_2 (= dy_1/dt)\nu[6] = v_3 (= dx_2/dt)\nu[7] = v_4 (= dy_2/dt)\n*/\n\nPetscErrorCode SetInitial(Vec u, LooseCtx *user) {\n /* Set initial conditions. */\n PetscErrorCode ierr;\n PetscReal *au;\n ierr = VecGetArray(u,&au); CHKERRQ(ierr);\n au[0] = 0.0; // q1 = x1\n au[1] = 1.0; // q2 = y1\n au[2] = 0.0; // q3 = x2\n au[3] = au[1] + user->l; // q4 = y2; satisfies (1)\n au[4] = 10.0; // v1\n au[5] = 10.0; // v2\n au[6] = 15.0; // v3\n au[7] = au[5]; // v4; satisfies (2)\n ierr = VecRestoreArray(u,&au); CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode FreeExact(Vec u0, PetscReal tf, Vec uexact, LooseCtx *user) {\n /* Exact solution based on parabolic motion. Problem\n m x'' = 0, x(0) = x0, x'(0) = v0\n m y'' = - m g, y(0) = y0, y'(0) = w0\n has solution\n x(t) = x0 + v0 t, x'(t) = v0,\n y(t) = y0 + w0 t - (g/2) t^2, y'(t) = w0 - g t */\n PetscErrorCode ierr;\n PetscReal *au0, *auex;\n if (user->spring) {\n SETERRQ(PETSC_COMM_SELF,7,\"exact solution only implemented for free\\n\");\n }\n ierr = VecGetArray(u0, &au0); CHKERRQ(ierr);\n ierr = VecGetArray(uexact, &auex); CHKERRQ(ierr);\n auex[0] = au0[0] + au0[4] * tf;\n auex[1] = au0[1] + au0[5] * tf - 0.5 * user->g * tf * tf;\n auex[2] = au0[2] + au0[6] * tf;\n auex[3] = au0[3] + au0[7] * tf - 0.5 * user->g * tf * tf;\n auex[4] = au0[4];\n auex[5] = au0[5] - user->g * tf;\n auex[6] = au0[6];\n auex[7] = au0[7] - user->g * tf;\n ierr = VecRestoreArray(u0, &au0); CHKERRQ(ierr);\n ierr = VecRestoreArray(uexact, &auex); CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode NewtonRHSFcn(TS ts, PetscReal t, Vec u, Vec G, void *ctx) {\n PetscErrorCode ierr;\n LooseCtx *user = (LooseCtx*)ctx;\n const PetscReal *au;\n PetscReal *aG;\n PetscReal dspring = 0.0, cspring = 0.0, Fx1, Fy1, Fx2, Fy2;\n\n PetscFunctionBeginUser;\n ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);\n ierr = VecGetArray(G,&aG); CHKERRQ(ierr);\n Fx1 = 0.0;\n Fy1 = - user->m * user->g;\n Fx2 = 0.0;\n Fy2 = - user->m * user->g;\n if (user->spring) {\n dspring = PetscSqrtReal( (au[0] - au[2]) * (au[0] - au[2])\n + (au[1] - au[3]) * (au[1] - au[3]) );\n if (dspring == 0.0) {\n SETERRQ(PETSC_COMM_SELF,1,\"exact ball collision (unlikely?)\\n\");\n }\n cspring = user->k * (1.0 - user->l / dspring);\n Fx1 -= cspring * (au[0] - au[2]);\n Fy1 -= cspring * (au[1] - au[3]);\n Fx2 += cspring * (au[0] - au[2]);\n Fy2 += cspring * (au[1] - au[3]);\n }\n aG[0] = au[4];\n aG[1] = au[5];\n aG[2] = au[6];\n aG[3] = au[7];\n aG[4] = Fx1 / user->m;\n aG[5] = Fy1 / user->m;\n aG[6] = Fx2 / user->m;\n aG[7] = Fy2 / user->m;\n ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr);\n ierr = VecRestoreArray(G,&aG); CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "516b1cf86cfd9fb10ac21021eb7458bd06aecf58", "size": 7735, "ext": "c", "lang": "C", "max_stars_repo_path": "petsc/loose.c", "max_stars_repo_name": "bueler/dae-examples", "max_stars_repo_head_hexsha": "fffd181c719e97fe1e28d01a41678357a9abde6a", "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": "petsc/loose.c", "max_issues_repo_name": "bueler/dae-examples", "max_issues_repo_head_hexsha": "fffd181c719e97fe1e28d01a41678357a9abde6a", "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": "petsc/loose.c", "max_forks_repo_name": "bueler/dae-examples", "max_forks_repo_head_hexsha": "fffd181c719e97fe1e28d01a41678357a9abde6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4825870647, "max_line_length": 98, "alphanum_fraction": 0.5544925663, "num_tokens": 2589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5727253401497463}} {"text": "/*solver/fixed_point.c\n* Solves a fixed point equation using\n* sequence acceleration.\n*\n* Author: Benjamin Vatter j.\n* email : benjaminvatterj@gmail.com\n* date: 15 August 2015\n*/\n\n#include \n#include \n#include \n#include \"fixed_point.h\"\n\n/*\n* Finds the fixed point of a function f\n* Translated from SciPy's fixed_point function\n*/\nvoid fixed_point(int n, ff_function *f, double *x0,\n double xtol, int maxiter, double *out)\n{\n\t//out = malloc(sizeof(double)*n);\n\tdouble *p = malloc(sizeof(double)*n);\n\tdouble *p1, *p2;\n\tdouble d;\n\tint pass;\n\tint i, j;\n\n\tfor (i=0; ifunction(out, f->params, p1);\n\t\tf->function(p1, f->params, p2);\n\n\t\tpass = 1;\n\t\tfor (j=0; j xtol){\n\t\t\t\tpass = 0;\n\t\t\t}\n\t\t\tif (out[j] != 0 && (p[j] - out[j])/out[j] > xtol){\n\t\t\t\tpass = 0;\n\t\t\t}\n\t\t\tout[j] = p[j];\n\t\t}\n\t\tif (pass == 1) {\n\t\t\tfree(p1);\n\t\t\tfree(p2);\n\t\t\tbreak;\n\t\t}\n\t\tif(i+1 >= maxiter){\n\t\t\tfree(p1);\n\t\t\tfree(p2);\n\t\t\tpass = -1;\n\t\t\tbreak;\n\t\t}\n\t\tfree(p1);\n\t\tfree(p2);\n\t}\n\n\tfree(p);\n\t// Free garbage result in case of no convergence\n\tif (pass == -1) {\n\t\tfree(out);\n\t}\n}\n", "meta": {"hexsha": "1c2c9a9bc56735e984aac4839f8fe516e44d208c", "size": 1395, "ext": "c", "lang": "C", "max_stars_repo_path": "fixed_point.c", "max_stars_repo_name": "benjaminvatterj/multidim_integration", "max_stars_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2", "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": "fixed_point.c", "max_issues_repo_name": "benjaminvatterj/multidim_integration", "max_issues_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2", "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": "fixed_point.c", "max_forks_repo_name": "benjaminvatterj/multidim_integration", "max_forks_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2", "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": 17.8846153846, "max_line_length": 55, "alphanum_fraction": 0.5455197133, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5726080309661736}} {"text": "/* randist/demo.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n\nint\nmain ()\n{\n gsl_rng * r ;\n\n int i, n = 10;\n double mu = 3.0;\n\n /* create a generator chosen by the environment variable GSL_RNG_TYPE */\n\n gsl_rng_env_setup();\n \n r = gsl_rng_alloc (gsl_rng_default);\n\n /* print n random variates chosen from the poisson distribution with\n mean parameter mu */\n\n for (i = 0; i < n; i++) \n {\n unsigned int k = gsl_ran_poisson (r, mu);\n \n printf(\" %u\", k);\n }\n\n printf(\"\\n\");\n}\n", "meta": {"hexsha": "0e7136833ed46e2a0f8213ab6bbbe88866479297", "size": 1349, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/randist/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/randist/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/randist/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": 26.98, "max_line_length": 81, "alphanum_fraction": 0.6849518162, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.572418836888224}} {"text": "/**\n * \\file include/shg/numalg.h\n * Numerical algorithms.\n */\n\n#ifndef SHG_NUMALG_H\n#define SHG_NUMALG_H\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace SHG {\n\n/**\n * Degree of polynomial in one variable.\n *\n * \\returns \\f$\\max \\{i: a_i \\neq 0, i = 0, \\ldots, m - 1 \\}\\f$ if it\n * exists, otherwise -1.\n *\n * \\throws std::invalid_argument if a.size() == 0 or a.size() > 32768.\n */\ntemplate